mercredi 24 octobre 2018

Get Lavavel (5) data without direct relationship

I have an app consisting of these tables

  • users
  • channels (with user_id foreign key to user)
  • playlists (with user_id foreign key to user and foreign channel_id to channels)
  • tracks (with playlist_id foreign key to playlists BUT NOT a user_id foreign key)

User model is defined with:

public function channels()
{
    return $this->hasMany('App\Channel');
}

Channel model is defined with:

public function playlists()
{
    return $this->hasMany('App\Playlist');
}

(and a $this->belongsTo('App\User'))

Playlist model is defined with:

public function tracks()
{
    return $this->hasMany('App\Track');
}

(and a $this->belongsTo('App\Channel'))

Track model is defined with:

public function playlist() { return $this->belongsTo('App\Playlist'); }

Now when listing the tracks in the specific Playlist I do this:

function list($playlist) { $tracks = Track::with('playlist')->get(); return response()->json($tracks); }

This works correctly at the page http://.../tracks/2 (where 2 is the playlist id) but if the user changes 2 into 3 he can potentially see the tracks in the playlist #3 which may not be his. So How do I get the user id from the playlist to show only the tracks belonging to a playlist which the user actually has?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire