Laravel 5.1: Get identifier from firstOrNew method

I have the following function that creates a new record in the database, if it does not already exist - if it exists, it updates it. The problem is that it returns true, and therefore I cannot get the ID of the inserted or updated record.

/**
 * Save timesheet.
 *
 * @param $token
 * @param $data
 */
public function saveTimesheet($token, $data) 
{
    return $this->timesheet->firstOrNew($token)->fill($data)->save();
}
+4
source share
1 answer

First create a new model, and then save it, the identifier will be automatically set in the model.

/**
 * Save timesheet.
 *
 * @param $token
 * @param $data
 */
public function saveTimesheet($token, $data) 
{
    // Set the data
    $model = $this->timesheet->firstOrNew($token)->fill($data);

    // Save the model
    $model->save();

    // Return the id
    return $model->id;
}
+5
source

Source: https://habr.com/ru/post/1617706/


All Articles