samedi 11 février 2017

Return result instead of modifying collection in Laravel Eloquent

Using Laravel's Blade template engine, I'm querying a model to retrieve a value from an Eloquent collection. It looks like this:

<select class="select2">
    @if(Request::old('supplier') != NULL)
        <option value=""></option>
    @endif
</select>

Note that I'm using this way to retrieve an old value because of using Select2. This works fine, this is not what the question is about.

Later in my code, I have another value and use the same code snippet. I noticed that the query changes the entire collection instead of just returning the result and leaving the collection as how it is. Here is an example of my problem;

Right now it is like this:

/*
 * $collection is an Eloquent collection of 3 objects
 * The objects have id's of 1, 2 and 3.
 */

$collection = Suppliers::all();
$test = $collection->where('id', 1)->first()->name; //this changes the entire collection instead of returning just the result and leaving everything as how it is.

echo $test;

$test = $collection->where('id', 2)->first()->name; 
// The above line throws a null reference exception because the collection only exists of the first item instead of all of them.

I need the second query to work as well, sort of like a object copy like in C#. I don't want to modify the collection itself but only return the result. How can I achieve this? Note that I need to use this in Blade this way. Hope someone can help!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kDjiwx
via IFTTT

Aucun commentaire:

Enregistrer un commentaire