unable to display data from eloquent relationship with laravel 5.4 - php

I want to display data from an eloquent relationship in my view but I seem to be doing something wrong. Here's my model relationship, controller and view
Product
class Product extends Model
{
protected $guarded = ['id'];
public function prices()
{
return $this->hasMany(Price::class, 'product_id');
}
}
Price
class Price extends Model
{
protected $guarded = ['id'];
public function product()
{
$this->belongsTo(Product::class);
}
}
HomeController
public function index()
{
$products = Product::with('prices')->get();
return view('home', compact('products'));
}
View
#foreach ($products as $product)
<tr>
<td>{{ $product->prices->date }}</td>
<td>{{ ucwords($product->name) }}</td>
<td>{{ $product->prices->cost }}</td>
</tr>
#endforeach
My view returns the error
Property [date] does not exist on this collection instance
How do i fix this error?

In hasMany relations you have a Collection as result, so you should have another foreach to access each Price. Try something like this:
#foreach ($products as $product)
#foreach ($product->prices as $price)
<tr>
<td>{{ $price->date }}</td>
<td>{{ ucwords($product->name) }}</td>
<td>{{ $price->cost }}</td>
</tr>
#endforeach
#endforeach

Related

Laravel data not being displayed

I am trying to read data from a local collections from my mongodb database. Name of database Intuit name of collection post.
Code inside PostController:
<?php
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller{
public function home() {
$posts = Post::with(['user'])->get();
return view('home', ['posts' => $posts->toArray()]);
}}
Code inside Post:
class Post extends Model{
use HasFactory;
protected $fillable = [
'STATUS',
'DDC_CODE',
'TRADE_NAME',
'SCIENTIFIC_CODE',
'SCIENTIFIC_NAME',
'INGREDIENT_STRENGTH',
'DOSAGE_FORM_PACKAGE',
'ROUTE_OF_ADMIN',
'PACKAGE_PRICE',
'GRANULAR_UNIT',
'MANUFACTURER',
'REGISTERED_OWNER',
'UPDATED_DATE',
'SOURCE'
];}
All of the above are the titles of the columns in the table.
Next home.blade.php:
<!DOCTPE html>
<html>
<head>
<title>View Records</title>
</head>
<body>
<table border = "1">
<tr>
<td>Id</td>
<td>STATUS</td>
<td>DDC_CODE</td>
<td>TRADE_NAME</td>
<td>SCIENTIFIC_CODE</td>
<td>SCIENTIFIC_NAME</td>
<td>SCIENTIFIC_CODE</td>
<td>INGREDIENT_STRENGTH</td>
<td>DOSAGE_FORM_PACKAGE</td>
<td>ROUTE_OF_ADMIN</td>
<td>PACKAGE_PRICE</td>
<td>GRANULAR_UNIT</td>
<td>MANUFACTURER</td>
<td>UPDATED_DATE</td>
<td>SOURCE</td>
</tr>
#foreach ($posts as $post)
<tr>
<td>{{ $post->_id }}</td>
<td>{{ $post->STATUS }}</td>
<td>{{ $post->DDC_CODE }}</td>
<td>{{ $post->TRADE_NAME }}</td>
<td>{{ $post->SCIENTIFIC_CODE }}</td>
<td>{{ $post->SCIENTIFIC_NAME }}</td>
<td>{{ $post->INGREDIENT_STRENGTH }}</td>
<td>{{ $post->DOSAGE_FORM_PACKAGE }}</td>
<td>{{ $post->ROUTE_OF_ADMIN }}</td>
<td>{{ $post->PACKAGE_PRICE }}</td>
<td>{{ $post->GRANULAR_UNIT }}</td>
<td>{{ $post->MANUFACTURER }}</td>
<td>{{ $post->REGISTERED_OWNER }}</td>
<td>{{ $post->UPDATED_DATE }}</td>
<td>{{ $post->SOURCE }}</td>
</tr>
#endforeach
</table>
</body>
</html>
The route handler is as follows
Route::get('view','App\Http\Controllers\PostController#home');
all of this seems to be fine but when I load up the application I see nothing but the column titles not sure what I am missing, I believe it is not working because the query in PostController is incorrect and need to change it as it is taken from another projec. Any and all help and suggestions are welcome.
Instead of
Post::with(['user'])->get();
use
Post::with(['user'])->all();
subject to user relationship is properly defined in your Post model
You are sending data as array, But you are trying to get them as object in your blade view file.
Instead of getting data like this:
$post->STATUS
Try using like this:
$post['STATUS']
Don't use ->toArray()
Pass data as below & variables will get displayed
return view('home', ['posts' => $posts)]);

