I have two fields in almost every table
of my DB
, they are created_by
and modified_by
. So, right now I have this in my controller
:
$request['created_by'] = Auth::user->id;
$request['modified_by'] = Auth::user->id;
I was thinking that I should turn this into middleware
or something a little more RESTful
but I don't know how I would go about this. It is being used in 100% of my store
methods right now, but it's possible that down the road I will have a table
that doesn't have these two fields, which is where I get confused.
Middleware job is to process requests, however you need here to control the model creation and update. So in my opinion, I would add those parts in model events, and remove them from all Controllers. So once a model is creating or updating, an event is triggered to change those parameters/attributes, just before saving the model.
This can be achieved easily as per the documentation:
In your AppServiceProvider:
<?php
namespace App\Providers;
use App\User;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::creating(function ($user) {
if ( ! $user->isValid()) {
return false;
}
});
}
You can replace User
with your model name, and make sure to import it.