Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually create a new empty Eloquent Collection in Laravel 4

How do we create a new Eloquent Collection in Laravel 4, without using Query Builder?

There is a newCollection() method which can be overridden by that doesn't really do job because that is only being used when we are querying a set result.

I was thinking of building an empty Collection, then fill it with Eloquent objects. The reason I'm not using array is because I like Eloquent Collections methods such as contains.

If there are other alternatives, I would love to hear them out.

like image 670
JofryHS Avatar asked May 12 '14 01:05

JofryHS


People also ask

How do I initialize a Collection in Laravel?

Creating Collections As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as: $collection = collect([1, 2, 3]); The results of Eloquent queries are always returned as Collection instances.

What does get () do in Laravel?

For creating ::where statements, you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.

What is create () in Laravel?

Whereas create is used to create a new record by providing all required field at one time . But to use create you should define fillable fields in your Model file like this. Copy Code /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name']; 4.

What is all () in Laravel?

all() is a static method on the Eloquent\Model. All it does is create a new query object and call get() on it. With all(), you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.


2 Answers

It's not really Eloquent, to add an Eloquent model to your collection you have some options:

In Laravel 5 you can benefit from a helper

$c = collect(new Post); 

or

$c = collect(); $c->add(new Post); 

OLD Laravel 4 ANSWER

$c = new \Illuminate\Database\Eloquent\Collection; 

And then you can

$c->add(new Post); 

Or you could use make:

$c = Collection::make(new Post); 
like image 105
Antonio Carlos Ribeiro Avatar answered Oct 12 '22 15:10

Antonio Carlos Ribeiro


As of Laravel 5. I use the global function collect()

$collection = collect([]); // initialize an empty array [] inside to start empty collection 

this syntax is very clean and you can also add offsets if you don't want the numeric index, like so:

$collection->offsetSet('foo', $foo_data); // similar to add function but with $collection->offsetSet('bar', $bar_data); // an assigned index 
like image 24
Gokigooooks Avatar answered Oct 12 '22 13:10

Gokigooooks