0
votes

I have a many to many relationship between table shops and users.So to create a new shop i want to assign users for that shop but i have an Error: Call to undefined method App\Models\Shop::user() when i try to create a new shop.

I have inside setupCreateOperation function in ShopCrudController this code :

protected function setupCreateOperation()
    {
        CRUD::setValidation(ShopRequest::class);

        $this->crud->addFields([
            ...
            [
                'name'  => 'user_id',
                'label' => 'Owners',
                'type' => 'select2_multiple',
                'entity' => 'user',
                'attribute' => 'firstname',
                'model' => "App\Models\User",
                'pivot'     => true,
                'options'   => (function ($query) {
                    return $query->orderBy('name', 'ASC')->where('depth', 1)->get();
                }),
            ],

        ]);

And The model Shop :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\app\Models\Traits\CrudTrait;

class Shop extends Model
{
    use HasFactory;
    use CrudTrait;

    ...

    public function users()
    {
        return $this->belongsToMany('App\Models\User','shop_user')->withTimestamps();
    }
}

And The model User :

<?php

namespace App\Models;

use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Parental\HasParent;
use Backpack\CRUD\app\Notifications\ResetPasswordNotification as ResetPasswordNotification;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;

    use HasParent;
    use CrudTrait;
    use HasRoles;
    use HasFactory;

    ...

    public function shops()
    {
        return $this->belongsToMany('App\Models\Shop', 'shop_user')->withTimestamps();
    }
}
1

1 Answers

0
votes

I made a typo in 'entity' => 'user' instead of 'entity' => 'users'