将未经授权的用户重定向到另一个页面 spatie laravel

redirect unauthorized users to another page spatie laravel

我正在开发 spatie laravel 我想将未授权的用户重定向到该视图的特定视图,它将有一个简单的按钮可以重定向到后面我已经尝试过这样但是它给我错误像

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function setCookie() on null

这是我在 app/exception/handler 中的代码。php

 public function render($request, Exception $exception)
{

     if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
    // Code here ...
      return view('404');
}
    return parent::render($request, $exception);
}
 /**
 * Convert an authentication exception into an unauthenticated response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }
    $guard = array_get($exception->guards(), 0);
    switch ($guard) {
      case 'admin':
        $login = 'admin.login';
        break;
      default:
        $login = 'login';
        break;
    }
    return redirect()->guest(route($login));
}

在404.blade.php

 @extends('web.layouts.default')
@section('title', '404')
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">You are not authorized</div>

                <div class="card-body">

                    <a href="{{ back() }}" class="btn btn-primary"> Click here to go back</a>
                 </div> <br>    <br>

        </div>
    </div>
</div>
@endsection

我有给用户的 gievn 查看主页权限,当有这个权限时,你可以在 profileController 中查看个人资料页面,我写的像

 <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use Spatie\Permission\Models\Permission;
class ProfileController extends Controller
{
     public function __construct()
    {
        //$this->middleware('auth',['except' => 'otp']);
       // return redirect(route('logout'));
         $this->middleware(['permission:view homepage','auth']);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        //$per=Auth::user()->getAllPermissions();
        return view('profile');

    }
}

当我向没有查看主页权限的用户输入 /profile 时,出现上述错误

请让我知道您想从我这里得到的任何意见

您应该尝试在 404.blade.php 文件中使用下面的按钮,它工作正常。

<a href="{{ redirect()->back()->getTargetUrl() }}" class="btn btn-primary"> Click here to go back</a>