Answer the question
In order to leave comments, you need to log in
Should Laravel Repository return objects or arrays?
Hello!
When working with Laravel and trying to use repositories, the following dilemma arose.
Most online resources and tutorials suggest the following repositories:
<?php
class UserRepository implements UserRepositoryInterface
{
public function all()
{
return User::all();
}
}
<?php
class UserRepository implements UserRepositoryInterface
{
public function all()
{
return User::all()->toArray();
}
}
<?php
$user->role->name;
<?php
User::with('role')->get()->toArray();
$user['role']['name']
<?php
$repo->newInstance(); // вернёт новый созданный объект Eloquent
echo $repo->id;
<?php
$repo->newInstance(); // новый созданный объект Eloquent будет преобразован к массиву
echo $repo['id']; // => error: undefined index
<?php
array_get($repo, 'id');
Answer the question
In order to leave comments, you need to log in
I always use objects because I love the possibilities they provide.
Accessing a model property is much prettier than accessing an array key + does not require checking for the existence of a property, as is the case with an array key.
I prefer the first option of working with objects.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question