Last active
February 21, 2021 06:31
-
-
Save silkyland/07ec293480a46771e2c8436a67decc61 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\Models\Post; | |
use Illuminate\Http\Request; | |
class PostController extends Controller | |
{ | |
public function apiIndex() | |
{ | |
$posts = Post::with('user', 'category')->get(); | |
return response()->json($posts); | |
} | |
public function apiStore(Request $request) | |
{ | |
$request->validate([ | |
'title' => 'required', | |
'category_id' => 'required', | |
'description' => 'required|min:10' | |
]); | |
$path = "https://via.placeholder.com/720x480"; | |
if ($request->hasFile('thumbnail')) { | |
$path = $request->file('thumbnail')->store('thumbnail'); | |
} | |
$post = new Post(); | |
$post->user_id = $request->user()->id; | |
$post->category_id = $request->input('category_id'); | |
$post->thumbnail = $path; | |
$post->title = $request->input('title'); | |
$post->description = $request->input('description'); | |
$post->save(); | |
return response()->json($post); | |
} | |
public function apiPost($id) | |
{ | |
$post = Post::with('user', 'category')->find($id); | |
return response()->json($post); | |
} | |
public function apiUpdate(Request $request, $id) | |
{ | |
$request->validate([ | |
'title' => 'required', | |
'category_id' => 'required', | |
'description' => 'required|min:10' | |
]); | |
$post = Post::with('user', 'category')->find($id); | |
$path = $post->thumbnail; | |
if ($request->hasFile('thumbnail')) { | |
$path = $request->file('thumbnail')->store('thumbnail'); | |
} | |
$post->user_id = $request->user()->id; | |
$post->category_id = $request->input('category_id'); | |
$post->thumbnail = $path; | |
$post->title = $request->input('title'); | |
$post->description = $request->input('description'); | |
$post->save(); | |
return response()->json($post); | |
} | |
public function apiDestroy($id) | |
{ | |
$post = Post::find($id); | |
$post->delete(); | |
return response()->json(['message' => 'Delete Post successfuly']); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment