【问题标题】:How to fix Call to a member function isAdmin() on null如何在 null 上修复对成员函数 isAdmin() 的调用
【发布时间】:2021-11-27 05:12:02
【问题描述】:

我有一条路线: Route::get('/TransactionHistory','QuoteController@transactionHistory');

在Controller QuoteController中,我有一个函数:

public function transactionHistory(){
         if(Auth::user()->isAdmin())
        {
               $res= DB::table('products_products')
->select('users_users.display_name','products_products.name','products_products.id','products_products.user_id','products_products.quantity_type','buy_product.price','buy_product.rating','buy_product.mileage_name','buy_product.id as buy_id')
->join('buy_product','products_products.id','=','buy_product.product_id')
->join('users_users','buy_product.user_id','=','users_users.id')
->get();
        }
        else{
       $u_id=auth()->user()->id;
      $res= DB::table('products_products')
->select('products_products.name','products_products.id','products_products.user_id','products_products.quantity_type','buy_product.price','buy_product.rating','buy_product.mileage_name','buy_product.id as buy_id')
->join('buy_product','products_products.id','=','buy_product.product_id')

->where('buy_product.user_id','=',$u_id)
->get();}
        
    return view('templates::pagetwigs/transaction-history')->with('details',$res);
    } 

在路由路径时出现错误:Call to a member function isAdmin() on null

如何解决这个问题。

【问题讨论】:

  • 您需要在 User 模型上定义 isAdmin() 。你定义了吗?
  • 所以这个函数在User模型(User.php)中。你可以从那里修改它,或者你可以添加另一个条件if( auth()->check() && Auth::user()->isAdmin() )。这个错误是因为用户没有登录我想是的。
  • @Abdullah Al Mamun 我没有用户模型
  • @Binsha User.php 是用户模型,它是 Laravel 的默认值。你可以找到它 app/User.php
  • 你的错误是 Auth::user()null;你登录了吗?如果您曾经引用​​过auth()->user() 方法(或Auth::user()),您需要确保您已经实际登录,否则您的代码将失败。或者在通过if(auth()->user() && auth()->user()->isAdmin())等引用之前检查一下。

标签: php laravel admin roles


【解决方案1】:

在路由或者控制器的构造函数中添加中间件,如图:

public function __construct()
{
      $this->middleware('auth');
    
}

除非您已登录,否则您将无法访问该页面。这将始终检查 Auth::user() 是否为空

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2015-10-26
    • 2016-05-22
    相关资源
    最近更新 更多