Chapter 15 - CRUD using REST API
Hello Artisan's, welcome to the 15th chapter of being an Artisanary. In this chapter we'll show how to perform CRUD(create-read-update-delete) using REST API. REST means Representational State Transfer which only works with json object. So if you already complete the previous chapters/sections, then you're good to go, if not my recommendation would be please complete the previous chapters. Because we'll use the same old repository that we use from chapter 4.
Note: Tested on Laravel 10.0
First, we'll create a controller called BlogController.php where we'll write our logic or insert the data. So, fire the below command in terminal.
php artisan make:controller Api/BlogController -r
It'll create a file under app\Http\Controllers\Api called BlogController.php. Now open the file and replace with below codes.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\BlogRequest;
use App\Repositories\BlogRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class BlogController extends Controller
{
protected $blogRepository;
public function __construct(BlogRepository $blogRepository)
{
$this->blogRepository = $blogRepository;
}
public function index(): \Illuminate\Http\JsonResponse
{
try {
$data = [
'blogs' => $this->blogRepository->all()
];
return response()->json($data);
} catch (\Exception $e) {
return response()->json([
'error' => $e->getMessage()
]);
}
}
public function store(Request $request): \Illuminate\Http\JsonResponse
{
$validator = Validator::make($request->all(),[
'title' => 'required|string|max:255|unique:blogs,title',
'description' => 'required',
'image' => 'required'
]);
if($validator->fails()) {
return response()->json([
'error' => $validator->errors()
]);
}
try {
$data = $request->all();
$data['user_id'] = 1;
$this->blogRepository->store($data);
return response()->json([
'success' => 'Blog created successfully'
]);
} catch (\Exception $e) {
return response()->json([
'error' => $e->getMessage()
]);
}
}
public function show(string $id): \Illuminate\Http\JsonResponse
{
try {
$data = [
'edit' => $this->blogRepository->find($id)
];
return response()->json($data);
} catch (\Exception $e) {
return response()->json([
'error' => $e->getMessage()
]);
}
}
public function update(Request $request, $id): \Illuminate\Http\JsonResponse
{
$validator = Validator::make($request->all(),[
'title' => 'required|string|max:255|unique:blogs,title,'.$id,
'description' => 'required'
]);
if($validator->fails()) {
return response()->json([
'error' => $validator->errors()
]);
}
try {
$this->blogRepository->update($id, $request->all());
return response()->json([
'success' => 'Blog updated successfully'
]);
} catch (\Exception $e) {
return response()->json([
'error' => $e->getMessage()
]);
}
}
public function destroy(string $id): \Illuminate\Http\JsonResponse
{
try {
$this->blogRepository->destroy($id);
return response()->json([
'success' => 'Blog deleted successfully'
]);
} catch (\Exception $e) {
return response()->json([
'error' => $e->getMessage()
]);
}
}
}
Put the below route in routes/api.php
Route::resource('blogs', BlogController::class)->except(['edit','create','update']);
Route::post('blogs/{id}', [BlogController::class, 'update'])->name('blogs.update');
And it's done.
N.B. WE already said that REST is work using json formats only. So, if you look at our controllers methods, eveytime we return a json instead of any redirects or views. For more info about REST, see this doc.
So, it's time to say goodbye for today. We saw the CRUD operation with REST API and in the next chapter we'll test our CRUD operation with postman. And yes keep up to date with the Github repository. That's it for today. See you in my next chapter. Happy coding ๐.