im trying to figure out eloquent and having a hard time understand it, even tho ive tried to read up on it.
I have two tables: fs_festivals, and fs_bands.
fs_festivals: id, name
fs_bands: id, festival_id, name
So, one festival can have many bands, and one band belongs to a festival.
Band-model (Band.php)
class Band extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'festival_id','name','note','bandak', 'bandakinfo','created_by','updated_by'
);
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'fs_bands';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function festival() {
return $this->belongsTo('Festival');
}
}
Festival-model (Festival.php):
class Festival extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'name','year','info','slug', 'image','created_by','updated_by'
);
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'fs_festivals';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function bands() {
return $this->hasMany('Band');
}
}
In my controller:
public function festivalHome() {
$bands = Band::all();
return View::make('fis.festivalhome')->with('bands',$bands);
}
And in my view:
Bands:
@foreach($bands as $band)
{{ $band->name }}
@endforeach
This lists all bands in the fs_bands table. I only want to list those who are set with the festival_id of the current festival im working on (say festival_id='2'). How should i go about this?
Ive tried this (seeing what others have done),
@foreach($festival->$bands as $band)
But it gives me an error of
Undefined variable: festival
What am I doing wrong? Also I wonder, should I do something else instead of $bands = Band:all(); to list them by festival_id? That would be an option but something tells me that this should be done automatically with eloquent.
Controller:
public function festivalHome($id) {
//$bands = Band::all();
$festival = Festival::with('bands')->whereId($id)->first(); //it will load festival with all his bands
return View::make('fis.festivalhome')->with('festival',$festival);
// or you can filter bands
$bands = Band::whereHas('festival', function($query) use ($id){
$query->whereId($id);
})->get(); //there will be only bands which will be on the festival
}
And in your view:
@foreach($festival->bands as $band)
{{ $band->name }}
@endforeach
//or
@foreach($bands as $band)
{{ $band->name }}
@endforeach