Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rotaercz's avatar

Is there a way to assign the id to a different column when using firstOrNew in Eloquent without having to do a second query?

I have 2 questions but they're related.

My table columns in my MySQL database looks like this:

'id', 'topic', 'root_id', 'parent_id', 'username', 'comment', 'created_at', 'updated_at'

My query looks like this:

$c = Comments::firstOrNew([
    'topic' => $topic,
    'root_id' => $id, // <---- the auto increment id would go here
    'parent_id' => $parent_id,
    'username' => $username,
    'comment' => $comment
]);

First question. I'd like to add the auto increment id to the root_id column without having to do a second query. Is this possible?

Second question, is it possible to do the following in a single query?

$root_id = Comments::select('root_id')
    ->where('topic', '=', $topic)
    ->where('parent_id', '=', $parent_id)
    ->first();
    
$c = Comments::firstOrNew([
    'topic' => $topic,
    'root_id' => $root_id,
    'parent_id' => $parent_id,
    'username' => $username,
    'comment' => $comment
]);
0 likes
2 replies
AdrianHernandezLopez's avatar

Hi @rotaercz ,

It is possible to change the primary key of an Eloquent model overwriting the property defined in the base model.

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'root_id';

On the other hand, it is possible to use firstOrNew method using two arguments as defined @ https://laravel.com/docs/5.5/eloquent#other-creation-methods. You will provide as first argument the values to find and a second argument with the values to set if not found.

$c = Comments::firstOrNew([
    'topic' => $topic,
    'parent_id' => $parent_id
], [
    'root_id' => $root_id,
    'username' => $username,
    'comment' => $comment
]);

Please note that the firstOrNew do not persist the record in the database as firstOrCreate does.

Hope this helps.

Regards, Adrian

rotaercz's avatar

Hey, thanks for the response. I think I wasn't very clear in my question. I'll post a new question that's clearer. :)

Please or to participate in this conversation.