Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

here is the answer

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

Thanks to Antonio Carlos Ribeiro from stackoverflow http://stackoverflow.com/questions/21803077/laravel-4-how-to-add-user-id-as-a-default-value-when-inserting-new-records

Last updated 2 years ago.
0

You can use property mutators inside your models:

public function setCompanyIdAttribute($cid)
{
     $this->attributes['company_id'] = Auth::user()->company->id;
}

Just another solution :)

Last updated 2 years ago.
0

usm4n said:

You can use property mutators inside your models:

public function setCompanyIdAttribute($cid)
{
    $this->attributes['company_id'] = Auth::user()->company->id;
}

Just another solution :)

not really 'another solution' because you still need to call for the method to trigger

$model->company_id = 'dummy value';

what ahmd8 needs is Model Observers (http://laravel.com/docs/eloquent#model-observers) and listen to the 'saving' event

Last updated 2 years ago.
0

Sorry :(, i misunderstood the problem, you are right :)

Last updated 2 years ago.
0

usm4n said:

Sorry :(, i misunderstood the problem, you are right :)

no worries ;)

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

ahmd8 ahmd8 Joined 15 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.