Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 how to add user id as a default value when inserting new records

I am building app for enterprise

their are three table: 1- users table (belong to company) 2- companies table (has many users) 3- branches table (belong to company)

when adding a branch I want to pass the company id in the model by default by adding the following code to the branches model

 protected $attributes = array(
    'company_id' => Auth::user()->company->id,
 );

this will reduce the hassle of inserting company_id for each insert or update of a record

like image 939
ahmed Avatar asked Dec 11 '25 03:12

ahmed


1 Answers

You can override the save method of your Model:

class YourModelClass extends Eloquent {

    public function save(array $options = array())
    {
        if( ! $this->company_id)
        {
            $this->company_id = Auth::user()->company->id;
        }

        parent::save($options);
    }

}

Not everytime you do:

$model = new YourModelClass;
$model->name = 'a name';
$mode->save();

It will also add the company_id to that model

like image 96
Antonio Carlos Ribeiro Avatar answered Dec 13 '25 17:12

Antonio Carlos Ribeiro