laravelandme's avatar

Unable to access request within trait

In my lumen project, I have a custom trait which will store one record in a audit trail table for every CREATE/UPDATE/DELETE events on every table/model. My new requirement is that, all of my APIs will receive one key_id as input which I need to store it in the audit trail table for every record.

I tried accessing request global helper function within trait as suggested here (https://laracasts.com/discuss/channels/general-discussion/traits-in-laravel-and-requests) , but got error as 'class request not found'.

Now, in order to get that key_id to each of audit trail table records, I created a BaseModel file which I extended for all of my models. Within this BaseModel, I created the following function.

public $key_id=null; //to avoid column not found during model CREATE/UPDATE/DELETE events;
public function getKeyId($value) {
    return $value;
}

Then during every table CRUD transaction in the controller, I populated this field with the key_id from request field, so that in trait, the key_id value was available within the concerned model instance itself. Because of this round about way, I had to include one line of code during every table's CRUD transaction for this key_id; instead if there is anyway to access the request within trait, it would be just one line of code within the trait to populate the key_id. Any suggestion to make this work will help me.

I also thought about using session, but with Lumen 5.3, usage of session variables are no longer included in the framework.

0 likes
2 replies

Please or to participate in this conversation.