laravel - Laravel 关系空
问题描述
在 YouTube 上关于关系的教程之后,我遇到了问题。
我已经从教程中复制了这段代码,但我不断收到错误。
我尝试将控制器代码从 auth() 更改为 app 等。
另外,我尝试重新运行迁移:新鲜等,但什么也没有。
用户模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Notifiable, Billable;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the Instance associated with the user.
*
* @return HasMany
*/
public function instance()
{
return $this->hasMany(Instance::class);
}
}
实例模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Instance extends Model
{
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'name'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
控制器
<?php
namespace App\Http\Controllers;
class SyncController extends Controller
{
public function successful()
{
return auth()->user()->instance()->create(['name' => 'test']);
}
}
错误
Call to a member function instance() on null {"exception":"[object] (Error(code: 0): Call to a member function instance() on null at /home/#/cc.#.io/app/Http/Controllers/SyncController.php:14)
[stacktrace]
编辑:
Route::middleware(['auth'])->group(function() {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('/subscribe', SyncController::class);
});
解决方案
这是因为auth()->user
正在获取null
,有必要检查调用后是否实际收到了该值。
推荐阅读
- c - C程序中打印的位数
- android - 使用 RadioButton 单击
- swift - 用于分离 UITest 代码的 Swift 条件语句
- jquery - ASP.NET MVC Texbox jQuery 自动完成功能不起作用
- python - 使用向右或向下跳跃或单位步长的网格中的最小成本路径
- c++ - 当某人写一些东西来“吞噬换行符”时,他们是什么意思?C++
- google-apps-script - 比较两个句子并在删除重复项的同时合并
- c# - 我如何知道已完成的活动中下载了哪些文件?
- mysql - 雪花中的 SUBSTRING_INDEX()
- r - 在 Markdown 文档中将页面方向更改为横向会破坏 adobe acrobat 中的书签使用