Traits
Are an alternative approach to inheritance that solves some limitations of single class inheritance, which PHP uses. Since all Eloquent models extends Model it can not extend another class. This is commonly used to share similar logic across objects. Let's imagine a couple of models have a Company relationship.
trait HasCompany {
public function company() {
return $this->belongsTo(Company::class);
}
}
Now the user can easily share code from the trait, by the keyword using. This is an example and most often a more complex use case would be needed for it to make sense.
class User extends Model {
use HasCompany;
}
Repositories
Repositories is a design pattern to abstract data layers from the application. Your logic should not care about how you store data, so if you wanted to change from Mysql to Mongodb, you would only swap out the repository and not have to change business logic.
Very opinionated here, but this is not a fitting design pattern for Laravel. Laravel has Eloquent and the database layer is therefor already abstracted. Repositories is sometimes used for Laravel applications, but rather an outlier, than a common sight. One of the main reasons for repositories, is to be data implementation agnostic, which already exists and you can swap between SQL servers flawlessly. Also Eloquents features like ::find(), scopes etc. feels like a replacement for Repositories and is quirky to use at the same time.
If you use Doctrine as the ORM, which you can in Laravel, it is the core of their architecture and repositories should be used.
It sometimes occurs that the repository pattern is used to encapsulate business logic, with a similar approach as used with services or action pattern.
Services
Is commonly used for a place to store business logic or the building blocks of your actions in your application. In traditional MVC design, Controllers should only handle input. Normally you would put your logic in Models, but they get "fat" very quickly, when this happens services is a common place to put business logic. Sometimes action or command design pattern are used, which is similar but still different.
One of the core things it solves, is to make your business logic reusable. Imaging filtering all users by an active flag, when you retrieve it in its controller.
public function all() {
return User::where('active', true)->get();
}
Now you have your business logic, that enforces that you only work on active users, later you want to notify all active users with an email, by notifications using a command.
class NotifyUsers extends Command {
public function handle() {
foreach (User::where('active', true)->get() as $user) {
$user->notify();
}
}
}
Now you manually have to keep business logic up to date. Next time you add a second condition or change the logic, you have to change the code in two places. In a big application where this code block is used often, it can make it quite hard to maintain the conditions without forgetting one of the places. If you make a service with this logic, you can easily utilize the same business logic across the application. While one have one place to change the code, if this logic had to change.
class UserService {
public function all() {
return User::where('active', true)->get();
}
}
Everywhere you want to use this business logic getting active users, you can use the service. Therefor only having one place to maintain the logic. A call can be as simply as resolve(UserService::class)->all(). Example of the updated logic with services would be.
// controller
public function all(UserService $userService) {
return $userService->all();
}
// command
class NotifyUsers extends Command {
public function handle(UserService $userService) {
$userService->all()->each->notify();
}
}
Conclusion
The world is not black and white, you have to figure out your own approach. My advice is, do not spend time on Repositories, Laravel has a lot of features to handle data related operations scopes, getters setters etc. that conflicts with the Repository design pattern. See if a service like design approach suits you and you can utilize em. Traits is not as much an architectural design pattern, as it is a Class inheritance alternative, simply to share logic between classes.
php - When to use Repository vs Service vs Trait in Laravel? - Stack Overflow
php - What is the purpose of repository when service classes can do the same? - Stack Overflow
Service vs Repository | Laravel.io
php - Creating Laravel repositories and binding as service providers - Stack Overflow
Videos
There is no definitive answer for your question since the patterns you use highly depend on the project's complexity and needs.
However, a Service and a Repository are two different things. The Repository is a common wrapper for the model and is where you write the queries to the database. IMO you shouldn't add logic here and the sole purpose of a repository is to grab os store data into the database. The advantage of Repositories is the "easiness" to switch to other database systems.
A Service, IMO, is where you add all the application's logic.
For additional information refer to this answer.
From DDD (Domain Driven Design) the responsibility of a repository is to take care of loading, storing, modifying and deleting an entity on the designated data storage (which may or may not be a database -- it may even be a remote server or just a file).
A service, on the other hand, has (or should have) a very narrow responsibility of performing some useful activity. Each service is instantiated separately and then injected into code in the application layer or above, which acts as a bridge (Bridge pattern). This approach has proven to be very advantageous because it allows to manage the dependencies between otherwise unrelated (uncoupled) code.
Those two definitions and the origin of the concepts shows that they actually are very different things. By pure chance you noticed that a repository and a service have an apparent overlap, but that's due to implementation details or plain misuse. Their responsibilities may under circumstances go hand in hand (giving rise to a collaboration) but they really are orthogonal concepts.
Furthermore, Repositories should arise from a deep layer (Persistance or DAL, Data Access Layer). Services, on the other hand, often are vertical cross-cutting or arise on the application layer.
Through proper layering the differences between repositories and services become even more apparent.
Do not think about them as pure code artifacts you can move around. They are well-defined concepts useful to understand about and design the structure of a system. They decline into actual code only as a consequence of that design.
I hope I succeeded in writing something that clears up some ideas and is not confusing.
why doesn't Laravel have a built-in repository pattern
Because there is no consensus on how they should be used if used at all.
For example, I use Repositories as an intermediary between laravel models and laravel controllers that needs the model instance to be instantiated and I never inject them into controllers but instantiate them manually when needed.
do we need to bind repositories as providers ?
As said above, there is no consensus so NO.
Depends on how you design your repositories, you can instantiate them manually, inject them into controller's instantiation (in the __contruct(UserRepository $userRepository)) as you can see in laravel from scratch tutorial from laracast or use them as service providers.
From Laravel Repository Pattern – How to use & why it matters
The last step is to register this service provider in our config/app.php. Open this file and add to providers our provider App\Providers\RepositoryServiceProvider::class
Now our application knows what class it should use when we type an objects by its interfaces.
This is why you need to bind your interfaces like that:
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->bind(EloquentRepositoryInterface::class, BaseRepository::class);
$this->app->bind(UserRepositoryInterface::class, UserRepository::class);
}
In order to let Laravel knows about what to instantiate when you do in your controller:
private $userRepository;
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
}
[EDIT 1]
Also there is a great article from the Laravel documentation for Dependency Injection: laravel.com/docs/master/controllers#dependency-injection-and-controllers