How to view the data of the last saved record in the database

Asked

Viewed 781 times

0

how do I display in the view only the data of the last saved record in the database? I can display all the data by calling the All() method in the control, and the good old foreach in the view to display the data. However, he wanted that when the user finishes the registration he was redirected to a page, where he could check the data that registered.

Obs:I’m using Laravel, eloquent Orm, mysql

in control I have this action to get all the data

public function exibe(){
  $dados = Denuncia::all();
  return view('AdminDenunciaView.exibeInformacao',['dados'=>$dados]);
}

in view use this foreach to display the data

@foreach ($dados as $item)
   {{$item->crime}}.<br/>
   {{$item->infrator}}.<br/>
@endforeach

But as I mentioned, I don’t need all the data to be shown, just the last record data

  • mysqli_insert_id - Returns the automatically generated id in the last query. With this you select with Where nameColuna = automatically generated id in the last https://www.php.net/manual/en/mysqli.insert-id.phpquery

3 answers

0

In the query you could give an order by, to list the last record.

Example: select * from clientes order by cliente_id desc

Thus would return the last registered record.

  • thanks for the feedback, but this way is returned all records, but in descending order. The idea is list only the last record

  • You can set limit 1 (MYSQL).

0

to sort by last record you can select order by desc Example

select * from tabelaExemplo order by tabelaExemplo_id  desc

To take only the last bank record you can do so:

select * from tabelaExemplo where tabelaExemplo.id = select max(id) from tabelaExemplo
  • obg for trying to help, but following the first answer is returned all the record, but in decreasing form, but the idea is to return only the last record. The second answer is showing a syntax error

0


You can order by the highest id (last added) and take the first record of the returned list, with the first() of eloquent.

example: DB::table('tabela')->orderBy('id', 'DESC')->first();

This way the first of the list will be the last id added, and this query will return you only 1 result.

  • Hello Sara! thanks for the feedback, following the example you posted I got the following answer. You are trying to use the orderby() method in the Eloquent collection. I researched a little more and found that I would have to use the sortByDesc method, because this already classifies the collection in the opposite order. Soon after, I use First method to capture the first in the opposite order, vlw thank you very much. looks like this::all()->sortByDesc('id')->first();

  • Hi, good that I helped!! vlw by the answer :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.