nischalinn
nischalinn

Reputation: 1175

pass data from joined table

I have built an eloquent query for inner join of two tables. I am getting data from the database, debugged using dump($ordered_books);

function fetchData()
    {
        $ordered_books = DB::table('ordered_books')
        -> join('books', 'books.id','=','ordered_books.BookID')
        -> select('books.BookName', 'ordered_books.BilledNum','ordered_books.BilledDate','ordered_books.Qunatity',
        'ordered_books.Price', 'ordered_books.BillPaid', 'ordered_books.Remarks' )
        -> get()->toArray();

        dump($ordered_books);

        return compact('ordered_books');
    }

But when I pass the data to view page, I am getting error:

Cannot use object of type stdClass as array

How to solve this error?

View page block

@foreach($ordered_books as $data)
 <tr>
     <td> {{$data['BookName']}} </td>
     <td> {{$data['BilledDate']}} </td>
     <td> {{$data['BilledNum']}} </td>
     <td> {{$data['Qunatity']}} </td>
     <td> {{$data['Price']}} </td>
     @if($data['BillPaid'] === 1)
                <td>PAID</td> 
            @else
                <td style="color:red">DUE</td>
            @endif
     <td> {{$data['Remarks']}} </td>
 </tr>
@endforeach

Upvotes: 0

Views: 49

Answers (3)

Peter Matisko
Peter Matisko

Reputation: 2253

The $data variable is not an array. It is a class. Try this:

$data->BookName

The variable from the get() function is of the type Collection of stdClass classes. You run toArray() on the Collection. That means, you have an array of StdClasses. You still have to use $data->variable

Upvotes: 2

Donnicias
Donnicias

Reputation: 186

Use object notation to fetch the values as shown below

 @foreach($ordered_books as $data)
  <tr>
   <td> {{$data->BookName}} </td>
   <td> {{$data->BilledDate}} </td>
   <td> {{$data->BilledNum}} </td>
   ...
 </tr>
@endforeach

Upvotes: 0

Teoman Tıngır
Teoman Tıngır

Reputation: 2901

I checked out what comes when we used toArray() method.. And you can see that in below, collection turn into array but items not.. they're still object..

array:6 [▼
  0 => {#254 ▶}
  1 => {#255 ▶}
  2 => {#256 ▶}
  3 => {#257 ▶}
  4 => {#258 ▶}
  5 => {#259 ▶}
]

As Peter Matisko mentioned, you should say

$data->BookName

Upvotes: 1

Related Questions