Reputation: 23
In my users table I add role_id
column where 1 is admin
and 2 is user
. So, when I want to his page in header in my app.blade.php file like this:
<ul class="nav navbar-nav">
@if(Auth::user()->role_id == 1)
<li><a href="{!! url('/admin/users'); !!}">Users</a></li>
@endif
</ul>
error appear: (3/3) ErrorException The use statement with non-compound name 'Auth' has no effect (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php) (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php)
index() method in AdminUsersController looks like this:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Role;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Auth;
class AdminUsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::paginate(5);
if(Auth::user()->role_id !== 1) {
return redirect('/home');
}
return view('admin.users.index', compact('users'));
}
When I use check()
instead of user()->role_id == 1
, It works but then all users can see except one that not login, but I want to see only admin
.
I cannot find the answer in similar topics...
Upvotes: 1
Views: 5801
Reputation: 4173
you use
<ul class="nav navbar-nav">
@if(Auth::user()->role_id == 1)
<li><a href="{!! url('/admin/users'); !!}">Users</a></li>
@endif
</ul>
but you are not sure the user logged in or not
I mean maybe user is guest and not logged in
you should use
@if(Auth::check() && Auth::user()->role_id == 1)
this condition check user is looged in then check user role_id
so replace code with:
<ul class="nav navbar-nav">
@if(Auth::check() && Auth::user()->role_id == 1)
<li><a href="{!! url('/admin/users'); !!}">Users</a></li>
@endif
</ul>
Upvotes: 1
Reputation: 1
You are likely getting this error because Auth::user()
is NULL
as no user is logged in when you visit that route.
Try adding the below to your controller to ensure that only logged in users can use the AdminUsers controller.
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
// user must log in to use this controller
$this->middleware('auth');
}
Whenever a user tries to visit one of the routes managed by this controller, s/he will be asked to login first. Then your Auth::user()->role_id == 1
will not return this error.
Reference: Laravel - protecting routes
Upvotes: 0
Reputation: 770
You can add this code in your index() method in AdminUsersController:
public function __construct()
{
// user must log in to use this controller
$this->middleware('auth');
}
public function index()
{
$users = User::paginate(5);
if(Auth::check()){
$roldId = Auth::user()->role_id;
if($roldId !== 1) {
return redirect('/home');
}
}
return view('admin.users.index', compact('users'));
}
It works for me and I hope it will work for you too.
Upvotes: 0