Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Call to a member function without globalScopes on null" in Laravel and Nova

I am planning to develop a web application using Laravel and Nova. Nova is a CMS package for Laravel introduced very very recently. Since it is the new technology, I am having an issue with using it. I cannot declare a field for the foreign key in the resource.

I created a new model called, Post running the artisan command to make model and this is the definition of the Post migration class.

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->string("title");
            $table->text('content')->nullable();
            $table->unsignedInteger('user_id');
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Then, I created a resource for it running this command.

php artisan nova:resource Post

When I check the Nova admin dashboard, I can see that the menu item for Post resource is added.

enter image description here

Then in the fields method of the Post resource, I added this code for the form scald folding.

public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            Text::make('Title')->rules('required')->sortable(),
            Textarea::make('content')->rules('required')->hideFromIndex()
        ];
    }

When I create a new Post from the Nova dashboard UI, I can see the fields. When I create, it is giving me an error saying that User id is required. So, I tried to specify the User field as well like this.

public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            BelongsTo::make('User')->rules('required'),
            Text::make('Title')->rules('required')->sortable(),
            Textarea::make('content')->rules('required')->hideFromIndex()
        ];
    }

When I create a new Post again, another error is thrown which is "call to a member function without globalScopes ".

enter image description here

How can I fix it?

like image 416
Wai Yan Hein Avatar asked Feb 03 '26 16:02

Wai Yan Hein


1 Answers

I had the same issue because I forgot to return the relationship in my model

I first had:

public function user()
{
    $this->belongsTo(User::class);
}

Instead of:

public function user()
{
    return $this->belongsTo(User::class);
}
like image 92
Ashwin Avatar answered Feb 05 '26 04:02

Ashwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!