1

I want to get the last record from the colume, then update it...just the last record

i have tried like this but its not working

DB::table('sales')
    ->where('id', $salesid)
    ->pluck('debt')
    ->last()
    ->update([
        'debt'. => 34
    ]);
julianstark999
  • 3,450
  • 1
  • 27
  • 41
PPK
  • 41
  • 1
  • 9
  • yes i can find the last record...but how do i update the last record? – PPK Jun 22 '20 at 18:49
  • it doesn't have to be 2 queries, it can be done in a single query. https://stackoverflow.com/questions/15715922/mysql-update-field-of-most-latest-record – Ersoy Jun 22 '20 at 18:52
  • Try this : `$last_row = DB::table('sales')->orderBy('id', 'DESC')->first();` then `$update = DB::table('sales')->where('id', $last_row->id)->update(['debt' => 34]);` – STA Jun 22 '20 at 19:02
  • 1
    the last record? i would assume an 'id' is a unique identifier so there shouldn't be more than 1 of those ... are you saying the field named `debt` has many values? not understanding why 'last' or 'first' etc is in play here – lagbox Jun 22 '20 at 19:16
  • Doesn't need to be 2 queries; just use a `limit()`: `DB::table('sales')->orderBy('id', 'DESC')->limit(1)->update(['debt' => 34]);`. But, as stated, the `orderBy()` and `limit()` seem redundant if `id` is being provided, since it should be unique. If it isn't, that's a different issue. – Tim Lewis Jun 22 '20 at 19:20

2 Answers2

1

You can do it many ways

$your_data=Model::orderBy('id', 'desc')->first();
$your_data->update(['column' => "value"]);


or you can use

$your_data=Model::latest()->first();

then update

$your_data->update(['column' => "value"]);

Ersoy
  • 8,816
  • 6
  • 34
  • 48
albus_severus
  • 3,626
  • 1
  • 13
  • 25
0

I think if you are concerning about performance, you should use direct update to the DB with out selecting from DB which add a extra overhead, This will work for mysql

 $updated = Model::orderBy('id', 'DESC')
     ->limit(1)
     ->update([
         "debt" => 34
     ]);

or else

DB::table('sales')
->orderBy('id', 'DESC')
->limit(1)
->update([
    'debt' => 34
])
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92