Traits in PHP and Laravel?

This is a fact that in PHP you can only have single inheritance. That means a class can inherit from only one other class. For example if a class needs to inherit more than one methods from different classes in order to prevent duplication of the code, it can’t extend multiple classes.

It is not possible in versions < PHP 5.4, but in PHP 5.4 a new feature was added known as Traits and is used effectively in Laravel.

I have created a Traits folder in my app/Http in Laravel project with a Trait called ActivityLog.php. Let’s take a look at very simple example how to implement Traits:

ActivityLog.php

<?php
use App\Http\Traits\ActivityLog;

trait ActivityLog {
    public function log($message, $object) {
        // Store $message and $object in database
        SomeModel::create([
            'message' => $message,
            'object_class' = get_class($object),
            'user_id' => Auth::user()->id
        ]);
    }
}

Implementation of trait in our models:

Product.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {
	use ActivityLog;
}

Stock.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Stock {
	use ActivityLog;
}

How to access trait implemented in Models?

ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Product;

class ProductController extends Controller
{
    /**
     * Store a new product.
     *
     * @param  Request  $request
     * @return Response
     */
	public function store(Request $request) {
		$product = new Product();
		$product->create($payload);
		$product->storeLog('product is created', $product);
	}
		
}

On the other hand, how to implement trait in Controller instead of Model:

StockController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Product;

class StockController extends Controller
{
	use ActivityLog;

	public function store(Request $request) {
		$product->update($payload);
		$this->storeLog('product is updated', $product);
	}

}

Get Gist of code examples here.

Quite simple, isn’t it. I never used this feature of PHP before I started to code in Laravel. Really a useful feature to reduce code duplication.

Author: Danyal
I'm a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.