In my requests file in laravel 5.2, I'm setting a condition to check if user is authorized for a request or not.
Code
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\questions;
use Auth;
class answerAddRequest extends Request
{
public function authorize()
{
if(questions::where('people_id',Auth::id())->count()==0)
return true;
else
{
return false;
return redirect('dashboard');
}
}
public function rules()
{
return [
'answer'=>'required|min:3'
];
}
}
If I do not add return false
it executes and inserts in a new row, which shouldn't happen, but with the current code it says Forbidden
which is correct but it doesn't redirect to my dashboard view. How can I make it to redirect to some other page if authorization fails?
In your request
file add a method called forbiddenResponse()
:
public function forbiddenResponse()
{
return redirect('dashboard');
}
Hope this helps!
Side Note
Also, just so you know DB
and Eloquent
have a method called exists
to save you having to do count checks with your database so (if you want to) you could write your authorize
method as:
public function authorize()
{
return questions::where('people_id', Auth::id())->exists();
}
You are using two return statements in your else block
else
{
return false;
return redirect('dashboard');
}
The second return statement is never reachable.
Update
If you want to redirect the user then you can create your custom middleware and write same code as you are doing in authorize()
.
Use this middleware in routes where you want to redirect the unauthorized user.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.