LARAVEL

Creating a route using a closure


In Laravel, you can define routes using closures directly in your routes/web.php or routes/api.php file. Closures allow you to define route logic inline without the need for a controller. Here's how you can create a route using a closure:

use Illuminate\Support\Facades\Route;
Route::get('/example', function () {
    return 'This is an example route using a closure!';
});

 

Crud API Example using User Model 

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

// Get all users
Route::get('/users', function () {
    $users = User::all();
    return response()->json($users);
});

// Get a specific user by ID
Route::get('/users/{id}', function ($id) {
    $user = User::find($id);
    return response()->json($user);
});

// Create a new user
Route::post('/users', function (Request $request) {
    $user = new User();
    $user->name = $request->input('name');
    $user->email = $request->input('email');
    $user->password = bcrypt($request->input('password'));
    $user->save();
    return response()->json($user);
});

// Update an existing user
Route::put('/users/{id}', function (Request $request, $id) {
    $user = User::find($id);
    $user->name = $request->input('name');
    $user->email = $request->input('email');
    $user->password = bcrypt($request->input('password'));
    $user->save();
    return response()->json($user);
});

// Delete a user
Route::delete('/users/{id}', function ($id) {
    $user = User::find($id);
    $user->delete();
    return response()->json(['message' => 'User deleted successfully']);
});

In the above code:

  • Route::get() defines a route for handling GET requests.
  • Route::post() defines a route for handling POST requests.
  • Route::put() defines a route for handling PUT requests.
  • Route::delete() defines a route for handling DELETE requests.

Each route has a closure function that performs specific actions like fetching all users, fetching a specific user by ID, creating a new user, updating an existing user, and deleting a user.

Please note that for the sake of simplicity, this example assumes that you're working with a User model with name, email, and password attributes. Ensure that you have imported the User model at the top of your routes file (use App\Models\User;). Also, consider adding validation and error handling to these routes for production use.

 


LARAVEL