2017-04-03 60 views
1

我试图在我的编辑请求中授权失败时在laravel中显示自定义403文件。如果授权失败,Laravel自定义错误页面

我试过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'); 
} 

我有一个文件夹叫错误,里边有我有仪表盘的文件夹和家长在错误文件的位置。

如果授权失败,我该如何重定向到该页面?

+0

'返回查看( 'errors.dashboard.parent.403')'? –

+0

我也尝试过,但它只是传递它并去编辑。 – raqulka

+0

你需要创建一个异常,并在Exceptions/Handler.php文件的报告方法中做'if($ e实例YOUREXCEPTION){//这里返回你的视图}' – Vikash

回答

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', '[email protected]'); 
2
return abort('403') 

Laravel文档: https://laravel.com/docs/5.4/errors#http-exceptions


如果你把一切都像在文档中,您将获得:

  1. 网址将保持不变。
  2. 将显示模板resources/views/errors/403.blade.php
  3. ASLO响应将有状态代码:403禁止

你想更改网址为http://www.examlpe.com/error403

return abort('403')不会重定向。它只是显示出现错误的客户端。


就你而言,在单个脚本中显示不同内容比不同脚本更容易。尝试将单个错误脚本作为“入口点”。并在该脚本中更改不同用户的输出。想象一下,403.blade.php是一个403错误页面的布局。

+0

这不反正我也不回答这个问题。我已阅读文档。 – raqulka

+0

为什么我要这样做是因为我有两个错误页面,一个用于未登录用户,另一个用于登录用户,一个文件位于错误/ /另一个位于错误/仪表板。我怎样才能显示不同的错误页面? – raqulka

0

前往文件例外/ Handler.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)

希望这将有助于:)

+0

Vikash,我为什么要这样做是因为我有两个错误页面,一个用于未登录用户,另一个用于登录用户。我怎样才能显示不同的错误页面?你的答案也不重定向到页面 – raqulka

+0

检查一次,如果有帮助 – Vikash

相关问题