Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$path - laravel

I wrote a relation belongsToMany between products and photos and now I want to show products in the home page. I did it like so:
#foreach ($latestProducts as $product)
<img src="{{$product->photos()->path}}">
#endforeach
homeController:
public function index()
{
$latestProducts = Product::orderBy('created_at' , 'desc')->limit(10)->get();
return view('front.layouts.index' , compact('latestProducts'));
}
photo model:
public function products() {
return $this->belongsToMany(Product::class);
}
product model:
public function photos() {
return $this->belongsToMany(Photo::class);
}
I got Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$path .And when I write {{$product->photos[0]->path}} , the error changes to "Undefined array key 0. Also when I write {{$product->photos->path}} ,I get an error as "Property [path] does not exist on this collection instance."

I believe you got a photo attribute/field in the Photo model. Because photos is a collection of photos, you might want to write:
#foreach ($latestProducts as $product)
#foreach ($product->photos as $photo)
<img src="{{$photo->path}}">
#endforeach
#endforeach
And only the first photo:
#foreach ($latestProducts as $product)
<img src="{{$product->photos->first()->path}}">
#endforeach
// Or to be safe
#foreach ($latestProducts as $product)
<img src="{{optional($product->photos->first())->path}}">
#endforeach
// Or this in php 8
#foreach ($latestProducts as $product)
<img src="{{$product->photos->first()?->path}}">
#endforeach

You have to use
{{ $product->photos->path }}
cause when you deal with relations in blade you deal with it as a property of class of the father class unlike when you deal with it in eloquent ORM you can use photos()

Basically the error is saying that there is no property photos in the $products. Assuming that the table name is correct and the foreign keys too
you can just do:
public function index()
{
$latestProducts = Product::with('photos')->orderBy('created_at' , 'desc')->limit(10)->get();
return view('front.layouts.index' , compact('latestProducts'));
}
And in blade file try to remove the (), because it will load the relationship.
#foreach ($latestProducts->photos as $product)
<img src="{{$product->path}}">
#endforeach

Related

get access to collection laravel

I am a new learner of the laravel framework working on 3 models
customer,
accidents,
License
where the relations are as follows:
public function License()
{
return $this->hasOne(license::class,'driver_id');
}
public function cars()
{
return $this->hasMany(car::class);
}
In the controller I do like this:
public function AdminCustomers()
{
$customers = Customer::with('cars')->with('License')->get();
return view('admin.AdminCustomers',compact('customers'));
}
now I want to display all 3 models' data on view.blade page
<tbody>
#foreach($customers as $customer)
<tr>
<td>{{$customer->id}}</td>
<td>{{$customer->name}}</td>
<td>{{$customer->adderss}}</td>
<td>{{$customer->mobileNo}}</td>
<th>{{$customer->License->id}}</th>
<th>{{$customer->License->Exp}}</th>
<td>{{$customer->cars->id}}</td>
<td>{{$customer->cars->color}}</td>
<td>{{$customer->cars->model_no}}</td>
<td>{{$customer->cars->company}}</td>
</tr>
#endforeach
</tbody>
But it doesn't work and I didn't know where is the problem
the error Exception
Property [id] does not exist on this collection instance.
$customer->cars will return a collection as the relationship is hasMany so you need to loop over the collection in the view
#foreach($customers as $customer)
<tr>
<td>{{$customer->id}}</td>
<td>{{$customer->name}}</td>
<td>{{$customer->adderss}}</td>
<td>{{$customer->mobileNo}}</td>
<th>{{$customer->License->id}}</th>
<th>{{$customer->License->Exp}}</th>
#foreach($customer->cars as $car)
<td>{{$car->id}}</td>
<td>{{$car->color}}</td>
<td>{{$car->model_no}}</td>
<td>{{$car->company}}</td>
#endforeach
</tr>
#endforeach
check the name in the corrisponding table on db, and if its different from "id" specify it into the model, as
protected $primaryKey = 'xxx';

