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_at
user_image
user_image_id
value
albumxuser_image (junction table)
albumxuser_image_id (primary key & auto increment)
album_id (FK from album)
user_image_id (FK from user_image)
I want to be able to get the album name from albumxuser_image table.
Here's what I've done so far.
Album.php model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Album extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'album';
protected $primaryKey = 'album_id';
public function AlbumxUserImage() {
return $this->belongsToMany('AlbumxUserImage', 'albumxuser_image','album_id','user_image_id');
}
}
routes.php (I didn't use view since I'm making a practice)
Route::get('all', function() {
$albumxuserimage = AlbumxUserImage::all();
foreach ($albumxuserimage->AlbumxUserImage as $getthem) {
echo $getthem->pivot->name; // I want to get the name column of the album table.
}
});
AlbumxUserImage.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AlbumxUserImage extends Model {
protected $table = 'albumxuser_image';
protected $primaryKey = 'albumxuser_image_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['album_id', 'user_image_id'];
}
Here's the error I get
Call to undefined method Illuminate\Database\Eloquent\Collection::AlbumxUserImage()