Another test I'm doing is putting the following code in the __constructor() method to have people that don't have the role be redirected elsewhere
if(Auth::user()->hasRole('admin'))
{
return redirect(route('home'));
}
That provides me with the following error
Call to a member function hasRole() on null
What am I doing wrong?
The route
Route::group(['auth', 'middleware' => ['role:admin']], function () {
Route::get('/admin', [AdminController::class, 'index'])->name('admin.index');
});
And the controller
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct()
{
// Making sure the user is authorized to be here
if(Auth::user()->hasRole('admin'))
{
return redirect(route('home'));
}
}
public function index()
{
echo '<pre>';
print_r(Auth::user()->with(['roles'])->get()->toArray());
echo '</pre>';
}
}
The ['role:admin'] middleware works, but I'm confused why the 'hasRole' thing isn't working either.