Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel foreach loop database

I’m kinda new to programming in general. I’m trying to loop through a table. There is a connection to the DB already. It’s giving me – "Object of class Illuminate\Database\MySqlConnection could not be converted to string"

class ProductController extends Controller
{
    
    function list(){  
    $serve = DB::table('sport'); 
    foreach($serve as $val){
        return strval($val);
    } 
    }

    
}

That’s my code so far. How can I fix that issue?

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

for iterating throgh table rows , you need to make your objects iterable ,
when you do :

 $serves = DB::table('sport'); 

you are not actually make it iterable ;
use get() method to make it terable:

 $serves = DB::table('sport')->get();

Now you can iterate over it .

foreach($serves as $serve){
   //$serve->field; 
}

notice that each $serve item is a model of Sport model
and now you can access the fields of sport table from this method

for eample if you have the fields in you sports table :

  1. id
  2. sport_name
  3. created_at
  4. updated_at

you can access them like this :

foreach($serves as $serve){
   echo $serve->id;
   echo $serve->sport_name;
}

finally please try to give better naming
and change $serves to $sports
and $serve to $sport to enhance code readibility.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading