mardi 12 avril 2016

Laravel 5.1 - How to pass a variable from 'before' filter to 'after' filter?

To explain myself more clearly: there are certain models in our application that need to log all the changes to them and its relationships. So I created a class that logs adjustments - LogAdjustment($before, $after).

The $before var expects loggable mode with all of its loggable relationships loaded, before any of it is changed.

And $after var expects same model with same relationships after all the changes to the model itself and relationships.

In controller I call it like this:

public function update(Request $request, $id)
{
    $model = Model::with('LoggableRelationships')->find($id);
    $before = $model->replicate(); // I want this removed from @update method

    /*... Lots of updates and syncs and attaches ...*/

    $after = $model->load('LoggableRelationships')->fresh(); // I want this removed from @update method
    \Path\to\class\LogAdjustment::saveAdjustment($before, $after); // I want this removed from @update method
    return view('yeah');
}

Now I would be extremely happy if I could put this out of controller-method logic. So I thought maybe create a before and after filter for this specific method and handle the logs there. How would I go about passing a variable from before to after?

Even better would be if I could somehow make it into a trait - if there's any nice possibility of doing that.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire