I\'m trying to create a many to many relationship using Laravel, but I am stuck.
Here\'s my current table model:
album
album_id
name
created_
You're trying to call AlbumxUserImage()
on a Collection
of models instead of on each individual model.
AlbumxUserImage::all()
is returning a Collection
of models, which you can think of as an array. You need to iterate over the collection and call AlbumxUserImage()
on each model in the collection.
That may solve your problem for now, but you seem to not understand how many-to-many relationships work in Laravel.
I don't know why you have a model for your pivot table. That is not how Laravel normally handles models with many-to-many relationships. A typical many-to-many relationship with your tables would look like this:
Models:
class Album extends Model {
protected $table = 'album';
protected $primaryKey = 'album_id';
public function images() {
return $this->belongsToMany('App\UserImage', 'albumxuser_image','album_id','user_image_id');
}
}
class UserImage extends Model {
protected $table = 'user_image';
protected $primaryKey = 'user_image_id';
public function albums() {
return $this->belongsToMany('App\Album', 'albumxuser_image','user_image_id','album_id');
}
}
Usage:
// Get all album names through UserImage
$userImages = UserImage::all();
foreach ($userImages as $userImage) {
foreach ($userImage->albums as $album) {
echo $album->name;
}
}
// Get all images through Album
$albums = Album::all();
foreach ($albums as $album) {
foreach ($album->images as $image) {
echo $image->value;
}
}