Article

Middlewares in laravel

Jan 19, 2020 2,961
Middlewares in laravel

Middlewares are important for any laravel app, say that you want to make an admin page for admin users only, or accept the post only from an activated user, luckily, this is pretty easy in laravel.

Using the Middlewares:

There are two basic ways to use middlewares in laravel:

  1. With Routing:
// For multiple routes:
Route::group(['middleware' => ['middleware_name']], function()
{ //put your routes here}
// OR for a single route:
Route::get('/', function () {})->middleware('middleware_name');
  1. With _construct:
// For All functions in the controller:
public function __construct()
{ 
$this->middleware('middleware_name');
}
// Or for only some of them:
public function __construct()
{ 
$this->middleware('middleware_name',
['only' =>['create','store','edit','update']]);
}
// Or except some of them:
public function __construct()
{
$this->middleware('middleware_name',
['except' =>['index','show']]);
}

Making a middleware:

Let’s make a middleware “isActivated” that will check the if the user has activated his account or not (Assuming that we have a Boolean column “is_activated” in our users table):

First, we will make a middleware named “IsActivated” by running this command:

php artisan make:middleware IsActivated

This will generate a middleware in “ /app/Http/Middleware/”

Let’s take a look at this middleware:

namespace App\Http\Middleware;
use Closure;
class IsActivated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

Now we can write the code that will ensure “is_activated” is true:

Let’s replace the “handle” function with this code:

public function handle($request, Closure $next)
    {
        $activated= Auth::user()->is_activated;
        if ($activated !== 1 )
        {
            return redirect()->back()->withErrors(array('message' => 'You did not active your email yet, pleas active your email'));
        }
        return $next($request);
    }

As we can see, this function will check the current user row in database and search for “is_activated” column, if it’s not equal to 1 (you can use this instead: “!($activated)” ) and then return an error message if failed or proceed to the next request.

After that, we will go to “app/Http/Kernel.php” and add our middleware to the “ $routeMiddleware” array (Note: You can see some useful middlewares there that you can use in your app):

protected $routeMiddleware = [
        .....
        'isActivated'=>\App\Http\Middleware\ActivatedUser::class,
    ];

Notice that we named our middleware “isActivated”.

By that we finished making our middleware and now we can use it as a constructor in our controller or in a route like I mentioned above :)

Ahmet Yusuf
Ahmet Yusuf

As a full-stack developer with a master’s degree in Electrical and Computer Engineering, I’m deeply passionate about web design and development. I enjoy exploring new technologies and sharing insights into creating user-centered digital experiences in this exciting field.

Related Articles

You may also like

See all posts
What is WEP Standard and What are the Limitations of Using it? cover

What is WEP Standard and What are the Limitations of Using it?

WEP, Wired Equivalent Privacy, is an older security protocol that is specified in 802.11b Wi-Fi IEEE (...)

Read article
Database Relationships Explained cover

Database Relationships Explained

This article will help you understand the concept of the database relationships. Understating the da (...)

Read article
Securing WebSocket Channels in Local Development: A Guide with Soketi and Laravel Valet cover

Securing WebSocket Channels in Local Development: A Guide with Soketi and Laravel Valet

In this tutorial, we will demonstrate how to set up private channels using Laravel Valet and Soketi. (...)

Read article