Learn Android with Java and Kotlin
 

The Middlewares: Restrict access to the ‘sell a product’ page

In this video, I shall introduce you to the concept of middlewares in Laravel. But why?….because we have to restrict an unauthenticated user from accessing the post ad page. So whenever a user clicks on the sell button from the menu, before even returning the view for the sell page we have to learn whether the user is logged in or not. If the user is already logged in we shall load the sell page, but if the user is not logged in we won’t allow him/her to post a product ad instead we’ll redirect him/her to the login screen. And we are going to do this with help of middleware.

Middleware in Laravel provides a mechanism for filtering HTTP requests. Laravel by default includes several useful middlewares. These middleware are located in the directory app/Http/Middleware. If you take a look inside this folder, you’ll find a middleware named Aunthenticate, this middleware, when applied to a route, redirects an unauthenticated user to the login screen if the user attempts to access that route. So we don’t even need to create our own middleware, this inbuilt middleware Authentication will work for us.

Now, the next question is how to use or apply a middleware to a route? Let me show you how…

Step 1: First, open the route file, web.php

Step 2: Take a look at the route for dashboard, notice how a middleware named auth is applied to this route. The function middleware() has been called and the key of the middleware enclosed in an array is passed to it. Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');

Step 3: Now, take a look at the file named kernel inside the folder app/Http. The middleware are registered inside this file. A key is associated with each of the middlewares. We can see that the key auth is assigned to the middleware Authenticate. And this is the one that is already applied to the dashboard route, we are going to apply the same to the sell route.

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}

Step 4: So back in our web.php file, call the function middleware() on the sell route and pass auth to it. We are not going to pass it in an array, as it is not mendatory. An array is required when you need to apply more than one middleware. Route::get('/sell',function(){ return view('sell'); })->middleware('auth');

Step 5: Now reload the website, log out if currently logged in. And try to access the route sell…. You’ll get redirected to the login screen. So we are done.

The complete code:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductsController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/



Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth'])->name('dashboard');

Route::get('/products',function(){
  return view('products');
});

Route::get('/product/{id}',function(){
  return view('product');
});

Route::get('/sell',function(){
  return view('sell');
})->middleware('auth');

Route::post('/product',
            [ProductsController::class,'store']);

require __DIR__.'/auth.php';

Conclusion: Middleware are powerful tool for controlling access to different features and parts of the website. We have just learned the basic concept with a simple usecase, but the possibilities are endless and we shall explore some more towards the end of the course. Next we shall retrieve the list of products from the database and display on the home page…. but wait, we still have this default welcome page as our home page. Let’s change this to make the products list page as the home page.

Inside the route file, remove the route for the welcome view, and change the uri of the products route to root. We can also delete the welcome.blade.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductsController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/



Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth'])->name('dashboard');

Route::get('/',function(){
  return view('products');
});

Route::get('/product/{id}',function(){
  return view('product');
});

Route::get('/sell',function(){
  return view('sell');
})->middleware('auth');

Route::post('/product',
            [ProductsController::class,'store']);

require __DIR__.'/auth.php';

Now enter bns.go on the browser… and the product list page is the home page now, perfect. Next, we shall start displaying the products from the database on this screen.

Leave a Reply

Your email address will not be published.