lundi 12 octobre 2015

How to use only specific columns with eloquent's diff method

I have two models with a many to many relationship: 'app' and 'component'. With the following function in the app model class they are connected:

public function components()
{
    return $this->belongsToMany('App\Models\Component');
}

Now I have a second method, to get me all the components not yet related to an app:

public function availableComponents()
{
    $allComponents = Component::all();
    $usedComponents = $this->components()->get();
    return $allComponents->diff($usedComponents);
}

The results of this diff, I use in some blade generated form to add more components to an app:

{!! Form::select('components[]', $availableComponents !!}

With the above code, my form is cluttered with unnecessary fields like timestamps and the description field. One result for example looks like this:

{"id":1,"created_at":"2015-10-08 15:17:17","updated_at":"2015-10-08 15:17:17","name":"Product","description":"Id dolor voluptas provident maiores alias et quasi non."}

I only need the id for the option field and the name for the select value. Normally with eloquent collections I could do {{ component->name }}. This doesn't seem to be an eloquent collection, just a normal php array. Hence, it doesn't work. What should I do?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire