How to Assign Multiple Relationships to One Model

ยท

0 min read

Today, I am going to show you how to assign one or multiple relationships to one model.

As you might already know, saving a new record is quite easy with Laravel.

use App\Ticket;

Ticket::create([
    'name' => 'The computer is not working'
]);

Sometimes, you want to attach another model to the record. We can do that as below:

use App\Ticket;
use App\Customer;

$ticket = new Ticket([
    'name' => 'The computer is not working'
]);

$customer = Customer::first();

$customer->tickets()->save($ticket);

Now, let's say the record belongs to different models, such as Customer, User and Type. Unfortunately, we can no longer use the previous method because when we call the save method, the database will throw an error as we are not defining the missing user_id and type_id. Instead, we need to use a different, and maybe more elegant, way:

use App\Ticket;

$ticket = new Ticket([
    'name' => 'The computer is not working'
]);

$ticket->customer()->associate(Request::get('customer_id'));

$ticket->user()->associate(Auth::id());

$ticket->type()->associate(Request::get('type_id'));

$ticket->save();

That's all to it.

If you have any questions, please leave a comment below.