Laravel fetch only pivot columns in many to many relationship Laravel fetch only pivot columns in many to many relationship laravel laravel

Laravel fetch only pivot columns in many to many relationship


As per your expected output i guess you need data from junction model only, If that is the case i suggest you to define direct mapping of Section and UserTrainingSection

class Section extends Model{    public function training_users()    {        return $this->hasMany('App\Models\UserTrainingSection', 'section_id');    }    public function users()    {        return $this->belongsToMany(User::class, 'section_user')->using('App\Models\UserTrainingSection')->withPivot('completed', 'completed_date');    }}

In query you can simply do

Section::with('training_users')->first();


In your with statement you are fetching all User data by definition.You can add a select statement to only get the results you want. You can add that either in the relationship in your model, or where you access the model in your API.

Example 1:

Section::with(['users' => function ($q) {    $q->where('users.id', Auth::user()->id)->select('completed', 'completed_date');}])->first();

Example 2:

public function users()    {        return $this->belongsToMany(User::class, 'section_user')->using('App\Models\UserTrainingSection')->withPivot('completed', 'completed_date')->select('completed', 'completed_date');    }

(Not tested)

See the documentation