Laravel blade echo the value doesn't work

I have two tables ..
User and UserMeta
I made relationship between them with hasOne().
Model
public function user_meta() {
return $this->hasOne('App\UserMeta');
}
Controller
public function index() {
$users = User::orderBy('id', 'desc')->paginate(10);
return view('users.index')->with('users', $users);
}
View
#forelse ($users as $user)
{{ $user->user_meta->country }}
#empty
#endforelse
This return error
Trying to get property 'country' of non-object
But here if I use dd() like this.
#forelse ($users as $user)
{{ dd($user->user_meta->country) }}
#empty
#endforelse
I can see the value return correctly. United State
dd stop loop execution for first element. If you uses dump helper, you will see this error again after several iterations. You need check for null:
#forelse ($users as $user)
#if(!is_null($user->user_meta))
{{ $user->user_meta->country }}
#endif
#empty
#endforelse

Laravel 5 how paginate with hasMany relationship

I have a relationship this like;
public function foods() {
return $this->hasMany('App\models\food\food', 'category_id', 'id');
}
My controller file content;
$datas = food_category::where('slug', $slug)->with('foods')->paginate(12);
But incoming datas in there all datas and this is causing bad performance. I want to paginate apply relationship datas.
If you want to paginate foods, try adding a separate method for that:
Model:
class food_category
{
public function getFoodsPaginatedAttribute()
{
return $this->foods()->paginate(12);
}
}
Controller:
$datas = food_category::where('slug', $slug)->get();
View:
#foreach ($datas as $data)
#foreach ($data->foods_paginated as $food)
{{ $food->name }}
#endforeach
#endforeach
Pass paginated collection to the view:
//view
#foreach ($datas as $data)
// do what you need
#endforeach
//link
{{$datas->links()}}

Display Fields of Relationship Query in Blade

After binding tables in a model and writing a query, fetched data in a Blade shows error.
Trying to get property of non-object
Model
<?php
public function unit()
{
return $this->belongsTo('TEST\Units');
}
Query
$inst = Instructions::with('unit')
->where('id',$inst_id)
->first()
->get();
Model
#foreach ($inst as $item)
<pre>{{$item->units->name}}</pre>
#endforeach
However, when using this code and I delete a name or other field, no error displays...
#foreach ($inst as $item)
<pre>{{$item->units}}</pre>
#endforeach
output:
{"id":1,"name":"UNIT 101","description":null,"created_at":"2017-03-06 13:30:18","updated_at":"2017-03-06 13:30:18"}
Solved
#foreach ($inst as $item)
#if (!empty($item->unit->id))
<pre>{{$item->unit->name}}</pre>
#endif
#endforeach

Laravel get posts by category

I'm trying to figure out how to get all the posts for a category using Laravel Eloquent 5.3.
I have three tables..
**Posts**
id | title | text
**Term_relationships**
term_id | post_id
**Terms**
id | name
Eloquent Models
class Term extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post', 'term_relationship');
}
}
class Post extends Model
{
public function terms()
{
return $this->belongsToMany('App\Term', 'term_relationship');
}
}
class Term_relationship extends Model
{
}
I've tried with for example
Term::where('name', $category)->posts->get();
Easy,
if you want Posts with Terms do this
$data = App\Post::with('terms')->get();
in your view :
#foreach($data as $post) // will loop over posts and show title
<div>{{$post->title }} </div>
#foreach($post->terms as $term)
<div> {{ $term->title }} </div> // will loop and echo all terms for current post
#endforeach
#endforeach
if you want Terms with posts do this
$data = App\Term::with('posts')->where('name', $category)->get();
in your view
#foreach($data as $term) // will loop over terms and show title
<div>{{$term->title }} </div>
#foreach($term->posts as $post)
<div> {{ $post->title }} </div> // will loop and show all posts in each term
#endforeach
#endforeach
i think the seconds way suits your needs better since int he first example u will need to use wherehas and a closure

Resources