To make a controller RESTful in Laravel, you typically create a controller that corresponds to a resource (e.g., User) and utilize Laravel's resourceful routing. Here's how you can create a RESTful controller for a User model in Laravel:
Use the following Artisan command to generate a RESTful controller:
php artisan make:controller UserController --resource
This command will generate a UserController.php
file in the app/Http/Controllers
directory with RESTful methods.
In your routes/web.php
or routes/api.php
file, define the routes for your User resource using the Route::resource()
method:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::resource('users', UserController::class);
This single line of code generates all necessary routes for CRUD operations:
//php artisan route:list
GET /users index users.index
GET /users/create create users.create
POST /users store users.store
GET /users/{user} show users.show
GET /users/{user}/edit edit users.edit
PUT /users/{user} update users.update
DELETE /users/{user} destroy users.destroy
In your UserController.php
, implement the methods corresponding to the generated routes:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
return User::all();
}
public function create()
{
// Show the form for creating a new resource
}
public function store(Request $request)
{
$user = User::create($request->all());
return response()->json($user, 201);
}
public function show(User $user)
{
return $user;
}
public function edit(User $user)
{
// Show the form for editing the specified resource
}
public function update(Request $request, User $user)
{
$user->update($request->all());
return response()->json($user, 200);
}
public function destroy(User $user)
{
$user->delete();
return response()->json(null, 204);
}
}
You can now test your RESTful routes using tools like Postman or by accessing them directly in your browser. For example:
GET /users
POST /users
GET /users/{user}
PUT /users/{user}
DELETE /users/{user}
That's it! You now have a RESTful controller for your User resource in Laravel.