Skip to content

Instantly share code, notes, and snippets.

@MostafaNorzade
Last active August 3, 2019 07:50
Show Gist options
  • Save MostafaNorzade/fe509060ffcf8670e22442adea1d29fb to your computer and use it in GitHub Desktop.
Save MostafaNorzade/fe509060ffcf8670e22442adea1d29fb to your computer and use it in GitHub Desktop.
<?php
// create middleware with below command :
// php artisan make:middleware My_middelware_name
// then define this in Kernel.php
// we have 2 types middelware : 1-before 2-after
// example for 'before middleware':
public function handle($request, Closure $next)
{
if($request->has('name')){
return $next($request);
}
return abort(404);
}
// example for 'after middleware' :
public function handle($request, Closure $next)
{
/** @var Response $result */
$result = $next($request);
$result->header('myName', '123');
return $result;
}
// define middleware for a controller
public function __construct()
{
$this->middleware('guest');
}
// define middleware for one or multi function in controller
public function __construct()
{
$this->middleware('guest')->only(['method1', 'method2']);
}
// define multi middleware together :
// in Kernel.php
protected $middlewareGroups = [
'custom.middle' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
]
]
// now just use this :
Route::get('/user', 'UserController')->middleware('custon.middle');
// pass parameters to middleware
Route::get('/', 'HomeController', [
'middleware' => 'allow:12', // pass 'allow' param with default value 12
]);
public function handle($request, Closure $next, $value)
{
if($request->has('name') && $request->allow == $value){
return $next($request);
}
return abort(404);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment