Skip to content

Instantly share code, notes, and snippets.

@danyal14
Last active August 6, 2020 08:47
Show Gist options
  • Save danyal14/d96e690fa26aed9cb139493ee249ca9d to your computer and use it in GitHub Desktop.
Save danyal14/d96e690fa26aed9cb139493ee249ca9d to your computer and use it in GitHub Desktop.
Traits in PHP and Laravel
<?php
use App\Http\Traits\ActivityLog;
trait ActivityLog {
public function storeLog($message, $object) {
// Store $message and $object in database
SomeModel::create([
'message' => $message,
'object_class' = get_class($object),
'user_id' => Auth::user()->id
]);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
use ActivityLog;
}
<?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);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stock {
use ActivityLog;
}
<?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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment