To build a RESTful API with routes in Laravel, you'll typically follow these steps:
Here's an example of building a RESTful API with routes for a User resource:
In your routes/api.php
file, define routes for the User resource:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::middleware('auth:api')->group(function () {
Route::prefix('users')->group(function () {
Route::get('/', [UserController::class, 'index']);
Route::post('/', [UserController::class, 'store']);
Route::get('/{user}', [UserController::class, 'show']);
Route::put('/{user}', [UserController::class, 'update']);
Route::delete('/{user}', [UserController::class, 'destroy']);
});
});
Create a UserController using the Artisan command:
php artisan make:controller UserController
Implement the methods in your UserController to handle CRUD operations:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
return User::all();
}
public function store(Request $request)
{
$user = User::create($request->all());
return response()->json($user, 201);
}
public function show(User $user)
{
return $user;
}
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 API using tools like Postman or by making HTTP requests to your API endpoints.
GET /api/users
: Get all users.POST /api/users
: Create a new user.GET /api/users/{user}
: Get a specific user.PUT /api/users/{user}
: Update a user.DELETE /api/users/{user}
: Delete a user.Ensure to replace /api
with your API prefix if you've defined one.
By following these steps, you'll have a basic RESTful API set up in your Laravel application.