In this article, we will give you information about middleware and we will see how to create custom middleware in laravel 7 and laravel 8.
Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. If your project has multiple users then we need to use middleware to provide different access or login to different users.
So, let's see how to create custom middleware in laravel 7/8 and create custom middleware in laravel 8.
In this example, I have created "roleType" middleware and I will use it simply on the route when the route will run you must have to pass the "type" parameter, and then you can access those requests like as below demo link.
First, we need to create custom middleware. So, run the below command in your terminal.
php artisan make:middleware RoleType
After running the above command, you will find one file on the app/Http/Middleware/RoleType.php location and you have to add the below code.
<?php
namespace App\Http\Middleware;
use Closure;
class RoleType
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->type != 'admin') {
return response()->json('Please enter valid type');
}
return $next($request);
}
}
After successfully adding this code of middleware we have to register this middleware on the kernel file.
app/Http/Kernel.php
protected $routeMiddleware = [
...
'roleType' => \App\Http\Middleware\RoleType::class,
];
Now, add route and add RoleType middleware in this route.
Route::get('check/role','UserController@checkRole')->middleware('roleType');
In this step, we will add the below code in UserController with the checkrole function.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function checkRole()
{
dd('checkRole');
}
}
Now, it's time to run this example. so, copy the below link in your URL and get the output.
You might also like:
Hello, laravel web developers! In this article, we'll see how to send real-time notifications in laravel 11 usi...
Sep-09-2024
Hello, laravel web developers! In this article, we'll see how to generate an app key in laravel 11. In laravel 11 we...
May-24-2024
In this article, we will see the laravel 10 ajax crud operations example. Here, we will learn about ajax crud operation...
Feb-27-2023
In this article, we will see the laravel 8 form validation example. form validation in laravel is a very common fun...
Oct-10-2020