I have two classes: Artist and Instrument . Each Artist can play one or more Instrument s. And each Instrument can be assigned to one or more Artist s. So, I created the following classes:
Artist.php
public function instruments() { return $this->belongsToMany('App\Models\Instrument'); }
Instrumentment.php
public function artists() { return $this->belongsToMany('\App\Models\Artist'); }
Then I have three database tables:
artists: id, firstname, lastname, (timestamps) instruments: id, name artist_instrument: id, artist_id, instrument_id
I can successfully find one artist and related tools:
ArtistController.php
$artist = Artist::find($artist_id); $instruments = $artist->instruments()->get(); return \View::make('artists')->with('artists', $artists)->with('instruments', $instruments);
I have 3 questions:
In my opinion, I can output $artist as:
{{ $artist->firstname }}
and I can iterate through $instruments like:
@foreach ($instruments as $instrument) <h2>{{ $instrument->name }}</h2> @endforeach
but is it possible to iterate over $artist (I know only one - see No. 2) and for each $artist iterate over $instruments ?
In my controller, how can I get all the artists and for each of these related tools with the ultimate goal of iterating through them in my view, as described in # 1.
Is it possible to get only certain columns in the above ArtistController.php example? I tried this:
$artist = Artist::where('id', $artist_id)->get('firstname'); $instruments = $artist->instruments()->get(); return \View::make('artists')->with('artists', $artists)->with('instruments', $instruments);
but I get the error Collection::instruments() undefined.
I suppose there is something wrong with my model relationship. I also tried to define my relationship in Artist.php using hasMany (I think it makes sense to say "every artist hasMany Instruments", but this gives me an error because it expects a table called artists_instruments , and also tries to get columns that would not be in this table (e.g. name ).
source share