Trying to get property of non-object Laravel hasMany Relation - laravel

I am pretty new to laravel and i am learning about relationships in eloquent. I have 3 models
Report
ReportModule
ReportSubModule
Relationships are such
SubModule hasMany Module
Report hasMany ReportModule
Report hasMany ReportSubModule
When i try to get the ReportSubModule from Report object in my view i have no error but when i try to get the ReportModule from Report object in my view i get error Trying to get property of non-object. If i print the ReportModule object i see json and i think i am getting the object but unable to get it's property
Here is my code
Report (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Report extends Model
{
public function report_module(){
//module_id is column in reports table that corresponds to
//id column in report_modules table
return $this->belongsTo(ReportModule::class,'module_id');
}
public function sub_module(){
//sub_module_id is column in reports table that corresponds to
//id column in report_modules table
return $this->belongsTo(ReportSubModule::class,'sub_module_id');
}
}
ReportModule (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class ReportModule extends Model
{
public function subModules(){
return $this->hasMany(ReportSubModule::class);
}
public function reports(){
return $this->hasMany(Report::class);
}
}
ReportSubModule (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class ReportSubModule extends Model
{
public function module(){
return $this->belongsTo(ReportModule::class);
}
public function reports(){
return $this->hasMany(Report::class);
}
}
view
<h4> {{$report ->report_name}} </h4>
<small>{{ $report->sub_module->sub_module_name }} </small><br/><br/>
<?php
$m = $report->report_module;
<!-- i get error on below line -->
echo $m->module_name;
?>
What am i doing wrong here.I should be able to get the ReportModule object property just like ReportSubModule but i'm not.Please guide me to resolve this problem.

I assume you have the relationship like this -
Report id(primary key) -> ReportModule report_id(foreign key)
ReportModule id(primary key) -> ReportSubModule report_module_id(foreign key)
You will have the relation ship in each Model like below -
1) Report Model -
public function reportModule(){
return $this->hasMany(ReportModule::class,'report_id'); //you can use has one as well if required
}
2) Report Model -
//relationship with report table
public function module(){
return $this->belongsTo(Report::class,'report_id');
}
//relationship with report sub module
public function reportSubModule(){
return $this->hasMany(ReportSubModule::class,'report_module_id); // you can use has one if required
}
and so you can create the relationships..
hope it will work for you

Related

Understanding Eloquent One-to-many Relationships

I'm trying to understand Eloquent relationships but it seems I'm missing something in understanding it. I have:
A Meeting produces many Documents.
A specific Document can be produced for one Meeting.
Thus a one to many relationship. I am trying to display the 'meeting_name' in the Document details table but get this error:
Trying to get property 'meeting_name' of non-object (View: C:\wamp64\www\yajra_contact_system\resources\views\documents\index.blade.php)
Here is my code.
Please please explain with code solution:
app\Document.php File:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Document extends Model
{
protected $fillable = [
'document_name',
'document_desc',
];
public function meeting(){
return $this->belongsTo(Meeting::class);
}
}
app\Meeting.php File:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Meeting extends Model
{
protected $fillable = [
'document_id',
'meeting_name',
'meeting_desc',
'room_no',
'no_of_invitees',
'comments'
];
public function documents(){
return $this->hasMany(Document::class);
}
}
app\Http\Controllers\DocumentsController.php File:
namespace App\Http\Controllers;
use App\Document;
use App\Meeting;
use Illuminate\Http\Request;
class DocumentsController extends Controller
{
public function index()
{
$documents = Document::all();
$meetings = Meeting::all();
return view('documents.index', compact('documents', 'meetings'));
}
}
resources\views\documents\index.blade.php File:
#foreach($documents as $document)
<tr>
<td>{{$document->id}}</td>
<td>{{$document->document_name}}</td>
<td>{{$document->document_desc}}</td>
<td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
</tr>
#endforeach
you have many problems in your code:
first: in order to use the relation ... you have to load it first ...
loading relation done by using with('relationName') method ...
in index:
$documents = Document::with('meeting')->all();
second:
<td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
the relation is named meeting without s .. not meetings ...
third:
it's pest practices to provide foreign key in relation:
in Meeting model
public function documents(){
return $this->hasMany(Document::class,'meeting_id');
}
in Document model:
public function meeting(){
return $this->belongsTo(Meeting::class,'meeting_id');
}
please make sure you have a column meeting_id in your documents table referenced as foreign key to id in meetings table
more details about loading relation in:
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
So you have your tables mixed up.
You have a single record per meeting yet you have a document_id in your meetings table which you would need to duplicate meeting record for each document.
Remove the document_id from your meetings table
Add a meeting_id to your documents table
remember to update your models fallible array else you wont get the new columns in the collection.
This should fix your problem as your relationships are correct.

Cannot establish relationship between two tables in Laravel

I want to create a relation between lising and attribute table in laravel for that i have used following code to establish relationship between them but the data in my view is not coming from both the tables. I'm getting following error:
Call to undefined relationship [adListAttributes] on model
[App\Models\AdListing].
Here listing can have as many attribute associated with and attributes
can be associated to many listings
ad_listings:
id
title
name
date
ad_list_attributes table :
id
listing_id
name
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListAttribute extends Model
{
protected $table = "ad_list_attributes";
public function Listings()
{
return $this->belongsToMany('AdListing', 'id', 'listing_id');
}
}
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListing extends Model
{
protected $table = "ad_listings";
public function Attributes()
{
return $this->belongsToMany('AdListAttribute', 'listing_id', 'id');
}
}
Problem is that you are using belongsToMany in both the models.This will cause a problem.
In AdListAttribute model,
public function listing_information()
{
return $this->belongsTo('App\AdListing', 'id', 'listing_id');
}
In AdListing model,
public function adlisting_attributes()
{
return $this->hasMany('App\AdListAttribute', 'listing_id', 'id');
}
You can get the results using,
$response = AdListing::get();
if($response->adlisting_attributes)
{
foreach($response->adlisting_attributes as $attribute)
{
echo $attribute->name;
}
}
Problem is that ur not calling the relationship with the right name i assume
$listings = AdListing::with('Attributes')->get();
Update :
Try this :
use App\Models\AdListAttribute;
//
return $this->belongsToMany(AdListAttribute::class, 'listing_id', 'id');
Same for other model, then try

In laravel how to get the join table data in same array without where condition

I have created both employes and employes_detail tabel with the data
i have created model for both of the table that is given below:
emloye model:
<?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
use App\Http\Model\EmployeDetail;
class Employe extends Model
{
public function employes_detail()
{
return $this->hasOne(EmployeDetail::class);
}
}
and eployedetail model:
<?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
class EmployeDetail extends Model
{
public function employe()
{
public function employe()
{
return $this->belongsTo(Employe::class);
}
}
}
and in controller i used like :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Model\Employe;
use App\Http\Model\EmployeDetail;
class EmployeController extends Controller
{
public function index(Request $request)
{
$Employe=Employe::all();
$convert=$Employe->toArray();
echo "<pre>";print_r($convert);exit;
//return view('employe.employe');
}
}
it showing only employe table data how can i show the data for the
employes_detail as well as .still i am not able to understand it on
laravel documentation can anyone please help me related this.
how can i get the all data from employes and employes_details table for all the records
but when i used this code in controller:
public function index(Request $request)
{
$Employe=Employe::where('id',1)->first();
//$convert=$Employe->toArray();
echo "<pre>";print_r($Employe->employes_detail);exit;
//return view('employe.employe');
}
its shows me the employe_detail table data
but i want both of the table data in a same array and i dont want to use where condition here.
the function employes_detail and employe in your models only declares the relationships between the models but if you want to load the relationship, you can try this :
Employe::with('employes_detail')->get();
or
$employees = Employe::all(); $employees->load('employes_detail');
Then you can access for each employees the relation attribute like that :
foreach($employees as $employe) {
$employe->employes_detail->id;
}
Hopes it helps you.

Need to know how to define two fields refering to same parent table in model in Laravel

In banner table I have another field image_id which also refers to media gallery , I need to know how would I define this Banner Model , as I already have defined video_id belongsTo mediagallery. I need help on this
//********** Banner model ***************************
namespace App;
use Illuminate\Database\Eloquent\Model;
class Banner extends Model
{
//
protected $table='banners';
public function mediagallery()
{
return $this->belongsTo('App\Mediagallery', 'video_id','id'); // 2nd foreign key field name , 3td is parent table primary key field name
}
}
//*********** Mediagallery model *********************
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mediagallery extends Model
{
//
protected $table='mediagalleries';
public function banner()
{
return $this->hasOne('App\Banner', 'video_id', 'id'); // 2nd foreign key o the child table , 3td is parent or local table
}
}
Create 2 relationships. One relationship for videos and another for images.
public function videoGallery()
{
return $this->belongsTo('App\Mediagallery', 'video_id','id');
}
public function imageGallery()
{
return $this->belongsTo('App\Mediagallery', 'image_id','id');
}
I don't know the specifics of the app, hopefully this helps.

How can i display a table with two foreign keys in laravel

I have 3 tables
Users
-------------
user_id (PK)
user_name
Items_distributed
-------------
user_id (FK)
item_id(FK)
Item List
-----------------
item_id(PK)
item_name
Now i need to print Items_distributed table by taking both the user_id and item_id and dispaly their item_name and user_name
i dont know how to display both things at a time
if i display either item_name or user_name its working
but when i try to print both it is not working .
Can any one solve my problem .
This is how i print the values
in controller i use like this
$itemdata=item::orderBy('user_id','desc')->paginate(10);
and in view
i use
#foreach($itemdata as $value)
<tr>
<td>{{$value->items->item_name}}</td>
<td>{{$value->users->user_name}}</td>
<td>{!!Html::link("editItem/",'Edit',array('class'=>'btn-sm btn-warning margin-left-btn'))!!}
{!!Html::link("deleteItem/".$value->item_id,'Delete',array('class'=>'btn-sm btn-warning margin-left-btn'))!!}</td>
</tr>
#endforeach
You should use Laravel Eloquent Relationship. When you create model file for DB Table, You just put relation with other model.
If Relation has set, than Laravel it self fetch data from Related table.
In your case, Three models are created.
1) User Model.
2) Item Model.
3) ItemDestributed Model.
UserModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Other code goes here
**/
public function itemDestribution()
{
return $this->hasMany('App\ItemDistribution','foreign_key');
}
}
ItemModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Items extends Model
{
/**
* Other code goes here
**/
public function itemDestribution()
{
return $this->hasMany('App\ItemDistribution','foreign_key');
}
}
ItemDestributionModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ItemDestribution extends Model
{
/**
* Other code goes here
**/
public function user()
{
return $this->belongsTo('App\User','foreign_key_of_user');
}
public function item()
{
return $this->belongsTo('App\Item','foreign_key_of_item');
}
}
You can find more about Eloquent Relation from Here.

Resources