-1

Here I am using laravel 5.5. My code is

$result = DB::insert('INSERT INTO .......');

Here it returns true. But how can I get inserted id? In my table id is the primary key. Thanks in advance

Hedayatullah Sarwary
  • 2,664
  • 3
  • 24
  • 38
Kabir
  • 31
  • 1
  • 5
  • 1
    Why not use Eloquent ORM? – Sachin Bahukhandi Apr 17 '21 at 05:54
  • I need to executive raw sql and get id.... because sql comes from my db – Kabir Apr 17 '21 at 07:09
  • Maybe executing this as a single statement: https://stackoverflow.com/a/17112962/5192105 – Sachin Bahukhandi Apr 17 '21 at 07:43
  • 1
    be careful with using raw my friend, I've seen a video where you can get SQL injection with raw. try to use eloquent or query builder better. just personal opinion :). you can find the video by search "How your Laravel application can get hacked, and how to prevent that from happening by Antti Rössi" on Youtube, – Wailan Tirajoh Apr 17 '21 at 11:57
  • Why do you must use a `RAW QUERY` instead of [Eloquent](https://laravel.com/docs/5.5/eloquent) ? If you are doing basic operations **`Eloquent`** is a must, no excuse... – matiaslauriti Apr 18 '21 at 08:24

4 Answers4

2

you can use insertGetId().

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]
);

doc can be found here.

zahid hasan emon
  • 6,023
  • 3
  • 16
  • 28
1

Instead of using DB method you can simply use Laravel eloquent:

$result = <YOUR_MODEL_NAME>::create(<YOUR_DATA>)->id();

it return the last inserted record id.

And make sure if you use this method you need to add $fillable in your MODEL like:

class <YOUR_MODEL> extends Model
{   
    protected $fillable = [ 'column_name_1', 'column_name_2', .., 'column_name_n' ];
}
wiwek chauhan
  • 468
  • 1
  • 5
  • 12
  • But I need to executive raw sql and get id.... how can I ? because sql comes from my db – Kabir Apr 17 '21 at 07:08
  • But why you use the raw SQL instead of eloquent? Laravel eloquent is easy to use. Just try at once. :) If you don't want to use eloquent then try this : $id = DB::getPdo()->lastInsertId(); – wiwek chauhan Apr 17 '21 at 07:12
0
$result = MODEL_NAME::create(data);
return $result->id;

try this may be it's working

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Arjun bhati
  • 306
  • 1
  • 3
  • 12
0

Why don't you order your rows and get last id?

select <primary key> from <table> order by desc limit 1;
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Mohammad Akbari
  • 446
  • 2
  • 9