How to check if a record is new in Laravel?

后端 未结 5 1886
星月不相逢
星月不相逢 2020-12-30 19:11

I recently started using Eloquent.

When I used PHP Active Record, there was a nice function that checked if a record was loaded from the database or is a new instan

5条回答
  •  不知归路
    2020-12-30 19:44

    Your model object has an attribute exactly designed for that. It's wasRecentlyCreated :

    $item = Item::firstOrCreate(['title' => 'Example Item']);
    
    if ($item->wasRecentlyCreated === true) {
        // item wasn't found and have been created in the database
    } else {
        // item was found and returned from the database
    }
    

    For more clarification between the way exists variable works vs wasRecentlyCreated variable (copied from the comment by CJ Dennis below)

     /* Creating a model */ 
     $my_model = new MyModel; 
     $my_model->exists === false; 
     $my_model->wasRecentlyCreated === false; 
     $my_model->save(); 
     $my_model->exists === true; 
     $my_model->wasRecentlyCreated === true;
    

    As opposed to if a model was loaded from a previous request:

    /* Loading a Model */ 
    $my_model = MyModel::first(); 
    $my_model->exists === true; 
    $my_model->wasRecentlyCreated === false;
    

提交回复
热议问题