<?php
namespace AppHttpControllers;
use AppModelsPost;
use AppHttpRequestsStorePostRequest;
use AppHttpRequestsUpdatePostRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesGate;
use IlluminateSupportFacadesStorage;
use IlluminateSupportStr;
class PostController extends Controller
{
public function __construct()
{
$this->middleware('auth')->except(['index','show']);
}
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
//
return redirect()->route('index');
}
/**
* Show the form for creating a new resource.
*
* @return IlluminateHttpResponse
*/
public function create()
{
//
return view('post.create');
}
/**
* Store a newly created resource in storage.
*
* @param AppHttpRequestsStorePostRequest $request
* @return IlluminateHttpResponse
*/
public function store(StorePostRequest $request)
{
$newName = "cover_".uniqid()."_".$request->file('cover')->extension();
$request->file('cover')->storeAs("public/cover",$newName);
$post = new Post();
$post->title = $request->title;
$post->slug = Str::slug($request->title);
$post->description = $request->description;
$post->excerpt = Str::words($request->description,50);
$post->cover = $newName;
$post->user_id = Auth::id();
$post->save();
return redirect()->route("index")->with('status','Post Created');
return $request;
}
/**
* Display the specified resource.
*
* @param AppModelsPost $post
* @return IlluminateHttpResponse
*/
public function show(Post $post)
{
return redirect()->route('post.detail',$post->slug);
}
/**
* Show the form for editing the specified resource.
*
* @param AppModelsPost $post
* @return IlluminateHttpResponse
*/
public function edit(Post $post)
{
//
Gate::authorize('update',$post);
return view('post.edit',compact('post'));
}
/**
* Update the specified resource in storage.
*
* @param AppHttpRequestsUpdatePostRequest $request
* @param AppModelsPost $post
* @return IlluminateHttpResponse
*/
public function update(UpdatePostRequest $request, Post $post)
{
$post->title = $request->title;
$post->slug = Str::slug($request->title);
$post->description = $request->description;
$post->excerpt = Str::words($request->description,50);
if($request->hasFile('cover')){
// delete old cover
Storage::delete("public/cover/".$post->cover);
// upload new cover
$newName = "cover_".uniqid()."_".$request->file('cover')->extension();
$request->file('cover')->storeAs("public/cover",$newName);
// save to table
$post->cover = $newName;
}
$post->update();
return redirect()->route('post.detail',$post->slug)->with('status','Post Updated');
}
/**
* Remove the specified resource from storage.
*
* @param AppModelsPost $post
* @return IlluminateHttpResponse
*/
public function destroy(Post $post)
{
//
Gate::authorize('delete',$post);
Storage::delete("public/cover/".$post->cover);
$post->delete();
return redirect()->route('index');
}
}