Loop orders in Laravel eloquent - php

I have three tables order_product, users and orders table, they all related each other and they work fine(as expected). I want to loop orders and not OrderProduct and also display them in the view . So far it is looping OrderProduct instead of Order, how can I loop orders and display in the view?
Here are the code.
Blade view
#foreach ($orders as $order)
<div>{{ presentPrice($order->billing_total) }}</div>
#endforeach
#foreach ($order->productInfo as $product)
<div>{{ presentPrice($product->price) }}</div>
#endforeach
User.php
public function sellerOrders()
{
return $this->hasMany(OrderProduct::class, 'seller_id');
}
OrderProduct.php
public function productInfo()
{
return $this->belongsTo('App\Product');
}
public function orderInfo()
{
return $this->belongsTo(Order::class, 'order_id');
}
Order.php
public function user()
{
return $this->belongsTo('App\User', 'seller_id');
}
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity','total','Subtotal');
}
Controller
$orders = Auth::user()->sellerOrders()->with('productInfo','orderInfo')->get();
When I dd($orders) it shows this
Collection {#306 ▼
#items: array:2 [▼
0 => OrderProduct {#300 ▶}
1 => OrderProduct {#301 ▶}
]
}

Your User class has the relationship defined with OrderProduct, not Order.
public function sellerOrders()
{
return $this->hasMany(OrderProduct::class, 'seller_id');
}

dd($order) is returning what it should. Since the sellerOrders() relationship is with the OrderProduct table. You did eager load order with that call, though, so you should be able to just access that one-to-one directly on the blade.
#foreach ($orders as $order)
<div>{{ presentPrice($order->orderInfo->billing_total) }}</div>
#endforeach
#foreach ($order as $product)
<div>{{ presentPrice($product->productInfo->price) }}</div>
#endforeach
The above would get you what you're looking for.

Related

Why belongToMany is not working in Laravel?

I'm trying to define a Many to Many relationships using "belongsToMany" relationship between 2 tables with a lookup table.
These are my tables:
I have a category_product like this
ProductController.php
public function index()
{
$categories = Category::with('products')->where('parent_id', 0)->get();
return view('Home.lists.product', compact('categories'));
}
Category..php
public function products()
{
return $this->belongsToMany(Product::class);
}
product.blade.php
#foreach($categories as $category)
#foreach($category->products as $product)
#dd($product->id)
#endforeach
#endforeach
I see this. 3 // resources\views/Home/lists/portfolio.blade.php
I want to return 3,5,4.
It is returned only 3. and I want to return all products.

Adding product to wishlist laravel

I'm creating a functionality which allows the user to add product in wishlist, but I'm getting an error Trying to get property of non-object when I click the (whishlist blade), the error comes from this line <h4>USD {{$wishlist->product->price }}</h4> if I remove the $product it displays no price how do i fix this?
Wishlist Controller
public function index()
{
$user = Auth::user();
$wishlists = Wishlist::where("user_id", "=", $user->id)->orderby('id', 'desc')->paginate(10);
return view('wishlist', compact('user', 'wishlists'));
}
Blade
#if (Auth::user()->wishlist->count() )
#foreach($wishlists as $wishlist)
<h2>USD {{$wishlist->product->price }}</h2>
<h4>USD {{$wishlist->product->name }}</h4>
#endforeach
#endif
Wishlist.php
class Wishlist extends Model
{
protected $table = "wishlist";
protected $fillable=['product_id','user_id'];
public function user(){
return $this->belongsTo(User::class);
}
public function product(){
return $this->belongsTo(Product::class);
}
}
User.php
public function wishlist(){
return $this->hasMany(Wishlist::class);
}
Product.php
public function wishlist(){
return $this->hasMany(Wishlist::class);
}
You should first change how you check the count of wishlist, since it runs a heavy query that recovers all wishlists then count them. And also remove the $ in $product as #lucasArbex suggested
#if ($wishlists->count() )
#foreach($wishlists as $wishlist)
<h2>USD {{$wishlist->product->price }}</h2>
<h4>USD {{$wishlist->product->name }}</h4>
#endforeach
#endif
Also change your controller and use the relation on your user
public function index()
{
$user = Auth::user();
$wishlists = $user->wishlist()->with('product')
->orderby('id', 'desc')
->paginate(10);
return view('wishlist', compact('user', 'wishlists'));
}
Firstly, you should access the product relation like so (removing $):
$wishlist->product->price
Secondly, you should eager load the wishlist's product using the ::with() query builder:
public function index()
{
$user = Auth::user();
$wishlists = Wishlist::with('product')
->where('user_id', $user->id)
->orderby('id', 'desc')
->paginate(10);
return view('wishlist', compact('user', 'wishlists'));
}
Also, if I am correct, your product relation is wrong.
Your wishlist should have many products (rather than the other way around).
In your frontend, you will need to loop through all of the wishlist's products:
#foreach($wishlist->products as $product)
{{ $product->price }}
#endforeach
Change the relation in your Wishlist class to hasMany:
public function products()
{
return $this->hasMany(Product::class);
}

Invalid argument supplied for foreach()

Newbie here. I've been working on a one to many relationship in Laravel 5.4. I'm working on reading the relationship between User and State. I keep getting this error. I have data in the tables. Here is the view:
#foreach ($user->states as $note)
<li>{{ $note->name }}</li>
#endforeach
Here is the User model:
class User extends Model
{
use SoftDeletes;
public function state(){
return $this->belongsTo(State::class);
}
public function role(){
return $this->belongsTo(Role::class);
}
public function district(){
return $this->belongsTo(District::class);
}
Here is the State model:
class State extends Model
{
protected $fillable = [
'name'
];
public function users(){
return $this->hasMany(User::class);
}
}
Check array or object count before applying foreach loop. It is really a bad practice of using loop without checking the array count.
#if(isset($user->states) && count($user->states) > 0)
#foreach ($user->states as $state)
<li>{{ $state->name }}</li>
#endforeach
#else
No Records Found
#endif
Check get results is not a blank $results != FALSE You can convert this snippet in laravel way
<?php
if($user->states != FALSE){
foreach ($user->states as $note){
echo '<li>'.$note->name.'</li>';
}
}else{
echo 'No Results Found!';
}
?>

Laravel : How to access many to many relationship data Ask

I have category and subcategory table with many to many relationship
class Category extends Model {
protected $table='categories';
protected $fillable=['name'];
public function subcategories() {
return $this->belongsToMany('App\Modules\Subcategory\Models\Subcategory', 'categories_subcategories', 'category_id', 'subcategory_id');
}
}
Subcategory
class Subcategory extends Model {
protected $table='subcategories';
protected $fillable=['name'];
public function categories()
{
return $this->belongsToMany('App\Modules\Category\Models\Category', 'categories_subcategories', 'subcategory_id', 'category_id');
}
}
in controller
public function catSubList()
{
$subcategories = Subcategory::with('categories')->get();
return view('Subcategory::category_subcategory',compact('subcategories'));
}
But in view when i tried to access the data with following view
#foreach($subcategories as $row)
<td>{{$i}}</td>
<td>{{$row->name}}</td>
<td>{{$row->categories->name}}</td>
#endforeach
I got the error like :
ErrorException in Collection.php line 1527: Property [name] does not exist on this collection instance.
How do i access $row->categories->name ? anyone with the suggestion please?
You have to make another foreach() loop Because your subcategories belongsToMany categories. row->categories returns a collection, not an object. Thus the error.
<td>{{$row->name}}</td>
<td>{{$row->categories->name}}</td>
#foreach($row->categories as $category)
<td>{{$category->name}}</td>
#endforeach
Update
Getting a category with all subcategories. Simply invert your query
$category = Category::with('subcategories')
->where('name', '=', 'cars')
->first();
//will return you the category 'cars' with all sub categories of 'cars'.
Without eager loading
$category = Category::find(1);
$subacategories = $category->subcategories;
return view('Subcategory::category_subcategory', compact('category', subcategories));

Laravel - Many To Many

I have two main tables with relationships many to many and a pivot table.
Tables
Model Product
public function orders()
{
return $this->belongsToMany('App\Order');
}
Model Order
public function products()
{
return $this->belongsToMany('App\Product', 'OrderDetails');
}
And
$orders = Equipment::all();
#foreach($orders as $order)
#foreach($order->products as $product)
{!! $product->name !!} //it works
// How to print the value of the quantity?
#endforeach
#endforeach
What should I do to print the value of the quantity?
Try ->pivot->quantity:
{!! $product->pivot->quantity !!}
Also, add withPivot to a ralationship:
return $this->belongsToMany('App\Product', 'OrderDetails')->withPivot('quantity');
https://laravel.com/docs/5.2/eloquent-relationships#many-to-many

Categories