Assignments of Class 27: Advanced Laravel Concepts

Rashmi Mishra
0

 Assignments of Class 27: Advanced Laravel Concepts

Here are some assignments to help reinforce advanced Laravel concepts like routing, middleware, authentication, and authorization. Each assignment includes a solution and an explanation.


Assignment 1: Grouped Routing and Named Routes

Objective: Create a route group with a prefix and a named route for managing user profiles.

Instructions:

1.   Define a route group with the prefix user.

2.   Within the group, create a route to view the user profile (/user/profile) and name it profile.show.

3.   Use this named route in a controller method to redirect users to the profile page.

Solution:

php

Copy code

// web.php

 

use App\Http\Controllers\UserController;

 

// Define the route group with the prefix 'user'

Route::group(['prefix' => 'user'], function () {

    Route::get('/profile', [UserController::class, 'showProfile'])->name('profile.show');

});

In the UserController, redirect to the named route.

php

Copy code

// UserController.php

 

public function redirectToProfile()

{

    // Redirecting to the named route 'profile.show'

    return redirect()->route('profile.show');

}

Explanation:
The
Route::group function groups routes with the prefix user, so the full URL for the profile route becomes /user/profile. Naming the route as profile.show allows us to reference it easily across the application. In redirectToProfile, we use redirect()->route('profile.show') to navigate to this route, making our code cleaner and more manageable.


Assignment 2: Applying Middleware to Protect Routes

Objective: Create a custom middleware to restrict access to certain routes based on the user role.

Instructions:

1.   Generate middleware called CheckAdmin.

2.   In the middleware, check if the authenticated user has an is_admin attribute set to true.

3.   Apply this middleware to an admin dashboard route, redirecting users who are not admins to the homepage.

Solution:

1.   Generate middleware:

bash

Copy code

php artisan make:middleware CheckAdmin

2.   Implement the middleware in app/Http/Middleware/CheckAdmin.php:

php

Copy code

// CheckAdmin.php

 

public function handle($request, Closure $next)

{

    // Check if the authenticated user is an admin

    if (!auth()->user() || !auth()->user()->is_admin) {

        // Redirect to homepage if not an admin

        return redirect('/');

    }

 

    return $next($request);

}

3.   Register middleware in app/Http/Kernel.php:

php

Copy code

protected $routeMiddleware = [

    'checkAdmin' => \App\Http\Middleware\CheckAdmin::class,

];

4.   Apply middleware to the route:

php

Copy code

// web.php

 

Route::get('/admin/dashboard', [AdminController::class, 'index'])->middleware('checkAdmin');

Explanation:
The
CheckAdmin middleware checks if the authenticated user has the is_admin attribute. If the user is not an admin, they are redirected to the homepage (/). Applying this middleware to the /admin/dashboard route ensures that only admins can access this route, enhancing security.


Assignment 3: Setting Up Authentication with Laravel Breeze

Objective: Set up user authentication in a Laravel project using Laravel Breeze.

Instructions:

1.   Install and set up Laravel Breeze.

2.   Configure the routes for login, registration, and password reset.

3.   Redirect authenticated users to a dashboard page after login.

Solution:

1.   Install Laravel Breeze:

bash

Copy code

composer require laravel/breeze --dev

php artisan breeze:install

npm install && npm run dev

php artisan migrate

2.   Update HomeController.php to handle redirection after login:

php

Copy code

// HomeController.php

 

public function index()

{

    // Redirect to dashboard if authenticated

    return auth()->check() ? redirect()->route('dashboard') : view('welcome');

}

3.   In web.php, define the dashboard route:

php

Copy code

Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth')->name('dashboard');

Explanation:
Laravel Breeze provides authentication scaffolding for login, registration, and password management. After logging in, users are redirected to the
dashboard route. This setup provides a quick and easy way to implement authentication in Laravel.


Assignment 4: Implementing Authorization with Policies

Objective: Create a policy to control access to editing posts. Only the user who created a post should be able to edit it.

Instructions:

1.   Create a policy for the Post model.

2.   Define an update method in the policy that checks if the current user is the post owner.

3.   Use this policy in the controller to restrict access to the post edit page.

Solution:

1.   Generate a policy:

bash

Copy code

php artisan make:policy PostPolicy

2.   Define the update method in PostPolicy.php:

php

Copy code

// PostPolicy.php

 

public function update(User $user, Post $post)

{

    // Allow update only if the user is the post owner

    return $user->id === $post->user_id;

}

3.   Register the policy in AuthServiceProvider.php:

php

Copy code

protected $policies = [

    Post::class => PostPolicy::class,

];

4.   Use the policy in the controller:

php

Copy code

// PostController.php

 

public function edit(Post $post)

{

    $this->authorize('update', $post);

 

    // Render the edit view if authorized

    return view('posts.edit', compact('post'));

}

Explanation:
The
PostPolicy contains an update method that checks if the logged-in user is the post owner by comparing their id with post.user_id. In PostController, calling $this->authorize('update', $post) ensures only the post owner can access the edit page.


Assignment 5: Route Caching for Improved Performance

Objective: Enable route caching in your Laravel application to improve performance.

Instructions:

1.   Cache the routes in your Laravel application.

2.   Test the application to ensure that the cached routes are functioning as expected.

3.   Clear the route cache if you add new routes or make changes.

Solution:

1.   Cache routes:

bash

Copy code

php artisan route:cache

2.   Clear route cache (when necessary):

bash

Copy code

php artisan route:clear

Explanation:
Route caching compiles all of the application's routes into a single file, which speeds up performance. After caching, you need to clear the route cache if you make any changes to your routes. This optimization is particularly beneficial for larger applications in production.

 

Post a Comment

0Comments

Post a Comment (0)