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!
>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 :
- id
- sport_name
- created_at
- 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.