I am working on a project in which I have three type of users Admin and user1 and user2. I want user1 and user2 to able to use certain features in application only if the admin has assigned an invoice to them. I have tried using helper function given below.
$invoice = Invoice::pluck('user_id')->toArray(); if (Auth::user()->admin == 1 || in_array(Auth::user()->id, $invoice)) { return 1; } else { return 0; }
but this does not work fine. I’ll have to place it before every method of a controller in order to restrains users to use that feature. Is there any thing else I can do?
Any Better Approach for this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use middlewares.
Create your middleware with
php artisan make:middleware UserWithInvoiceMiddleware
Then open your file in app/Http/Middleware/UserWithInvoiceMiddleware.php
, and add this to the handle
method:
public function handle($request, Closure $next, ...$guards)
{
$user = auth()->user();
$invoice = Invoice::pluck('user_id')->toArray();
if ($user->admin || in_array($user->id, $invoice)) {
return $next($request);
}
return response()->json(['message' => 'Request not authorized.'], 401);
}
Also, you can create a relation in your user model with the Invoice model:
public function invoice()
{
return $this->hasOne(Invoice::class);
}
Then, you can simplify your middleware using this relation:
public function handle($request, Closure $next, ...$guards)
{
if (auth()->user()->admin || auth()->user()->has('invoice')) {
return $next($request);
}
return response()->json(['message' => 'Request not authorized.'], 401);
}
You have to register your middleware in app/Http/Kernel.php
, under the $routeMiddleware
array:
protected $routeMiddleware = [
...
'user-with-invoice' => AppHttpMiddlewareUserWithInvoiceMiddleware::class,
];
Then, you can protect your routes with this middleware, adding a ->middleware('user-with-invoice')
to the routes where the user has to be an admin or have an invoice:
Route::get('/example', ExampleController::class)->middleware('user-with-invoice');
Method 2
you can use make a middleware and pass requests throw it to check if the user is authorized to do that or not.
class SomeMidllewareName { /** * Handle an incoming request. * * @return mixed */ public function handle(Request $request, Closure $next) { $invoice = Invoice::pluck('user_id')->toArray(); if (1 == Auth::user()->admin || in_array(Auth::user()->id, $invoice)) { return $next($request); } return response()->json(['message' => 'you are not authorized'], 401); } }
then, you can validate on the routes and you can use also policies and validate every feature alone
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0