首页 > 解决方案 > 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);
});

标签: laravel

解决方案


这是因为auth()->user正在获取null,有必要检查调用后是否实际收到了该值。


推荐阅读