Article

Middlewares in laravel

Jan 19, 2020 2,872
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 EDGE Cellular System ? cover

What is EDGE Cellular System ?

EDGE (Enhanced GPRS) is a data system which is used on GSM networks. EDGE provides three times faste (...)

Read article
Web Design Quality Impact on the User cover

Web Design Quality Impact on the User

Bringing users to visit a website can be an easy task compared to converting them to be returning vi (...)

Read article
Multiple Image Uploader with Laravel 5.5 and Dropzone.js cover

Multiple Image Uploader with Laravel 5.5 and Dropzone.js

In a lot of our projects we need to make a multiple image uploader. In this tutorial, We will make a (...)

Read article