我的代码运行正常。在安装了Laravel Passport v7之后(我写这篇文章的最新版本,顺便说一句,我使用的是Laravel v5.7也是最新版本),我的代码不再起作用了。当我尝试运行$user->role->id
时出现错误
试图获取非对象的属性“ id”
那是因为我的$user->role
并没有返回角色模型对象,而是返回了null
,并且在安装Laravel Passport之前它正在返回角色模型。我不知道是否有任何连接,但是由于这个原因,我不想更改整个代码。即使是我也尝试在用户模型return $this->belongsTo(Role::class, 'role_id');
中编写代码,但是效果不佳。
这是我的代码: 用户模型:
namespace App;
use App\Role;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsTo(Role::class);
}
}
角色模式:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function user()
{
return $this->hasMany(User::class);
}
}
用户表架构:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email', 250)->unique();
$table->string('password');
$table->string('phone', 11)->nullable();
$table->integer('role_id')->unsigned()->default(1);
$table->string('api_token', 60)->unique();
$table->rememberToken();
$table->timestamps();
});
角色表架构:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
HomeController:
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$user = \Auth::user();
$products = new Product;
// here i am getting the error
if ($user->role_id > 2) {
$products = Product::where('name', '!=', NULL)->latest()->paginate(6);
} else {
$products = $products->getApprovedAndUntaken();
}
return view('welcome', compact('products'));
}
public function home()
{
return view('home');
}
}
答案 0 :(得分:1)
我猜该错误与config/auth.php
中配置错误的Auth Guard有关。
安装护照后,检查阵列是否如下所示:
config / auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport', // Passport goes here
'provider' => 'users',
],
],
每次访问相关对象时,都应像
一样访问它$user->object()
不是
$user->object
如果这对您有用,请现在让我!
答案 1 :(得分:0)
使用with
方法获取联接数据
$products = Product::where('name', '!=', NULL)->with('role')->get()->paginate(6);