What is use of middleware in Laravel? - laravel

I'm not clear with the concept of middleware in Laravel. What does laravel middleware do? Please provide an example if possible.

Middleware is something that is placed between two requests.
Suppose that you need to make sure that when user access to a specific group of routes he/she is authenticated.
There are two option:
Add in every controller the code to check if user is logged in ( in this example we do not consider a parent controller )
Use a middleware
In the first case you should write in each controller the same code.
With the middleware you have a piece of code that you can re-use in multiple section of your application.
Let's suppose that we want to create a Middleware that need to check if the user is logged in:
namespace App\Http\Middleware;
use Closure;
class UserIsLoggedIn
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!auth()->user()) {
return redirect('home');
}
return $next($request);
}
}
Now with this code we can check our user where we need.
First of all since this is a custom middleware you need to register it in the app/Http/Kernel.php file in the $routeMiddleware property:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
// ...
'isLoggedIn => \App\Http\Middleware\UserIsLoggedIn::class,
];
Let's assume that you have a group of routes that need to check the user is logged in:
Route::get('admin/profile', function () {
//
})->middleware('isLoggedIn');
Now all the routes in this group will check if the user is logged otherwise he will be redirect to home.
Now assume that you have another controller that need to make sure that the user is logged in, now you can re-use the middleware to do that:
class MyController extend Controller {
function __construct(){
$this->middleware('isLoggedIn');
}
}
So middleware help you to organize the login and re-use pieces of code for specific tasks.
Laravel has a lot of documentation about middleware that you can find here

Related

Laravel - limiting users for number of posts

Is there any way to limit users in my project for number of posts. For example, I want my users can create a maximum 10 posts each one. So one user has 10 posts? Is it something with hasMany or something else? Please help find a solution. Thank you
By definition
Middleware provide a convenient mechanism for filtering HTTP requests
entering your application. For example, 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. However, if the user is authenticated, the
middleware will allow the request to proceed further into the
application.
To prevent user from adding more than 10 posts you need to create a middleware to protect your posts/create route
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware CheckUserPostsNumber
This command will place a new CheckUserPostsNumber class within your app/Http/Middleware directory. In this middleware, we will only allow access to the posts/create route if the user posts number < than 10. Otherwise, you will redirect the user back to the home URI:
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
class CheckUserPostsNumber
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->posts->count() >= 10) {
return redirect('home');
}
return $next($request);
}
}
Assigning Middleware To Routes
you would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, append it to this list and assign it a key of your choosing:
// Within App\Http\Kernel Class...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
//...
'checkUserPostsNumber' => 'App\Http\Middleware\checkUserPostsNumber'
];
Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:
Route::get('posts/create', function () {
//
})->middleware('auth', 'checkUserPostsNumber');
Docs
if ($user->posts->count() >= 10) {
//
}

Laravel conditional routing based on database value

I'm developing an admin panel with laravel. I'm putting a preference for an end user to choose if the site is down (for maintenance or similar purpose).
The preference will be stored as boolean in the database. Based on this value frontend will be routed to a custom view if the site is down.
(Site will be hosted on a shared host, no SSL. Using artisan commands are not an option.)
Currently, I can get "site_is_down" value from the database at boot time with a custom method in AppServiceProvider.php's register() method.
But I'm not sure how can I route calls based on this value in the routes file.
I have two named route groups (Frontend and Backend) and standard Auth::routes() in routes/web.php. Only frontend routes should be conditionally routed. Backend and Auth should be excluded. (So the user can access Backend panel).
I'm trying to achieve something like this:
(I know this is not proper syntax, I'm trying to explain my mind)
<?php
if (config('global.site_is_down') === true) {
//Route all frontend route group to maintenance view ->except(Backend and auth)
} else {
//Route all as normal
}
Create a middleware:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckMaintainaceMode
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (config('global.site_is_down')/*or what ever logic you need*/) {
return redirect('mainainance-mode-url');
}
return $next($request);
}
}
then use this middleware in frontend routes
Route::get('/frontend', function () {
//
})->middleware('CheckMaintainaceMode');
or
Route::group(['middleware' => ['CheckMaintainaceMode']], function () {
//
});

Prevent user from accessing some routes in Laravel

Working on a Laravel application and I have some routes, the routes are of a multi step form. I need to prevent the user from accessing the last route (which directs to last page of the form) before accessing or filling in the previous routes.
Routes
Route::get( '/first', 'TrController#payQuote')->name('b2c.payquote');
Route::get( '/second', 'TrController#emailQuote')->name('b2c.sendquote');
Route::get( '/receipt', 'TrController#getReceipt')->name('b2c.receipt');
Route::get( '/success', 'TrController#getSuccess')->name('b2c.success');
You could create a middleware class and then use the middleware directly in your routes file.
Example:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckPermission
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// TODO: Add your logic here.
if ($request->age <= 200) {
return redirect('home');
}
return $next($request);
}
}
Then in your routes file:
Route::get('admin/profile', function () {
//
})->middleware(CheckPermission::class);
There are multiple ways to do it. One way could be that you can check http-referrer on the last page and if it is the route previous to the last one then you allow it otherwise redirect it to the previous page. This can be implemented for every page.
Other way could be database driven. For every page visit you can have an entry in the database and check on the next page if there is an entry otherwise redirect him to wherever you want.

Looking for some helps in adding policy to my laravel projects

I am new in learning laravel. Currently I have been stuck in the Laravel Policy,could you please kindly help with directing me how to add policy to my project?
I would like to make just only the Administrator User be able to see the 'Administration Dashboard' by using Laravel Policies Rules but failed. Actually every registered user is able to see that entrance(just like the attached picture showing below).
The user name is uu#gmail.com and the password is uuuuuu.
Please go to my testing website http://lookoko.com/ and log with the user name and password you will see that Administration Dashboard list in the drop-down lists.
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware AdminMiddleware
This command will place a new AdminMiddleware class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the logged-in user is admin. Otherwise, we will redirect the users back to the home URI.
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (! auth()->user()->is_admin) {
return redirect()->route('home');
}
return $next($request);
}
}
Here I am assumming you have a column in user table named is_admin
Registering Middleware
You should assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. For example:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
...
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
Once the middleware has been defined in the HTTP kernel, you may use the group method to assign middleware to group of routes:
Route::group(['middleware' => ['admin']], function () {
// all your admin routes comes here
});
Docs

Laravel routes for admin and users

i have 2 logins pages on my project
1) cms/admin/login
2) cms/users/login
How to redirect if user to user login page
cms/users/login
and if admin call
cms/admin/ redirect to cms/admin/login page
First of all, you don't know if user is user or admin until he logs into your app, so having 2 different routes for same thing is kinda bad. To achieve something similar what you want, you will need to have one cms/login route where user/admin will login and depending on his status (e.g. 1 - user, 2 - admin) you redirect him on cms/user/page or cms/admin/page. To make this you will have to use Middleware which is very good documented in Laravel official documentation.
For example your middleware for all admin pages should look like this
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
/**
* Run the request filter.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($request->input('status') == 2) {
//2 means its admin and i let him get that admin page
return $next($request);
}
//he is not admin so i redirect him back
return Redirect::back();
}
}
In Kernel.php you add middleware alias
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
And in routes.php you assign middleware to that routes
Route::get('/cms/admin/page', ['middleware' => 'admin', 'uses'=>'Controller#method']);
Hope it helps

Resources