S
S
Sergey Bobrov2015-06-23 15:56:27
Laravel
Sergey Bobrov, 2015-06-23 15:56:27

How to work with collections in laravel 5 correctly?

Hello. I'm interested in the model question. Business logic hangs on my models, and the objects themselves have states, that is, there are fields with data and methods, and when I create a model, I need to initialize it. I thought about doing them through the constructor, but for some reason I had errors, I don’t remember which ones, it was a long time ago, I decided to make the init () method, and it turns out somewhere like this
$user = User(); $user->init($id).
And now the question is, when I want to use collections, for example
$users = User::all()
, is there a way to initialize them somehow, more beautifully than just through a loop?
For some reason, in the constructor through this, it is not possible to find out data about the object, for example:

User.php
...
protected $fillable = ['email', 'password']
public function __constuct() {
         var_dump($this->email);
         var_dump($this->getAttribute('email'));
}
...
Route.php
...
Route('test', function() {
         User::all();
})
...

We get:
NullNullNullNullNullNullNullNullNullNullNullNull...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Plisko, 2015-06-23
@tachini

The constructor creates a Model, and the collection is returned by finders like all, find, first. You need the newCollection method, and in it you can pull your collection with an overlapped constructor, while not forgetting to pull the parent constructor at the beginning.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question