John Davidson

php - Laravel ::all() command only returns 1 record

0 comments
Message:


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"}


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



My Answer:
It seems like there might be an issue with the way you are retrieving the records from the database. The `return $pool;` statement inside the foreach loop will only return the first record and exit the loop.

To get all the records and display them, you should remove the `return $pool;` statement and instead loop through the `$pools` variable to display each record. Here is an example:

php
$pools = \App\Pool::all();

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


This will loop through all the records in the `$pools` variable and display each one. Make sure to adjust the display logic according to your requirements.

If you are still only getting one record, there might be an issue with the data in your database or the way you are querying it. Double-check your database records and the query conditions to ensure they are correct.

Rate this post

5 of 5 based on 9942 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us