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();
Related
Let's assume, There Is two Table 'empData' & 'district'. 'empData' table contain 'id', 'name', 'empDistrict' ('empDistrict' contain the corresponding id of district) . and 'District' table contain 'id', 'name' of all districts.
Now I want to fetch the student's details including the district name. (Note: In the empDatatable, I contain only district id) How can I achieve this?
My Implementation
My District Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\EmpData;
class District extends Model
{
protected $guarded = [];
public function empdistrict(){
return $this->belongsTo(EmpData::class, 'empDistrict', 'id');
}
}
My EmpData Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
$data= EmpData::all();
return view('frontend.allusermindata',compact(['data']));
}
My Blade file where I show the data
foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict()->name}}</p>
}
But I get this error
Trying to get property 'name' of non-object
foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict->name}}</p>
}
Calling the method returns a BelonsTo class instance. Use laravel magic method by calling it as an attribute.
Further on this question, you'll have performance issues down the line, better load the data in the same query.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
$data= EmpData::with('empdistrict')->get();
return view('frontend.allusermindata', compact(['data']));
}
I want to echo value of NSC from table Group Class but i get this error Trying to get property 'nsc' of non-object
Table Item Name
Table Group Class
Model Item Name
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ItemName extends Model
{
protected $table = 'tbl_item_name';
protected $fillable = [
'inc',
'item_name',
'short_name',
'definition_eng',
'definition_ind'
];
public function GroupClass()
{
return $this->belongsTo('App\GroupClass', 'nsc', 'inc');
}
}
Model Group Class
namespace App;
use Illuminate\Database\Eloquent\Model;
class GroupClass extends Model
{
protected $table = 'tbl_group_class';
protected $fillable = [
'inc',
'nsc',
'description',
'main_group'
];
public function ItemName()
{
return $this->belongsTo('App\ItemName', 'inc', 'nsc');
}
}
Blade
<td>{{ $ItemName->GroupClass->nsc }}</td>
Please help to solve this problem, thank you so much
You should try this::
Blade
<td> {{ isset($ItemName->GroupClass) ? $ItemName->GroupClass->nsc : '' }} </td>
Model Item Name
public function GroupClass()
{
return $this->belongsTo('App\GroupClass', 'inc', 'nsc');
}
Model Group Class
public function ItemName()
{
return $this->belongsTo('App\ItemName', 'nsc', 'inc');
}
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
I'm trying to echo out the name of the user in my article and I'm getting the ErrorException Trying to get property of non-object. Here is my code:
Model (I have a User model too):
1. News
class News extends Model
{
public function postedBy()
{
return $this->belongsTo('User');
}
protected $table = 'tcity_news';
protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
}
2. User
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
}
Controller:
public function showArticle($slug)
{
$article = News::where('slug', $slug)->firstOrFail();
return view('article', compact('article'));
}
Blade:
{{ $article->postedBy->name }}
When I try to remove name in the blade {{ $article->postedBy }} it echoes out the id, but when I try to add the ->name there it says Trying to get property of non-object but I have a field name in my table and User model. Am I missing something?
UPDATE: When I try what user dschu said which is {{ dd( $article->postedBy) }} , I get the id of the user.
The problem is that you seem to have the same name (postedBy) for your relationship and the field in you database.
You should have a field called user_id instead of postedBy (or userId to be consistent).
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.