Support the ongoing development of Laravel.io →
Database Eloquent

Hi guys,

I'm trying to find the best way to implement the following.

I have a Client of a given Sector who belongs to an Agency.

clients table:

  • client_id

  • sector_id NOT NULL

  • agency_id NOT NULL

  • [...]

Both sector_id and agency_id are mandatory and this rule is enforced in DB (NOT NULL fields, although).

I'd also like my Client model to ensure agency_id and sector_id are set so I coded it like so:

// BaseModel declares an event handler on "saving" 
// and uses Validator with $rules to check input
class Client extends BaseModel 
{
    protected $table = 'clients';
    protected $primaryKey = "client_id";
    protected $guarded = ['client_id', 'agency_id', 'sector_id'];

    protected static $rules = array(
        'name' => 'required|max:255',
        [other rules on contact info etc]
    );

    public function agency()
    {
        return $this->belongsTo('Agency');
    }

    public function sector()
    {
        return $this->belongsTo('Sector');
    }
}

And in my unit test I go

$sector = Sector::find(1);
$agency = Agency::find(1);

$new_client = new Client($attributes); // $attributes contains fields such as name, contact info etc
$new_client->sector()->associate($sector);
$new_client->agency()->associate($agency);
$s = $new_client->save();

Is this the right way to do it? Do I have to call associate method twice to link a Client to both Sector and Agency?

Thanks!

Last updated 3 years ago.
0

Yes, that's the way for the relation linking, but what is that you want to test there?

Last updated 3 years ago.
0

Hey,

above test is only there to make sure things work.

I wanted to have another test which would fail if a client had no sector associated to it and I was wondering if guarding required fields was the way to go.

Thanks for your answer.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

JoolsMcFly joolsmcfly Joined 22 Apr 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.

© 2025 Laravel.io - All rights reserved.