Lecture notes of Class 27: Advanced Laravel Concepts
Objective:
- Explore advanced Laravel
features such as routing and middleware.
- Implement user authentication
and authorization.
Outcome:
- Students will be able to
configure routing, apply middleware, and set up authentication and
authorization in Laravel.
Introduction
In this class, we dive into some of Laravel's advanced
features that enhance security, streamline route management, and control user
access to resources. By understanding how to work with middleware, routing
configurations, and authentication/authorization, developers can create secure
and structured applications.
1. Routing in Laravel
1.1 Route Groups
Route groups allow you to organize routes that share
attributes, such as middleware, prefixes, or namespaces. This is particularly
useful when you have several routes that should share common behavior or
structure.
Example: Basic Route Group
php
Copy code
Route::group(['prefix' => 'admin'], function () {
Route::get('/dashboard',
[AdminController::class, 'dashboard']);
Route::get('/users',
[AdminController::class, 'listUsers']);
});
Here, all routes within this group are prefixed with
"admin." So, the actual URLs are /admin/dashboard and /admin/users.
1.2 Route Prefixes and Namespaces
- Prefix: Adds a common path segment to
all routes within the group.
- Namespace: Groups routes by associating
them with a specific namespace, usually linked to a specific controller.
Example: Prefix and Namespace
php
Copy code
Route::group(['prefix' => 'api', 'namespace' => 'App\Http\Controllers\Api'],
function () {
Route::get('/posts',
'PostController@index');
});
This example specifies a prefix (api) and a namespace (App\Http\Controllers\Api),
so the route /api/posts maps to the index method of PostController.
1.3 Named Routes
Named routes make it easier to reference specific routes in
your application, particularly useful for redirects or URL generation.
Example: Defining and Using Named Routes
php
Copy code
// Defining a named route
Route::get('/profile', [UserController::class, 'profile'])->name('profile');
// Using the named route
return redirect()->route('profile');
2. Middleware in Laravel
Middleware acts as a filter for incoming HTTP requests,
allowing developers to control access and manage behavior globally or for
specific routes.
2.1 Applying Middleware to Routes
Middleware can be applied to individual routes, route groups,
or even globally to the entire application. Common middleware includes
authentication (auth) and guest middleware (guest), among others.
Example: Applying Middleware to Routes
php
Copy code
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth');
2.2 Creating Custom Middleware
Laravel allows you to create custom middleware for handling
specific logic on requests.
Steps to Create Middleware:
1. Generate middleware using Artisan:
bash
Copy code
php artisan make:middleware CheckAdmin
2. Define the middleware logic in app/Http/Middleware/CheckAdmin.php:
php
Copy code
public function handle($request, Closure $next)
{
if (!auth()->user()
|| !auth()->user()->isAdmin()) {
return redirect('home');
}
return $next($request);
}
3. Register middleware in app/Http/Kernel.php.
4. Apply it to routes:
php
Copy code
Route::get('/admin', [AdminController::class, 'index'])->middleware('checkAdmin');
2.3 Global Middleware
Global middleware is applied to all routes in the
application. It is useful for tasks such as logging or managing sessions.
3. Authentication in Laravel
Authentication verifies the identity of users accessing the
application. Laravel provides tools for handling user login, registration, and
password management with ease.
3.1 Setting up Authentication with Breeze or Jetstream
To quickly set up authentication in Laravel, you can use Laravel
Breeze or Jetstream packages, both of which offer pre-built
authentication scaffolding.
Using Laravel Breeze
1. Install Breeze:
bash
Copy code
composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate
2. This generates the routes, views, and
controllers for user registration, login, and password reset.
3.2 Authentication Guards
In Laravel, guards define how users are authenticated for
each request.
- Web Guard: Used for standard web-based
authentication.
- API Guard: Used for token-based
authentication, usually for APIs.
4. Authorization in Laravel
Authorization controls user permissions within the
application. Laravel provides two main ways to manage authorization: Gates
and Policies.
4.1 Gates
Gates are simple, closure-based authorization checks. They
are typically defined in the App\Providers\AuthServiceProvider.
Example: Defining a Gate
php
Copy code
Gate::define('view-dashboard', function ($user) {
return $user->isAdmin();
});
Use the gate in a controller or route:
php
Copy code
if (Gate::allows('view-dashboard')) {
// The current user
can view the dashboard
}
4.2 Policies
Policies provide a structured way of managing authorization
logic and are useful when dealing with complex permissions.
Creating a Policy
1. Generate a policy:
bash
Copy code
php artisan make:policy PostPolicy
2. Define methods for specific actions,
like view, update, and delete.
Example: Post Policy
php
Copy code
public function update(User $user, Post $post)
{
return $user->id
=== $post->user_id;
}
3. Register the policy in AuthServiceProvider.
4. Apply policy checks:
php
Copy code
if ($user->can('update', $post)) {
// The user can
update the post
}
Summary
- Routing: Organizing routes into groups,
applying prefixes, and creating named routes.
- Middleware: Applying and creating
middleware for access control and filtering requests.
- Authentication: Setting up user authentication
with packages like Breeze and managing guards.
- Authorization: Using gates and policies to
control user permissions.
By mastering these advanced features, students will gain the
ability to create secure, organized, and user-centric applications in Laravel.