0

Hello I am new to laravel, I want to loop through a data table and get each id of it in a variable. So i did it like this, but unfortunatly nothing works

$station_id = 0;
$stations = Station::all();

foreach ($stations as $station) {
    $station_id =  $station->id;
}
return $station_id;

this only showing the last id;

Lafoune
  • 436
  • 2
  • 12
  • 28
  • You know that this will only output the last id as you return station_id after the loop that sets it to something different each time? What would be the purpose of this? I suspect there is a better way to do this but I need to know your use case. – Petay87 Jun 18 '19 at 14:59
  • Are you trying to get all IDs in a collection or array? So for example you'd want the result to be an array of IDs that looks something like this `[1, 5, 7]`? – Bogdan Jun 18 '19 at 15:00

2 Answers2

2

The way you are trying it your $station_id will be set to the very last ID.. If you want to have an array of ids from the stations just use this:

$stations = Station::pluck('id')->toArray();
nakov
  • 13,938
  • 12
  • 60
  • 110
2

What you can do is loop all of the result set and add the ids to an array. First, you need an empty array:

$stations = Station::all();
$station_ids = [];

foreach ($stations as $station) {
    $station_ids[] =  $station->id;
}
return $station_ids;

Once you have all station_ids, you can then loop in your view like this

Controller

$stations = Station::all();
    $station_ids = [];

    foreach ($stations as $station) {
        $station_ids['ids'] =  $station->id;
    }
    return view('view.blade.php',$station_ids);

view

@foreach($ids as $id)
      {{ $id->fieldname}}
  @endforeach

You can not assign a single variable in a loop to a single id.

Md Mazedul Islam Khan
  • 5,318
  • 4
  • 40
  • 66
Peace Ngara
  • 673
  • 5
  • 7