Laravel - Many To Many - php

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

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.

How to get username from users table in laravel?

Here is the Controller code I have
public function index()
{
$ajobs = Job::all();
return view('jobs_all', ['jobs' => $ajobs]);
}
This shows all my Table Data. I have stored user id as another column named created_by
In the View, I get value by ID, how how can I get the Username from Users table.
#foreach ($jobs as $ajob)
{{ $ajob->created_by }} //Here instead of UserID, how can i get Username by matching the UserID with UsersTable ?
#endforeach
Add next method to your "Job" model:
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
now you can add ORM param "with" to your method "index":
public function index() {
$ajobs = Job::with('user')
->all();
return view('jobs_all', ['jobs' => $ajobs]); }
now we have access to user model fields, and you can show them this way:
#foreach($jobs as $ajob)
{{ $ajob->user->name }}
#endforeach
More info about laravel relations here: https://laravel.com/docs/8.x/eloquent-relationships#one-to-one
you can use laravel eloquent belongsTo relationship. in your Job model add the following method.
public function user()
{
return $this->belongsTo(User::class, 'created_by');
//assuming your user model name is User and both models are in the same namespace. if not, adjust according to your structure.
}
and then you can use this relationship to get the user name like
#foreach ($jobs as $ajob)
{{ $ajob->user->name }}
//name is the column name from the user table. change if necessary.
#endforeach
You can use relations but in fast way on your situation you can join your tables:
$user_id = DB::table('jobs')
->select('users.id')
->join('jobs', 'jobs.user_id', '=', 'users.id')
->get();
=> add on your job table as foreginId user
$table->timestamp('created_at')->useCurrent();
$table->foreignId('created_by')->constrained('users')->onUpdate('cascade')->onDelete('cascade');
**That Function add on job model**
public function getCreatedAttribute()
{
return ucfirst($this->user->name);
}
=>relationship add on job table
public function user()
{
return $this->belongsTo(User::class,'id','created_by');
}
=>created display your user name
#foreach ($jobs as $ajob)
{{ $ajob->created}}
#endforeach
=>listing controller
public function index() {
$jobs = Job::with(['user']);
return view('jobs_all', compact('jobs')); }

wishlist not showing laravel

I'm creating a wishlist ,so that user can be able to save item to wishlist. I have products table, wishlist table which has user_id and product_id columns and also I have pivot table product_wishlist table which has foreign key product_id and wishlist_id. The problem is it doesn't display the product information like price, name etc and it shows no errors, I don't know if my relations are wrong or there is something else, how can I fix this ?
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->belongsToMany(Product::class,'product_wishlist','wishlist_id', 'product_id');
}
}
Product.php
public function wishlist(){
return $this-belongsToMany(Wishlist::class);
}
Wishlist controller
public function index()
{
$user = Auth::user();
$wishlists = Wishlist::with('product')
->where('user_id', $user->id)
->orderby('id', 'desc')
->paginate(6);
//dd($wishlists);
return view('front.wishlist', compact('user', 'wishlists'));
}
Blade
#foreach($wishlists as $wishlist)
<h3 >USD {{$wishlist->name }}</h3>
<h4 >USD {{$wishlist->price }}</h4>
#endforeach
You will need to do
{{ $wishlist->product->price }}
As the price is an attribute on the product you need to access the product object before accessing the price.

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);
}

Loop orders in Laravel eloquent

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.

Categories