Laravel one to many relationship doesn't work anymore

This relationship of mine was working last week, but it stopped working.
When i use it in my blade template it says: Trying to get property 'name' of non-object.
The weird thing is, when i use it in dd() it perfectly shows, but when i try to print it in blade, it doesn't.
Code PaymentsController
<?php
namespace App\Http\Controllers;
use App\Betaling;
use App\Settings;
use Illuminate\Http\Request;
class PaymentsController extends Controller
{
public function index(){
$user_id = auth()->user('id');
$role = auth()->user()->role_id;
$settings = Settings::where('user_id', $user_id->id)->first();
if ($role === 1){
$totaalaantalbetalingen = Betaling::all();
} else {
$totaalaantalbetalingen = Betaling::where('user_id', $user_id->id)->get();
}
return view('payments.index', compact(['totaalaantalbetalingen','role', 'user_id', 'settings']));
}
}
Code index.blade.php
#foreach($totaalaantalbetalingen as $betaling)
<tr>
<th scope="row">{{ $betaling->id }}</th>
#if($role === 1)
<td>{{ $betaling->user->name }} </td>
#endif
<td>{{ $betaling->customer->name }}</td>
<td>{{ $betaling->reference}}</td>
<td>€ {{ $betaling->amount}}</td>
<td>{{ $betaling->time_of_invoice }}</td>
<td>{{ $betaling->time_of_payment }}</td>
<td></td>
<td>{{ $betaling->user->location }}</td>
</tr>
#endforeach
code User model:
public function betalingen(){
return $this->hasMany(Betaling::class);
}
code Betaling model:
public function customer(){
return $this->belongsTo(User::class);
}
public function user(){
return $this->belongsTo(User::class);
}
code Customer model:
public function betaling(){
return $this->hasMany(Betaling::class);
}
pass auth()->user()->id and in blade file check !empty($totaalaantalbetalingen)
code User model:
public function betalingen(){
return $this->hasMany('App\Betaling','betalingenid','id'); // pass foreign key for ex.
}
code Betaling model:
public function customer(){
return $this->belongsTo('App\User','customer_id','id');// pass foreign key for ex.
}
public function user(){
return $this->belongsTo('App\User','user_id','id');// pass foreign key for ex.
}
code Customer model:
public function betaling(){
return $this->hasMany('App\Betaling','customer_id','id');// pass foreign key for ex.
}
Controller
public function index(){
$user_id = auth()->user()->id;
$role = auth()->user()->role_id;
$settings = Settings::where('user_id', $user_id)->first();
if ($role == 1){
$totaalaantalbetalingen = Betaling::all();
} else {
$totaalaantalbetalingen = Betaling::where('user_id', $user_id)->get();
}
return view('payments.index', compact(['totaalaantalbetalingen','role', 'user_id', 'settings']));
}
blade.php
#if(!empty($totaalaantalbetalingen) && isset($totaalaantalbetalingen))
#foreach($totaalaantalbetalingen as $betaling)
<tr>
<th scope="row">{{ $betaling->id ?? '' }}</th>
#if($role === 1)
<td> {{ $betaling->user->name ?? '' }} </td>
#endif
<td> {{ $betaling->customer->name ?? '' }} </td>
<td> {{ $betaling->reference ?? '' }} </td>
<td> € {{ $betaling->amount ?? '' }} </td>
<td> {{ $betaling->time_of_invoice ?? '' }} </td>
<td> {{ $betaling->time_of_payment ?? '' }} </td>
<td> </td>
<td> {{ $betaling->user->location ?? '' }} </td>
</tr>
#endforeach
#endif

How to paginate and show all records using hasMany in laravel 5.6?

