skip to Main Content

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 IlluminateDatabaseMySqlConnection 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!

5

Answers


  1. Chosen as BEST ANSWER

    This is how it looks now and it returns the values in the localhost.

    function list(){  
        foreach(DB::table('sport')->get() as $val){
            print_r($val);
        } 
        }
    

  2. 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.

    Login or Signup to reply.
  3. You have to get the sport table data first and then loop over on it:

    $sports = DB::table('sport')->get();
    
    foreach($sports as $sport){
      // $sport->table_field; do something here
    }
    
    Login or Signup to reply.
  4. class ProductController extends Controller
    {
        
        function list(){  
           $serve = DB::table('sport')->get(); 
              foreach($serve as $val){
               // code
              } 
        }
    
        
    }
    
    Login or Signup to reply.
  5. To loop in a table you can use:

    DB::table('sports')->orderBy('id')->chunk(100, function ($sports) {
        foreach ($sports as $sport) {
            //your code
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search