Display Fields of Relationship Query in Blade - laravel

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

Related

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

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

How to differentiate between empty collection & collection with no data after executing a query

I have two query from which one is executed on some particular event.
Now, I have to differentiate between collection which is empty(query when not executed) & collection that fetch no data from database.
public function dashboard()
{
$owned = DB::table('eusers')
->join('tasks', 'eusers.id', '=', 'tasks.task_assign_to')
->where('tasks.task_assign_to', '=',$id)
->get();
$filteredData = DB::table('tasks')
->join('eusers', 'eusers.id', '=', 'tasks.task_assign_to')
->where('tasks.task_status', '=', $filterKey)
->where('tasks.task_assign_to', '=', $id)
->get();
return view('euser.dashboard', compact('owned', 'filteredData'));
}
Now what I want is something like this :
<div class="row">
#if(isset($filteredData))
#foreach($filteredData as $data)
//Some code here...
#endforeach
#else
#foreach($owned as $data)
//Some code here...
#endforeach
#endif
</div>
Note : I got results only when $filteredData have some data in it.
Add condition of not empty as below:
<div class="row">
#if(isset($filteredData) && !empty($filteredData->toArray()))
#foreach($filteredData as $data)
//Some code here...
#endforeach
#else
#foreach($owned as $data)
//Some code here...
#endforeach
#endif

Select query with relationship laravel one to many

I have a relational mode like this:
Model Siswa
public function kelengkapan()
{
return $this->belongsTo('Modules\PesertaDidik\Entities\SiswaKelengkapan');
}
Model SiswaKelengkapan
public function siswas()
{
return $this->hasMany('Modules\PesertaDidik\Entities\Siswa');
}
I want to use select query with relational
in this controller:
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
this is my blade...
<td>{{$data->kelengkapan->kelas_masuk}}</td>
but an error in the blade like this
Trying to get property 'kelas_masuk' of non-object
I want to show kelas_masuk in the table,
How to use the select query with relation eloquent?
There is no issue with your select query
You are trying to retrieve the data on null that's why you get Trying to get property 'kelas_masuk' of non-object
Controller
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
Blade file
Assume you are using foreach or forloop
<td>{{ $data->kelengkapan->kelas_masuk ?? '--' }}</td> //coalescing operator
Or
<td>
#if(!is_null($data->kelengkapan))
{{ $data->kelengkapan->kelas_masuk }}
#endif
</td>
Here you are used get() method so it's return all the rows
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
in your blade
<td>{{$siswa[0]->kelengkapan->kelas_masuk}}</td>
You can also use foreach loop.
#foreach($siswa as $data)
<tr>
<td>{{$data->kelengkapan->kelas_masuk}}</td>
</tr>
#endforeach

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 Pagination with eloquent Queries

I am trying to paginate my template which has a table on it.
This is my function in the controller which has the eloquent queries.
public function orderbydate()
{
$order =DB::table('sales_flat_order_items as s')
->leftJoin('sales_flat_orders as w', 'w.entity_id','=','s.order_id')
->select(array(DB::Raw('sum(s.amount_refunded) as amount_refunded'),
DB::Raw('sum(s.row_total) as row_total'),
DB::Raw('sum(s.discount_amount) as discount_amount'),
DB::Raw('sum(s.tax_amount) as tax_amount'),
DB::Raw('sum(s.qty_ordered) as qty_ordered'),
DB::Raw('sum(w.subtotal) as subtotal'),
DB::Raw('sum(w.total_invoiced) as total_invoiced'),
DB::Raw('sum(w.shipping_amount) as shipping_amount')))
->where('qty_canceled','=','0')
->where('status','!=','canceled')
->get();
$orderbydate = DB::table('sales_flat_order_items as s')
->leftJoin('sales_flat_orders as w', 'w.entity_id','=','s.order_id')
->select(array(DB::Raw('sum(s.amount_refunded) as amount_refunded'),
DB::Raw('sum(s.row_total) as row_total'),
DB::Raw('sum(s.discount_amount) as discount_amount'),
DB::Raw('sum(s.tax_amount) as tax_amount'),
DB::Raw('sum(s.qty_ordered) as qty_ordered'),
DB::Raw('sum(w.subtotal) as subtotal'),
DB::Raw('DATE(w.created_at) days'),
DB::Raw('sum(w.total_invoiced) as total_invoiced'),
DB::Raw('sum(w.shipping_amount) as shipping_amount')))
->where('qty_canceled','=','0')
->where('status','!=','canceled')
->groupBy('days')
->orderBy('s.created_at')
->get();
return View::make('sales_flat_orders.orderbydate', compact('order','orderbydate'), ['orderbydate'=>Paginate(3)]);
}
I want to use pagination in my template. So i ma doing like this.
#foreach(array_chunk($orderbydate->getCollection()->all(), 3) as $row)
<div class = "row">
#foreach($row as $s)
<article class = "col-md-4">
<tbody>
<tr class="odd gradeX">
<td>{{date("d F, Y",strtotime($s->days))}}</td>
<td>{{ round($s->qty_ordered, 2) }}</td>
<td>{{round($s->subtotal,2)}}</td>
<td>{{round($s->tax_amount,2)}}</td>
<td>{{round($s->discount_amount,2)}}</td>
<td>{{round($s->row_total,2)}}</td>
<td>{{round($s->amount_refunded,2)}}</td>
<td>{{round($s->total_invoiced,2)}}</td>
<td>{{round($s->shipping_amount,2)}}</td>
</tr>
</article>
#endforeach
#endforeach
But thins does not work. Where am i going wrong?
Thanks in advance
If you want to use pagination instead of get method you need to use paginate method.
For example the working pagination should work like this:
Paginator::setCurrentPage($page);
Paginator::setBaseUrl($baseUrl);
Paginator::setPageName('page');
$users = User::paginate(15);
now in Blade template you can display users in foreach loop and add pagination links:
#foreach ($users as $user)
{{{ $user->name }}}
#endforeach
{{ $users->links() }}
You should definitely look also at Pagination documentation

Resources