Search code examples
phplaravellaravel-5voyager

Laravel Voyager: BelongsToMany


I have a table books and authors. I want to get the ability to attach authors to books. I tune BREAD for books: enter image description here

With these settings I can click edit and choose authors for my book, but when I try to save books, laravel gives out this error:

 SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'Mrs. Alivia 
 Stanton IV' for column 'authors_id' at row 1 (SQL: insert into 
 `authors_books` (`authors_id`, `books_id`) values (Mrs. Alivia Stanton IV, 
 55))

And this is logical. But when I switch name to id, laravel gives out this error:

 SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in field 
 list is ambiguous (SQL: select `id` from `authors` inner join 
 `authors_books` on `authors`.`id` = `authors_books`.`authors_id` where 
  `authors_books`.`books_id` = 57) (View: 

I tried to use all combinations, but nothing happened.

Model Books:

class Books extends Model
{   
protected $fillable = ['name','img'];

public function authors()
{
    return $this->belongsToMany('App\Authors');
}

public function getImgAttribute($img)
{   
    if(!empty($img)){
        return 'storage/images/books/'.$img;
    }else{
        return 'storage/images/books/not-found.jpg';
    }
}

 }

Model Authors:

class Authors extends Model
 {

protected $fillable = ['name','img'];

public function books()
{
    return $this->belongsToMany('App\Books');
}

public function getImgAttribute($img)
{   
    if(!empty($img)){
        return 'storage/images/authors/'.$img;
    }else{
        return 'storage/images/books/not-found.jpg';
    }
}
}

Pivot table Help please!


Solution

  • Model Books:

    class Books extends Model
    {   
    protected $fillable = ['name','img'];
    
    public function authors()
    {
        return $this->belongsToMany('App\Author','Pivot table');
    }
    
    public function getImgAttribute($img)
    {   
        if(!empty($img)){
            return 'storage/images/books/'.$img;
        }else{
            return 'storage/images/books/not-found.jpg';
        }
    }
    
     }
    

    Model Authors:

    class Authors extends Model
     {
    
    protected $fillable = ['name','img'];
    
    public function books()
    {
        return $this->belongsToMany('App\Book,'Pivot table');
    }
    
    public function getImgAttribute($img)
    {   
        if(!empty($img)){
            return 'storage/images/authors/'.$img;
        }else{
            return 'storage/images/books/not-found.jpg';
        }
    }
    }
    

    please read this document for better understanding http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/