I have a query that works before using laravel eloquent method
$products = Product::where('category', 'ILIKE', '%'.$conditionTxt.'%')
->orderBy('created_at', 'desc')
->get();
But after using query builder approach
$products = DB::table('products')
->where('category', 'ILIKE', '%'.$conditionTxt.'%')
->orderBy('created_at', 'desc')
->get();
It returns this error:
Undefined property: stdClass::$inventory
Here is my model and portion of the view where it points the error.
Model
public function inventory(){
return $this->hasMany('App\InventoryRecord\InventoryRecord');
}
View:
<td>
<?php
for($i = 0; $i < count($val->inventory); $i++){
if( $val->inventory[$i]->total_qty <= 50 ) { ?>
<span style="color:#C00"><?php echo $val->inventory[$i]->total_qty.' -'; ?></span>
<?php }else{ ?>
<span style="color:#25A602"><?php echo $val->inventory[$i]->total_qty.' -'; ?></span>
<?php
}
}
?>
</td>
When you use query builder approach it returns an Illuminate\Support\Collection
containing the results where each result is an instance of the PHP StdClass
object (not a model object). You may access each column's value by accessing the column as a property of the object.
But you can't access the Model relations because you have PHP StdClass
object.
I would suggest you, stick to Laravel eloquent
.
You are mixing up two different pieces of functionality. Laravel provides a data access layer, which is the Query Builder. Laravel also provides an ORM called Eloquent, which is built on top of the Query Builder.
When you use Eloquent to query the database, you will get instances of your Eloquent Models back.
When you use the Query Builder to query the database, you will get instances of stdClass
back.
The query builder doesn't, and shouldn't, know anything about your Eloquent models. If you need Eloquent functionality (like accessing your inventory
relationship), then you need to use Eloquent to query the database.