Get the Last Inserted Id Using Laravel Eloquent

2019-01-01 12:44发布

I'm currently using the below code to insert data in a table:

<?php

public function saveDetailsCompany()
{
    $post = Input::All();

    $data = new Company;
    $data->nombre = $post['name'];
    $data->direccion = $post['address'];
    $data->telefono = $post['phone'];
    $data->email = $post['email'];
    $data->giro = $post['type'];
    $data->fecha_registro = date("Y-m-d H:i:s");
    $data->fecha_modificacion = date("Y-m-d H:i:s");

    if ($data->save()) {
        return Response::json(array('success' => true), 200);
    }
}

I want to return the last ID inserted but I don't know how to get it.

Kind regards!

24条回答
情到深处是孤独
2楼-- · 2019-01-01 12:59
$objPost = new Post;
$objPost->title = 'Title';
$objPost->description = 'Description';   
$objPost->save();
$recId = $objPost->id; // If Id in table column name if other then id then user the other column name

return Response::json(['success' => true,'id' => $recId], 200);
查看更多
只若初见
3楼-- · 2019-01-01 12:59

The shortest way is probably a call of the refresh() on the model:

public function create(array $data): MyModel
{
    $myModel = new MyModel($dataArray);
    $myModel->saveOrFail();
    return $myModel->refresh();
}
查看更多
与君花间醉酒
4楼-- · 2019-01-01 13:00

After saving model, the initialized instance has the id:

$report = new Report();
$report->user_id = $request->user_id;
$report->patient_id = $request->patient_id;
$report->diseases_id = $request->modality;
$isReportCreated = $report->save();
return $report->id;  // this will return the saved report id
查看更多
时光乱了年华
5楼-- · 2019-01-01 13:00

Using Eloquent Model

$user = new Report();        
$user->email= 'johndoe@example.com';  
$user->save();
$lastId = $user->id;

Using Query Builder

$lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);
查看更多
伤终究还是伤i
6楼-- · 2019-01-01 13:02

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

$id = DB::table('users')->insertGetId([
    'email' => 'john@example.com',
    'votes' => 0
]);

Refer: https://laravel.com/docs/5.1/queries#inserts

查看更多
琉璃瓶的回忆
7楼-- · 2019-01-01 13:02

In laravel 5: you can do this:

use App\Http\Requests\UserStoreRequest;
class UserController extends Controller {
    private $user;
    public function  __construct( User $user )
    {
        $this->user = $user;
    }
    public function store( UserStoreRequest $request )
    {
       $user= $this->user->create([
            'name'              => $request['name'],
            'email'             => $request['email'],
            'password'          => Hash::make($request['password'])
        ]);
        $lastInsertedId= $user->id;
    }
}
查看更多
登录 后发表回答