Home > Software design >  Laravel Relationship Null
Laravel Relationship Null

Time:11-07

I am having an issue following a tutorial on YouTube about relationships.

I have replicated this code from the tutorial and I keep getting errors.

I've tried changing the controller code from auth() to app etc.

Also, I've tried re-running migrations:fresh etc and nothing.

User Model

<?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);
        }
    }

Instance Model

<?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);
    }
}

Controller

<?php

namespace App\Http\Controllers;

class SyncController extends Controller
{
    public function successful()
    {
        return auth()->user()->instance()->create(['name' => 'test']);
    }
}

Error

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]

CodePudding user response:

Check if your route is guarded by auth middleware. If not you can add that in order to fix. You might use Route group like following -

Route::group(['middleware' => ['auth']], function () {
    Route::resource('your_url', 'YourController');
    // Or whatever route you want to add...    
});

CodePudding user response:

This is because the auth()->user is getting null, it will be necessary to check if the value is being received.

  • Related