I have a question on which is the better way of doing things.
Controller
public function __construct(User $user)
{
$this->users = $user;
........................
}
public function index()
{
$users = array();
//I did this, cause a user class has been instantiated already in the construct function.
$users = $this->users->all();
//This is what I read on the docs, static method of calling records
$users = User::all();
}
The question is which is the laravel way of doing things?
I would say that $users = User::all()
is the more Laravel-esque way.
I would also question the code in that constructor. You're asking the container to pass in a user (singular) then assigning it to an attribute called $users
, plural. Seems a bit dodgy to me!
By way of example, my controller constructors typically look like this:
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
...
}
My general objective is to keep as little code as possible in the controller and get the repositories and other business objects to do the heavy lifting.