Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1: Get ID from firstOrNew method

I have the following function which creates a new record in the database if one doesn't already exists - if one exists, it updates it. The problem is that it returns true and therefore I can't 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();
}
like image 667
V4n1ll4 Avatar asked Mar 14 '23 01:03

V4n1ll4


1 Answers

First create the new model and then save it, the id will be set in the model automaticaly.

/**
 * 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;
}
like image 174
Jerodev Avatar answered Mar 17 '23 03:03

Jerodev