亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

調用 Laravel Auth 輔助方法的最佳方式

調用 Laravel Auth 輔助方法的最佳方式

PHP
千巷貓影 2023-07-01 17:23:51
我有一個簡單的用戶表-id-name-email-role我應該使用第一種還是第二種方法?第一種方法1.if(auth()->user()->role == 'admin'){   // do something}else if (auth()->user()->role == 'supervised'){  // do something}else{  //this is a simple user}這是第二種方法2.$auth = auth()->user();if($user->role == 'admin'){   // do something}else if ($user->role == 'supervised'){  // do something}else{  //this is a simple user}每次我調用這個方法時都會auth()->user()調用數據庫嗎?。。。?
查看完整描述

2 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

auth()->user()當您使用或關系(已加載/設置)時,它不會進行多次調用。您可以安裝發條并檢查它。


不過,我不會在 User 類之外進行這些比較。將這些方法添加到您的用戶模型中。


public function isAdmin()

{

    return $this->role === 'admin';

}


public function isSupervised()

{

    return $this->role === 'supervised';

}

并像這樣使用它們;


auth()->user()->isAdmin()


查看完整回答
反對 回復 2023-07-01
?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

我會使用第一種方法,而不是創建不必要的變量。它不會多次調用數據庫。查看user()中的方法SessionGaurd.php


// If we've already retrieved the user for the current request we can just

// return it back immediately. We do not want to fetch the user data on

// every call to this method because that would be tremendously slow.

if (! is_null($this->user)) {

    return $this->user;

}


查看完整回答
反對 回復 2023-07-01
  • 2 回答
  • 0 關注
  • 134 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號