How can I display value of pivot table ? Laravel 5.3 - laravel

I have 3 model : store model, product model, order model
store model is like this :
class Store extends Model
{
protected $fillable = ['name', 'user', 'address', 'phones', 'email', 'photo'];
...
}
product model is like this :
class Product extends Model
{
protected $fillable = ['store_id','category_id','name', 'photo','description'];
...
}
order model is liket this :
class Order extends Model
{
...
public function products()
{
return $this->belongsToMany(Product::class, 'orders_products')
->withPivot('sub_total','quantity','price','information')->withTimestamps();
}
public function store()
{
return $this->belongsTo(Store::class);
}
}
I have 4 table : stores table, orders table, products table, orders_products table
orders_producs table is pivot table
In view blade laravel I call this :
{{ $order->store->name }}
It works. It success display store name
My problem is when I want to display product name
In view blade laravel I try :
{{ $order->products->name }}
There exist error :
Undefined property: Illuminate\Database\Eloquent\Collection::$id
(View:...
It seems the wrong way of calling
How can I solve it?

Since it's belongsToMany(), you can display data like this:
#foreach ($order->products as $product)
{{ $product->name }}
{{ $product->pivot->price }}
#endforeach

Related

Trying to get property 'name' of non-object?

Hi Guys i am new to laravel and i am trying to retrieve category names for each formation and i am getting this error
Trying to get property 'name' of non-object (0)
The "name" i am trying to retrieve is the name of category that my formation belongs to.
This is My Category Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
function formations()
{
return $this->hasMany('App\Formation');
}
protected $fillable =['name','description'];
}
And This is My Formation Model
class Formation extends Model
{
function category()
{
return $this->belongsTo('App\Category',"category_id");
}
protected $fillable =['name','price','durations','category_id'];
}
And here is my view page where i am trying to retrieve the category name
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td>{{$formation->category->name}}</td>
td>{{$formation->durations}}</td>
#endforeach
This is My Controller
public function index()
{
//$formations = Formation::all();
$formations = Formation::with('category')->paginate('4');
$categories = Category::all();
return view('formation.index',compact('categories','formations'));
}
Any Suggestion about where i might be wrong ? And thanks in Advance !
This error usually comes when you have removed one or more row from database, but trying to access that row with an id. Make sure that you have all the category in the category table with the id which is mentioned in the formation table category_id field.
In your view
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td> {{ $formation->categories()->pluck('name')->implode(' ') }}</td>
<td>{{$formation->durations}}</td>
#endforeach
Try changing the relationship
class Formation extends Model
{
function category()
{
return $this->belongsTo('App\Category',"id","category_id"); //if your categories id is id
}
protected $fillable =['name','price','durations','category_id'];
}
In your view
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td>{{$formation->category->name}}</td>
<td>{{$formation->durations}}</td>
#endforeach
The Problem was that i have deleted a row from my category table in database that's why the name wasn't recognized.

Many to many tables how to view on Laravel

I have this three tables :
Table 1. users
'first_name', 'last_name', 'bio', 'image', 'email', 'password', 'user_group','remember_token',
Table 2. professions
'id', 'title',
Table 3 user_profesions
'id','user_id', 'profession_id'
I combined the users table with user_professions table like this:
public function index(){
$mentors = User::where('user_group', 2)->get();
$all_professions = Profession::get();
foreach($mentors as $mentor) {
$mentor->professions = UserProfession::where('user_id', $mentor->id)->get();
}
dd($mentors);
return view('mentors.list-of-mentors')->with(['mentors'=>$mentors, 'all_professions' => $all_professions]);
}
So it gives me this when I die dump
I am also passing the all professions from professions table.
In view I am doing it like this
#foreach($mentors as $mentor)
{{$mentor->first_name}}
#foreach($all_professions as $profession)
{{$profession}}
#endforeach
#endforeach
I am stuck here I don't know how to make the professions for that particular user to appear.. Can someone please help me..?
You can use eloquent ManyToMany relationship to fetch data between User and Profession model. And for that you have to define it like this
User Model
public function professions()
{
return $this->belongsToMany('App\Profession','user_profesions');
}
Profession Model
public function users()
{
return $this->belongsToMany('App\User','user_profesions');
}
Now fetch it like this in controller
$mentors = User::with('professions')->where('user_group', 2)->get();
return view('mentors.list-of-mentors')->with('mentors',$mentors);
In view you can use it like this
#foreach($mentors as $mentor)
{{$mentor->first_name}}
#foreach($mentor->professions as $profession)
{{$profession}}
#endforeach
#endforeach
Check here https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
Add relationship mathods to your models.
UserModel
public function professions()
{
return $this->hasMany(Profession::class);
}
ProfessionModel:
public function users()
{
return $this->hasMany(User::class);
}
And now you can do this:
$user = User::where('user_group', 2)->with('professions')->get();
dd($user->professions);

Getting data from a relationship but getting collection error

