Laravel 4 how to add user id as a default value when inserting new records
laravel, laravel-4, php
Solution
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
Problem
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