Matt Pierce
Matt Pierce

Reputation: 805

Laravel Create Record and Use ID Value in Another Column

When I create a new record in my Fan model, at the same time that I create the new Fan record, I want to use the new ID value in another column. I'm trying to do this all at once and not have another method to go back and update the record.

$fan = Fan::create([
    'display_name' => $displayName,
    'bio' => $bio,
    'logo_url' => $logoUrl,
    'algolia_id' => 'fan_'??, // I want to replace ?? with this record's ID value.
]);

I've tried $fan, but doesn't work since that variable isn't created yet. I cannot use Auth because the ID isn't the Auth user's ID.

Thanks!

Upvotes: 3

Views: 2839

Answers (1)

AntoineB
AntoineB

Reputation: 4694

I doubt you can automatically do it, you should do it in 2 steps:

$fan = Fan::create([
    'display_name' => $displayName,
    'bio' => $bio,
    'logo_url' => $logoUrl
]);

$fan->algolia_id = 'fan_' + $fan->id;
$fan->save();

That said, it's not a great database design, you'd rather want to build the algolia_id field when you need to use it, since you'd store duplicated value (the id and the algolia_id are the same except for fan_).

Upvotes: 4

Related Questions