Gui O
Gui O

Reputation: 383

Laravel cannot use object of type Eloquent/Builder as array

As i'm now working with laravel, i have to display some data on the interface. But Laravel is installed on the computer X, and the database is on a distant Y server. For testing purpose, i am trying to display simple data from a table, the first information of the following table :

Table site : code_site varchar(255) primary key

So, this is how i made it :

database.php

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => '126.x.x.x',
    'database'  => 'MYNET',
    'username'  => 'mynet',
    'password'  => 'mypassword',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'port'      => '3308',
),

model/Site.php

<?php

class Site extends Eloquent {
<empty because i don't need relations for now> }

routes.php

Route::model('site', 'Site');
Route::get('liste_sites', array('uses' => 'HomeController@liste_sites', 'as' => 'liste_sites'));

liste_sites.blade.php

@for ($i = 0 ; $i < count($sites); $i ++)
    <p>{{$sites[$i]->code_site}}</p>
@endfor

HomeController.php

public function liste_sites() 
    {
        $sites = Site::select('code_site')
        ->orderBy('code_site','desc');

        return View::make('liste_sites', array( 'sites' => $sites, 'which_actif' => 1));
    }

But i get the error

Cannot use object of type Illuminate\Database\Eloquent\Builder as array

Is it because my data are not readable ?

Upvotes: 5

Views: 24923

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

Change this line:

$sites = Site::select('code_site')->orderBy('code_site','desc');

to this:

$sites = Site::select('code_site')->orderBy('code_site','desc')->get();

I'm pretty sure that should fix it.

Basically, until you call one of the closing functions ->get(), ->paginate(10) or ->first() $sites is treated as a Query, and not an array of Site objects, and as such can't be used in a view. Hope that helps!

Upvotes: 14

Related Questions