Muhammad Kazim
Muhammad Kazim

Reputation: 621

Laravel: how to get value from query builder object

I am new in laravel. i have a table but dont have model for this. I am using below to fetch record.

$classes = DB::table('school_classes')->get();
return view('classes', ['allClass' => $classes]);

it returns below:

[{"id":1,"register_school_id":1,"class":"I","section":"A","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":2,"register_school_id":1,"class":"I","section":"B","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":3,"register_school_id":1,"class":"I","section":"C","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},    {"id":4,"register_school_id":1,"class":"I","section":"D","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},        
{"id":5,"register_school_id":1,"class":"I","section":"E","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"}]

how I can pick the value separately of each item... i tried foreach but getting error. plz help. thanks in advance.

Upvotes: 1

Views: 1375

Answers (2)

Raghu Aryan
Raghu Aryan

Reputation: 93

You want to get data in array format, then you can use "toArray" & also easily access data using foreach loop Laravel function.

$classes = DB::table('school_classes')->get()->toArray();

return view('classes', ['allClass' => $classes]);

Upvotes: 0

Yamen Ashraf
Yamen Ashraf

Reputation: 2950

The query builder returns a Illuminate\Support\Collection instance. You can access the collection as below:

@foreach($allClass as $class)
    {{ $class->id }}
@endforeach

Also check Collections

Upvotes: 3

Related Questions