Search code examples
relationshiplaravel-backpacklaravel-relations

Saving issue about relationship with laravel backpack


I have a field in ImageCrud controller.

        $this->crud->addField([
            'label'     => "Etiketler",
            'type'      => 'select_multiple',
            'name'      => 'tags', // the method that defines the relationship in your Model
            'entity'    => 'tags', // the method that defines the relationship in your Model
            'model'     => "App\Models\Tag", // foreign key model
            'attribute' => 'name', // foreign key attribute that is shown to user
            'pivot'     => true, 
        ]);

Seems like ;

image crud controller select.

Also i have 2 more models,

Models\ImageTag.php and Models\Tag.php

ImageTag.php ;


    protected $table = 'image_tags';
    protected $fillable = [
        'image_id',
        'tag_id'
    ];

Here is the Tag.php also

    protected $table = 'tags';
    protected $fillable = [
        'name',
        'slug',
        'description',
    ];

Also my Image.php model has tags() public function.

    public function tags() {
        return $this->belongsTo('\App\Models\ImageTag', 'id', 'image_id');
    }

If you keep this, CRUD controller show multiple select field. But never save image_tags tabel record.

Also here is the, request results after save button click.

requests

What should i do ? Where do i did mistake, can anyone explain this. Any idea. Thanks.


Solution

  • The right relation is belongsToMany.

    here is the code,

        public function tags() 
        {
            return $this->belongsToMany(Tag::class, ImageTag::class)->withTimestamps();
        }