php - Limiting retrieved columns when using withPivot on belonsToMany relationship

Solution:

i think that the most straightforward way is to make independent relation based on the pivot table using pivot model:

class ShiftEmployee extends Pivot
{
    protected $table='shift_employee';
} 

now the new relation in Shift Model:

class Shift extends Model
{
    public function shortlistedApplications()
    {
        return $this->hasMany(ShiftEmployee::class,'shift_id');
    }
 public function scopeWithShortlistedApplications($query)
    {
        $query->with('shortlistedApplications:shift_id,shortlisted');
    }
}

now this new scope would bring the data you want

Answer

Solution:

What I think you need is to only load the shortlisted attribute of your employee's application in your scopeWithApllications:

public function scopeWithApplications($query)
{
    $query->with('applications.application:id,shortlisted');
}

This will still return an Application instance as a relationship, but will only load it's shortlisted attribute. Then, after retrieval, you can map your collection in order to merge the application's attribute to your employee, if that's really important. But in terms of data shortage, this will do the trick.

Answer

Solution:

In your application model use withPivot method. Like this:

public function applications(){
return $this->belongsToMany('App\Application')
    ->withPivot('shortlisted')
    ->withTimestamps();}

You can use this link for more clear example https://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

Source