wishlist not showing laravel - php

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.

Related

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

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

How can I connect one to many relationship in laravel eloquent?

Image model:
public function getImage(){
return $this->belongsTo('App\Product');
}
Product model:
public function product(){
return $this->hasMany('App\Image');
}
Controller:
public function index()
{
$products = Product::all(); //Select *
return view('product.index',compact('products'));
}
View:
#foreach($products as $product)
<td>{{ $product->getImage->image_link}}</td>
#endforeach
Error:
Trying to get property 'image_link' of non-object (View:
C:\xampp\htdocs\ecommerce\resources\views\product\index.blade.php)
Their should be a relation between post and product with product id
In Product.php
public function product(){
return $this->hasMany('App\Image');
}
then you can use $product->images->image_link
Is there a product_id field in your image table? and is there hasMany in your Product model?
In your Product model should be a relation like as below.
Product.php
public function images(){
return $this->hasMany('App\Image');
}
After then, you can use images in product for loop $product->images->image_link.

laravel eloquent multiple tables where criteria

I have spent two days trying to solve this issue but no luck.
I have 3 tables, categories, items and related items, every item is under one category and category can have many items, this part working fine, now the issue is in related item, I have in the table realteditems 3 fields, id(just autoincrement), ritemf_id,riteml_id those refers to item_id in items table.
What I want to do is to display item with its details and related items to this item, means if item1 have many realted items,such item2,item3,item4 .. so need to display like this
item_title: item1
related item:
item2
item3
item4
controller
$items = Item::orderBy('category_id', 'asc')->with('category')->get()->groupBy('category_id');
$categories = Category::orderBy('category_id', 'asc')->get();
return view('home',['items' => $items,'ritems' => $ritems,'categories' => $categories]);
items modal
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function relateditems()
{
return $this->belongsTo('App\Relateditem', 'ritemf_id');
}
relateditems modal:
class Relateditem extends Model
{
protected $table="relateditems";
protected $fillable=['ritemf_id','riteml_id'];
protected $primaryKey='id';
public $timestamps=false;
public function items()
{
return $this->belongsTo('App\Item', 'item_id');
}
}
showing items with its category in blade(working fine)
#if (!empty($categoryItems->first()->category))
{{ $categoryItems->first()->category->category_name }} #else {{$category_id}} #endif
#foreach($categoryItems as $item)
{{$item->item_title}}
${{$item->item_price}}
#endforeach
#endforeach
relateditems()definition looks incorrect to me in Item model, Item may have more than one related items then this should be hasMany/beongsToMany association.
Assume its hasMany then update your item model as
public function relateditems() {
return $this->hasMany('App\Relateditem', 'ritemf_id');
}
And eager load your related items for each item
$items = Item::orderBy('category_id', 'asc')
->with(['category', 'relateditems'])
->get()
->groupBy('category_id');
I assume the groupBy method is used from collection class to group retrieved data not on database side
You need to fix both relations in Item Model and RelatedItem model. relateditems should be hasMany because an item can have many related item.
You also need to define belongsTo relation in RelatedItem to Item using riteml_id key
Item modal
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function relateditems()
{
return $this->hasMany('App\Relateditem', 'ritemf_id');
}
Relateditem modal:
class Relateditem extends Model
{
protected $table="relateditems";
protected $fillable=['ritemf_id','riteml_id'];
protected $primaryKey='id';
public $timestamps=false;
public function item() //i have change it to item instead items, because belongsTo always return single record
{
return $this->belongsTo('App\Item', 'riteml_id');
}
}
Fetch Data
$items = Item::orderBy('category_id', 'asc')->with('category','relateditems', 'relateditems.item')->get()->groupBy('category_id');
foreach($items as $categoryId => $groupItems){
echo $groupItems->first()->category;
foreach($groupItems as $item) {
echo $item->item_tile;
...
foreach($item->relateditems as $relatedItem){
if ($relatedItem->item){
echo $relatedItem->item->item_tile; //this will show you related item title
}
}
}
}
For Single Item
$item = Item::with('category','relateditems', 'relateditems.item')->find(1);
foreach($item->relateditems as $relatedItem){
if ($relatedItem->item){
echo $relatedItem->item->item_tile; //this will show you related item title
}
}

Access table data in Laravel

I'm trying to show a list of contacts for the logged in user. But obviously I'm doing something wrong.
I get a error on the contacts list page:
Trying to get property 'name' of non-object
User.php
public function contacts()
{
return $this->belongsToMany(Contact::class);
}
Contact.php
public function users()
{
return $this->belongsToMany(User::class);
}
ContactsController.php
public function index()
{
//
$user = Auth::user();
$user_contacts = $user->contacts()
return view('contacts.list')->with('contacts', $user_contacts);
}
list.blade.php
#foreach ($contacts as $contact)
* {{ $contact->name }} <br>
#endforeach
Table schema:
contacts:
id
created_at
updated_at
name
address
users:
id
name
password
remember_token
created_at
updated_at
contact_user:
contact_id
user_id
If you want to access pivot properties of your many to many relationship table u can access with pivot
#foreach ($contacts as $contact)
* {{ $contact->pivot->name }} <br>
#endforeach
Also creates a relatioship between contact and users
public function contacts()
{
return $this->belongsToMany(Contat::class)->withPivot(['your', 'pivot','columns']);
}
Hope this helps
In your controller you have the following;
public function index()
{
$user = Auth::user();
$user_contacts = $user->contacts()
return view('contacts.list')->with('contacts', $user_contacts);
}
It needs to be the following;
public function index()
{
$user = Auth::user();
$user_contacts = $user->contacts
return view('contacts.list')->with('contacts', $user_contacts);
}
Using $user->contacts()(method) will return an instance of the query builder for that relationship, where as $user->contacts(property) will return a collection with results from a select query.
You must return your pivot table's data in the relation as below:
public function contacts()
{
return $this->belongsToMany(Contat::class)->withPivot(['your', 'pivot','columns']);
}
And you must get relation data like below:
$user_contacts = $user->contacts // Not $user->contacts()

Categories