Laravel advanced | Traits
In Laravel, traits are a way to reuse common functionality across multiple classes. A trait is similar to an abstract class, but it cannot be instantiated on its own. Instead, it is used to add methods to existing classes.
Here is an example of a trait in Laravel:
<?php
namespace App\Traits;
trait Loggable
{
public function log($message)
{
Log::info($message);
}
}
This trait can be used in any class by adding the use
statement at the top of the class:
<?php
namespace App\Http\Controllers;
use App\Traits\Loggable;
class UserController extends Controller
{
use Loggable;
public function store(Request $request)
{
$this->log('Creating new user');
User::create($request->all());
return redirect()->route('users.index');
}
}
You can also use multiple traits in a single class by adding multiple use
statements:
<?php
namespace App\Http\Controllers;
use App\Traits\Loggable;
use App\Traits\AnotherTrait;
class UserController extends Controller
{
use Loggable, AnotherTrait;
public function store(Request $request)
{
$this->log('Creating new user');
User::create($request->all());
return redirect()->route('users.index');
}
}
Traits are a powerful way to add reusable functionality to your classes and make your code more maintainable and scalable. It is important to note that if a method from the class and trait have the same name, the method from the class will be used. If the class method is abstract or not defined, the method from the trait will be used.