5

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 ?

1
  • Your $sites variable holds an instance of Illuminate\Database\Eloquent\Builder because you have not called a method on it to retrieve the data the query builder is relating to. As Tim says below, you can call get() on it and you will have the results returned. As you can see with your statement, you call select() then orderBy(). The object returned by select is chain-able to allow you to call subsequent methods in order to build your query. Things like order, limit etc. The get() method call will finally execute the built query. Commented Nov 6, 2014 at 14:18

1 Answer 1

14

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!

Sign up to request clarification or add additional context in comments.

2 Comments

It is working I wasn't aware that paginate execute the request. Thanks !
No problem! I ran into this issue in a number of my queries until I found this out :P.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.