Home > other >  Laravel ::all() command only returns 1 record
Laravel ::all() command only returns 1 record

Time:11-18

Hi guys I am trying to get all the records from a table in my database using $pools = \App\pool::all();
The database currently has 3 records in it but only the first record is returned

foreach($pools as $pool)
    {return $pool;}

{"poolId":1,"poolName":"TestPool","pAdminId":70,"poolStatus":1,"created_at":"2021-11-17 08:06:57","updated_at":"2021-11-17 08:06:57"}

My SQLDB

This has not been a problem before when using ::all() The same is true when using

$pools = \App\Pool::where('pAdminId',$user->id)->get();

The $user->id returns 70, this is also happening for another table of mine Poolmembers, both were created using the php artisan make:model command and rolled back once to change a datatype and then migrated again.

The model for pool looks as follow


namespace App;

use Illuminate\Database\Eloquent\Model;

class Pool extends Model
{
    //
    protected $primaryKey = 'poolId';
    protected $fillable = ['poolId', 'poolName', 'pAdminId', 'poolStatus'];
}

Any help would be appreciated

Thank you

CodePudding user response:

You can get only one return statement in a function so if you put return inside the loop the execution of a function will stop. https://www.php.net/manual/en/function.return.php

foreach($pools as $pool) {
    echo $pool->poolId;
}

if you want to skip or break an iteration in PHP you can use continue or break inside your loop.

CodePudding user response:

Armand, You are using return in for loop. Due to which it shows you only a single record because it returns on the first index of the array. Try this

foreach($pools as $pool)
    {
echo $pool->poolId; //it will return id of each record;
}
   
  • Related