dream3323 2017-07-05 11:37
浏览 234

Laravel:Auth :: user() - > app.blade.php中的role_id显示尝试获取非对象的属性

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\vendettaesources\views\layouts\app.blade.php) (View: C:\xampp\htdocs\vendettaesources\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...

  • 写回答

3条回答 默认 最新

  • duankuang1046 2017-07-05 12:09
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容