我正在尝试在我的编辑请求中授权失败时在laravel中显示自定义403文件。
我试过了forbiddenResponse()
但事实证明它已经被淘汰了。
然后我尝试failedauthorization()
,但这也没有重定向,允许我编辑。
这是我的请求文件
public function authorize()
{
$job_posting_id = $this->route('id');
$job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();
if($job_posting){
return true;
}
return false;
}
public function failedAuthorization()
{
return redirect('errors.dashboard.parent.403');
}
我有一个名为errors的文件夹,里面有错误文件所在的仪表板文件夹和父文件夹。
如果授权失败,如何重定向到该页面?
答案 0 :(得分:2)
return abort('403')
Laravel文档: https://laravel.com/docs/5.4/errors#http-exceptions
如果您在文档中制作所有内容,那么您将实现:
resources/views/errors/403.blade.php
。您想要将更改网址更改为http://www.examlpe.com/error403吗?
返回中止(' 403')不进行重定向。它只是向客户显示错误发生。
在您的情况下,单个脚本中显示的内容比不同的脚本更容易。尝试将单个错误脚本作为"入口点"。并在该脚本中更改不同用户的输出。想象一下,403.blade.php是一个403错误页面的布局。
答案 1 :(得分:0)
public function authorize()
{
$job_posting_id = $this->route('id');
$job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();
if($job_posting){
return true;
}
return redirect('/error');
}
public function failedAuthorization()
{
return view('errors.dashboard.parent.403');
}
在你的路线
Route::get('error', 'YourController@failedAuthorization');
答案 2 :(得分:0)
转到例外/处理程序.php的 report
方法文件。
public function report(Exception $e)
{
if(!Auth::check())
{
// Do whatever you want - redirect or return something
}
if($e instanceof HttpException && $e->getStatusCode() == 403)
{
// Do whatever you want - redirect or return something
}
return parent::report($e);
}
无论您的授权失败,只需撰写abort(403)
希望这会有所帮助:)
答案 3 :(得分:0)
在laravel文件夹中,打开app / Exceptions / Handler.php粘贴以下代码。这将返回403和500错误的自定义错误页面。
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.custom_all', [], 500);
}
if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
return response()->view('errors.custom', [], 403);
}
return parent::render($request, $exception);
}