I have two tables user and user details. Which has one to one relationship.
And I want to display all the data in the users table (name, email, password) and the address and the age only in the user_details table. How can I do it when I have Eloquent relationship made such as
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table ='users';
protected $fillable = ['user_name', 'email', 'password'];
public function userdetails(){
return $this->hasOne('App\UserDetail','user_id');
}
}
UserDetail.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserDetail extends Model
{
protected $table ='user_details';
protected $fillable = ['user_id', 'full name', 'address', 'age'];
public function users(){
return $this->belongsTo('App\User');
}
}
Maybe I can pass to my view and loop them using foreach?
{{$user->user_details->address}}
In controller function you can fetch user like this
$users = User::with('userdetails')->get();
pass this users variable in view and in your view and in your view try this
#foreach($users as $user)
{{ $user->user_name }}
{{ $user->email }}
{{ $user->userdetails->full_name }}
{{ $user->userdetails->address }}
{{ $user->userdetails->age }}
#endforeach
You can use eager loading to load the data:
$users = User::with('userdetails')->get();
And then access it:
{{ empty($user->userdetails) ? 'No address attached to this user' : $user->userdetails->address }}
Thank you everyone, I just queried to the related table. So I query using userdetails
controller:
user_detail = UserDetail::with('user')->get();

Laravel Category Model Relationships

I have the following table structure in my database.
Table Name: tiles
Columns: id, tile_name, tile_thumb, tile_snippet
Table Name: tags
Columns: id, tag_title
Table Name: tile_tags
Columns: id, tile_id, tag_id
Models:
Tile, Tag, TileTag
In my main model class for entries I am specifying the following relationship to a model called TileTag which is a pivot table.
<?php namespace Tiles;
use Illuminate\Database\Eloquent\Model;
class Tile extends Model {
protected $table = 'tiles';
public function tags() {
return $this->belongsTo('Tiles\TileTag');
}
}
During my foreach loop it returns the tile_name and any other columns from my table, except the ones joined by the relatipnship.
#foreach($tiles as $tile)
<a href="tile/{{$tile->tile_name}}">
<li class="col-md-4 mix" data-category="{{ $tile->tags->tag_title }}">
{!! HTML::image($tile->tile_thumb, null, array('class' => 'img-responsive')) !!}
</li>
</a>
#endforeach
How can I get my categories/tags linked to my primary entries when they are sorted during each loop?
I try returning the data during the loop by {{ $tile->tags->tag_title }} but it returns an empty string.
Controller Method:
class TileController extends Controller {
/**
* Display a listing of tiles from the database.
*
* #return Response
*/
public function index() {
// Get tile data from the model
$tiles = \Tiles\Tile::all();
return view('pages.index', compact('tiles'));
}
Returned Array:
I think that you don't have to create a model for Tile_Tag. Laravel can handle ManyToMany relationships out of the box (I suppose that this is the type of the relationship because you use pivot table). Your models should be
class Tile extends Model {
protected $table = 'tiles';
public function tags() {
return $this->belongsToMany('Tiles\Tag');
}
}
and
class Tag extends Model {
protected $table = 'tags';
public function tiles() {
return $this->belongsToMany('Tiles\Tile');
}
}
Laravel will know that you have a pivot table named "tag_tile" with columns "tag_id" and "tile_id". Check the relevant documentation here
Then you can iterate through tags collection for each tile like this
#foreach ($tiles as $tile)
{!!$tile->tile_name!!}
#foreach ($tile->tag as $tag)
{!!$tag->tag_title!!}
#endforeach
#endforeach
Hope it helps.

hasManyThrough() or similar database model

I have a database setup similar to this:
items
id - integer
user_id - int
users
id - integer
name - string
contacts
id - integer
user_id - integer
name - string
Using Eloquent ORM how would I query for that returns the associated user, and their contacts? I'm currently using
Items::with('user')->get();
Models and relationship:
// User model
class User extends Eloquent {
public function items()
{
return $this->hasMany('Item');
}
public function contacts()
{
return $this->hasMany('Contact');
}
}
// Contact model
class Contact extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
// Item model
class Item extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
Usage:
$items = Item::with('user.contacts')->get(); // Result will be a collection object
$firstItem = $items->first(); // get the first item from collection
// Or this to get first one
$firstItem = $items->get(0); // get the first item from collection
$firstItem->user; // Get related User Model
$firstItem->user->contacts; // get collection of Contact models
If you pass the $items to your view then you may use a loop, for example:
$items = Item::with('user.contacts')->get();
return View::make('viewname')->with('items', $items);
In your view:
#foreach($items as $item)
{{ $item->property_name }}
{{ $item->user->property_name }}
#foreach($item->user->contacts as $contact)
{{ $contact->propertyname }}
#endforeach
#endforeach
It's called loading nested relations - last example on http://laravel.com/docs/eloquent#eager-loading
$items = Items::with('user.contacts')->get();
// then for example:
$item = $items->first();
$item->user; // user Model
$item->user->contacts; // Collection of Contact models
A note: there is no relation to access such relation directly. hasManyThrough won't work in this setup.

Resources