show the last data db laravel

3

Hi I have this problem with laravel

this is my code

$last = DB::table('nombre_votos')->select('id')
               ->orderby('created_at','DESC')->first();
 return view('user/votos/index',compact('last'));

The idea is to show me the last name that was created it is displayed like this

    
asked by Ramon Albares 05.10.2018 в 21:54
source

1 answer

2

Try the take() method to which you indicate the number of elements to take as follows: take(1) and at the end you use the get() method * this will return a collection of an element *

  $data = DB::table('nombre_votos')
                 ->select('nombrePersona')
                 ->orderBy('created_at','DESC')
                 ->take(1)
                 ->get();

 return view('welcome')->with(["data" => $data]);//sustituye por tu                                               
 vista

By using the sorting DESC and using the take (1) method with the number one, the query builder will know that it is only going to take a single element and that this is the last one registered.

In select remove the id column and put the name of the column that stores the names as in my example

Expected result

Once you run your query, your result should be very similar to this

[
  {
   "nameUser": "delta"
  }
]
  

You just have to adjust the names of your columns

Update

As you are returning a collection, in the view you can do the following

@foreach($data as $d)
   {{ $d->nameUser }}//sustituye nameUser por el nombre de la columna tuya
@endforeach

You can also get it as follows

 $data = \DB::table('users')
                     ->select('nameUser', 'users.id')
                     ->orderBy('created_at','DESC')->first();

     return view('welcome')->with(["data" => $data]);

As first returns a single element now in the view I can read it the value like this

{{ $data->nameUser }}
    
answered by 05.10.2018 / 22:04
source