Laravel 5
How to give user access to specific route when certain conditions are met?
For example let user access
Route::get(view('posts/{id}'),'PostsController#show');
when user has over 100 points in his user->points column.
You can use Middleware for this,In Laravel it is very easy to secure your routes by creating your own middlewares.
The following steps are required to do this:
run command php artisan make:middleware Middlewarename and you'll find your middleware inside app/Http/Middleware/yourcustomemiddleware.php
Register your middleware in app/Http/kernel.php file which you just created
Now implement logic in middleware you just created:
YourMiddlewareClassCode:
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->points >= 100)
{
return $next($request);
}
return redirect()->back()->with('flash_message','you are not allowed to access this');
}
Attach middleware to your route:
routes/web.php:
Route::get(view('posts/{id}'),'PostsController#show')->middleware('yourcustommiddleware');
All done now your route is secured.
Summary: this statement return $next($request); in middleware will return the route when condition is matched else it will redirect to the previous route.
Note: I don't know your db structure and also this is just an example to show you that what is middleware and how it works and how you can use it.
Related
I am new to laravel and trying to make a panel for food delivery
I have used Laravel default Registration and Login for User Category--Restaurant
and then after user login , the user can Add restaurant details using route (/add_details)
once the user has added restaurant details the user should not be able to go to that route (/add_details)
this will depend on a column in restaurant table (is_verified)
how do i check that
I was thinking of using a Laravel middleware
but then i was stuck how laravel middleware $request variable works
how can i get column value in middleware and verify it
or if any other simple but effective solution
as
i will be using it in sidebar.blade.php as well
so that i can hide the menu
I made a middleware and added it to kernel.php and is using it in routes
Its working fine
but i want to ask is this the right way i have done it
Route::get('/manage_cuisines', 'RestaurantCuisineController#create')->name('manage-cuisines')->middleware('restaurant_verified');
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use \App\User;
use \App\Restaurant;
class CheckRestaurantVerification
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$restaurant = Restaurant::find(User::find(Auth::id())->restaurant_id);
if($restaurant->is_verified == 0)
{
return redirect('home');
}
return $next($request);
}
}
There is a table users in my website and a user is allowed to update a user if it is admin or it is his/her account. I can put this rule inside a middleware and impose it on the route but I want to create separate middlewares and OR among them. Can I do that?
The following code
Route::group(['middleware' => ['admin','Owner']],
function () {
Route::resource('roles', 'RoleController');
Route::resource('locations', 'LocationController');
Route::resource('recipients', 'RecipientController');
Route::resource('classifications', 'ClassificationController');
});
has AND behavior. I think it is possible to do this using some if ... else ... statement inside the web.php or the UserController but I need to know if there is any other way out.
Thanks in advance
update
Here is Owner middleware
class OwnerMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $id)
{
if(Auth::guest())
return abort(403, 'Access Denied');
if(Auth::user()->id != $id)
return abort(403, 'Access Denied');
return $next($request);
}
}
Then I pass the $id parameter to it.
There really isn't an "OR" for middleware. It either acts or passes. You have to expand the current middleware to check ownership or permission to edit.
However, I'd recommend using a policy with middleware to resolve this:
See: https://laravel.com/docs/master/authorization#via-middleware
I am trying to handle ajax request that were initiated from idle/expired session(maybe the page was left open and the session got expired). I wrote the below middleware but it's not working as expected:
namespace App\Http\Middleware;
use Closure;
class AjaxSessionCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(!\Auth::check())
{
if($request->ajax())
{
return response()->json(['Session_error'=>'Session Expired'], 401);
}
}
return $next($request);
}
}
I also tried to add this code to the Auth middleware with no luck.
Strangely enough authenticated(user logged in) ajax requests are detected by this.
Lost 2 days finding solutions. Desperate call here.
use optimised code for performance use both auth::check and request->ajax() in same if condition by AND operator. just try session expiry in configuration file
It's because session runs after middleware, you can see the reference here. If you want to check that session expired, I think you should use after middleware instead of before middleware
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
I have some problems with subdomain routing in laravel 5.2 and hope you can help me with it.
The point is that I need to redirect a user on certain subdomain, depending on it's usertype.
For example in database I have a usertype (1,2,3 etc...) and basing on that value I need to redirect user on
type1.mysite.com
type2.mysite.com
type3.mysite.com
etc...
But the problem is that I can't get authenticated user in routes.php, it always returns null.
Any ideas on how to solve that problem?
And by the way, to make a subdomain routing, I have to configure apache in some way or it can be done with laravel?
Thanks for the answers!
you need to edit it and specify what we want it to do.
In App\Http\Middleware you should see the newly created file
php artisan make:middleware UserTypeMiddleware
<?php namespace App\Http\Middleware;
use Closure;
class UserTypeMiddleware {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
//check your user type here
if ($request->user()->type != 1)
{
return redirect('DefinedRoute');
}
return $next($request);
}
}