We have seen middleware before and it can be used with controller also. Middleware can also be assigned to controller’s route or within your controller’s constructor. You can use the middleware method to assign middleware to the controller. The registered middleware can also be restricted to certain method of the controller.
To know more about Middleware In laravel visit our Bajarangisoft site.
Assigning Middleware to Route
Route::get('profile', [
'middleware' => 'auth',
'uses' => 'UserController@showProfile'
]);
Here we are assigning auth middleware to UserController in profile route.
Assigning Middleware within Controller’s constructor
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserController extends Controller {
public function __construct() {
$this->middleware('auth');
}
}
Here we are assigning auth middleware using the middleware method in the UserController constructor.
Example(1)
1.Add the following lines of code to the app/Http/routes.php file and save it.
routes.php
Route::get('/user_demo/path', [
'middleware' => 'userdemofrst',
'uses' => 'demoController@show_userdemo'
]);
2.Create a middleware called userdemoMiddleware by executing the following line of code.
php artisan make:middleware userdemoMiddleware
3. Add the following code into the handle method of the newly created userdemoMiddleware at app/Http/ Middleware.
<?php
namespace App\Http\Middleware;
use Closure;
use DB;
use Auth;
class userdemoMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
echo '<br>User Demo Middleware';
return $next($request);
}
}
4.Create a middleware called user_demosecMiddleware by executing the following command.
php artisan make:middleware user_demosecMiddleware
5. Add the following code in the handle method of the newly created user_demosecMiddleware at app/Http/Middleware.
<?php
namespace App\Http\Middleware;
use Closure;
class user_demosecMiddleware
{
public function handle($request, Closure $next)
{
echo '<br>User Demo Second Middleware';
return $next($request);
}
}
6. Create a controller called demoController by executing the following line.
php artisan make:controller demoController
7.Copy the following code to app/Http/demoController.php file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class demoController extends Controller
{
public function __construct()
{
$this->middleware('userdemosec');
}
public function show_userdemo(Request $request)
{
$uri = $request->path();
echo '<br>URI: ' . $uri;
$url = $request->url();
echo '<br>';
echo 'URL: ' . $url;
$method = $request->method();
echo '<br>';
echo 'Method: ' . $method;
}
}