Laravel 11 REST API CRUD With Best Practices - by Sandalanka - Mar, 2024 - Medium
Laravel 11 REST API CRUD With Best Practices - by Sandalanka - Mar, 2024 - Medium
Become a member
Creating a RESTful API CRUD application in Laravel 11 with best practices involves
several steps, including setting up your Laravel application, defining routes,
validation, model, resources, creating controllers, implementing the Repository
design pattern, and working with models. Here’s a step-by-step guide on how to
achieve this:
in the Interfaces, create a new file called ProductRepositoryInterface.php and add the
following code to it.
<?php
namespace App\Interfaces;
interface ProductRepositoryInterface
{
public function index();
public function getById($id);
public function store(array $data);
public function update(array $data,$id);
public function delete($id);
}
in the classes, create a new file called ProductRepository.php and add the following
code to it.
<?php
namespace App\Repository;
use App\Models\Product;
use App\Interfaces\ProductRepositoryInterface;
class ProductReposiotry implements ProductRepositoryInterface
{
public function index(){
return Product::all();
}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Interfaces\ProductRepositoryInterface;
use App\Repository\ProductReposiotry;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
$this->app->bind(ProductRepositoryInterface::class,ProductReposiotry::c
}
/**
* Bootstrap services.
*/
public function boot(): void
{
//
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
class StoreProductRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|ar
*/
public function rules(): array
{
return [
'name' => 'required',
'details' => 'required'
];
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
class UpdateProductRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|ar
*/
public function rules(): array
{
return [
'name' => 'required',
'details' => 'required'
];
}
<?php
namespace App\Classes;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Log;
class ApiResponseClass
{
public static function rollback($e, $message ="Something went wrong! Proces
DB::rollBack();
self::throw($e, $message);
}
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
namespace App\Http\Controllers;
use App\Models\Product;
use App\Http\Requests\StoreProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Interfaces\ProductRepositoryInterface;
use App\Classes\ResponseClass;
use App\Http\Resources\ProductResource;
use Illuminate\Support\Facades\DB;
class ProductController extends Controller
{
return ResponseClass::sendResponse(ProductResource::collection($data),'
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(StoreProductRequest $request)
{
$details =[
'name' => $request->name,
'details' => $request->details
];
DB::beginTransaction();
try{
$product = $this->productRepositoryInterface->store($details);
DB::commit();
return ResponseClass::sendResponse(new ProductResource($product),'
}catch(\Exception $ex){
return ResponseClass::rollback($ex);
}
}
/**
* Display the specified resource.
*/
Open in app
public function show($id)
{
1
$product
Search = $this->productRepositoryInterface->getById($id);
/**
* Show the form for editing the specified resource.
*/
public function edit(Product $product)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(UpdateProductRequest $request, $id)
{
$updateDetails =[
'name' => $request->name,
'details' => $request->details
];
DB::beginTransaction();
try{
$product = $this->productRepositoryInterface->update($updateDetail
DB::commit();
return ResponseClass::sendResponse('Product Update Successful','',
}catch(\Exception $ex){
return ResponseClass::rollback($ex);
}
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id)
{
$this->productRepositoryInterface->delete($id);
return ResponseClass::sendResponse('Product Delete Successful','',204);
}
}
To map each method defined in the controller to specific routes, add the following
code to routes/api.php.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
Route::apiResource('/products',ProductController::class);
Thanks…………
Written by Sandalanka
108 Followers
Sandalanka
15 1
Sandalanka
Sandalanka
routes/api.php
In Laravel 11, the API route file (api.php) is not visible by default, and you cannot define API
routes without publishing the API route…
Sandalanka
18
Awais
20
Lists
Staff Picks
634 stories · 946 saves
Self-Improvement 101
20 stories · 1727 saves
Productivity 101
20 stories · 1603 saves
Reza Khademi
115 1
Samuel Trstenský
81
Ritik
113 2
24 1