ahmad-y

ahmad-y

2016/11/07 | 0 | 2434 | 0

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');

2. 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);
    }
}

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 :)