Last active
August 6, 2020 08:47
-
-
Save danyal14/d96e690fa26aed9cb139493ee249ca9d to your computer and use it in GitHub Desktop.
Traits in PHP and Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Product extends Model { | |
use ActivityLog; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Stock { | |
use ActivityLog; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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