I have two tables one table for general information about the order named orders and a detail table for information like products, notes and delivery date.
Basically, I want to show in the same page the table orders and for each order can be multiple products, notes, dates from the table detail, and also I want to paginate in order to show exactly 20 orders on each page and every product, note, date row with the same id_order.
In conclusion, on each page there are 20 orders from table orders but there can be 40 rows from table detail with products, notes, delivery date, because one order can contain more than one product. in fact I want to use rowspan html in order to show on the same row the detail.
This is my Orders model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class order extends Model
{
public $timestamps = false;
protected $fillable = ['client','number_order','file'];
public function details()
{
return $this->hasMany('App\Detail','orders_id')->orderBy('id', 'desc');
}
}
Detail model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Detail extends Model
{
protected $table = 'detail';
public function order()
{
return $this->belongsTo('Detail','orders_id');
}
}
My controller:
public function index()
{
$orders = Order::first(); //This works only with one record I cant show all records, all() is not working
$orders->setRelation('details', $orders->details()->paginate(10));
return view('orders.index', compact('orders'));
}
View:
<tbody>
#foreach ($orders->details as $detail)
<tr id="{{ $detail->orders_id }}">
<td>{{ $detail->product }}</td>
</tr>
#endforeach
</tbody>
You can use eager load details on order like this
public function index()
{
$orders = Order::with('details')->paginate(20);
return view('orders.index', compact('orders'));
}
In view
<table>
<tbody>
#foreach($orders as $order)
<tr>
<td>{{ $order->created_at }}</td>
<td>... put any order info here</td>
<td>
<label>Order Details:</label>
<table>
#foreach ($order->details as $detail)
<tr id="{{ $detail->orders_id }}">
<td>{{ $detail->product }}</td>
<td>{{ $detail->note }}</td>
</tr>
#endforeach
</table>
<td>
</tr>
#endforeach
</tbody>
</table>

hasMany relationship Laravel 5.4 Trying to get property of non-object

I have a relationship in my models with foreing keys, protected table.
This is my models:
Lot.php:
<?php
namespace App;
class Lot extends Model
{
protected $table = 'auct_lots_full';
protected $primaryKey = 'lot_id';
public function comments()
{
return $this->hasMany(Comment::class,'lot_id', 'lot_id');
}
}
Than related model Comment.php:
<?php
namespace App;
class Comment extends Model
{
public function lot()
{
return $this->belongsTo(Lot::class, 'lot_id', 'lot_id');
}
}
In my view I try to do this:
#foreach ($comments as $comment)
<dt>{{ $comment->lot }}</td>
#endforeach
It result this:
{"lot_id":391959148,"date":"2017-05-21","company":"MITSUBISHI","model_year_en":2005"}
Than in view I need to get only company information and I do this:
#foreach ($comments as $comment)
<td> {{ $comment->lot->company }}</td>
#endforeach
this result Error:
Trying to get property of non-object
I try to do this:
#foreach ($comments as $comment)
<td>
#foreach($comment->lot as $lot)
{{ $lot->company }}
#endforeach
</td>
#endforeach
And it also gives error:
Trying to get property of non-object
How can I get $comment->lot->company work?
Thanks, to Snapey from laracasts
when you do this
#foreach ($comments as $comment)
<td> {{ $comment->lot->company }}</td>
#endforeach
you are relying on EVERY comment having a lot and every lot having a company
You can use this to protect against empty properties
#foreach ($comments as $comment)
<td> {{ $comment->lot->company or '---'}}</td>
#endforeach
Then the loop will continue even if the lot does not have company

Accessing data from a relation in blade? - Laravel

I have this code snippet in my blade:
#foreach($products as $product)
<tr>
<td></td>
<td>{{ $product->name }}</td>
<td>{{$product->tags}}</td>
<td>{{$product->created_at}}</td>
<td>
// some other code and buttons
</td>
</tr>
#endforeach
In $product->tags ( tags is the name of my relation ) are the tags I need and some other things, but I only want the tags.
I tried to reach them with $product->tags->tag but this hasn't worked for me. Can anybody tell me how I can access only the tags?
Try this:
#foreach($product->tags as $tag)
<td>{{ $tag->tag }}</td>
#endforeach
$product->tags returns an array of Tag objects.
If you have a relationship set between your Products and it's Tags (https://laravel.com/docs/5.1/eloquent-relationships)
Products Model
//namespace and use statements
class Products extends Model
{
/**
* Get all of the tags for the product.
*/
public function tags()
{
return $this->hasMany('App\Tags');
}
}
Tags Model
(assuming tags can be used for multiple products)
//namespace and use statements
class Tags extends Model
{
/**
* The tags that belong to the product.
*/
public function products()
{
return $this->belongsToMany('App\Products');
}
}
Then you can query in you controller for the products with their tags (https://laravel.com/docs/5.1/eloquent-relationships#querying-relations)
$products = App\Products::with('tags')->get();
Then you can simply access them in your view with your current code but using
#foreach($products as $product)
<tr>
<td></td>
<td>{{ $product->name }}</td>
#foreach($product->tags as $tag)
<td>{{ $tag->name }}</td>
#endforeach
<td>{{ $product->created_at }}</td>
<td>
// some other code and buttons
</td>
</tr>
#endforeach

Categories