I need help on how to get the property of relationship table using eloquent. I am building a list of users in HTML table and want to display info from three tables join together using eloquent relationship
Example:
I have 3 table users, users_profile, and branch. Each user can have one profile and one branch, and each branch can have multiple users.
users
---
id
username
email
users_profile
-----
id
user_id
branch_id
fullname
address
branch
-----
id
branch_name
User model
public function user_info()
{
return $this->hasOne('User_info','user_id','id');
}
User_info model
public function user() {
return $this->belongsTo('User');
}
public function branch() {
return $this->belongsTo('Branch');
}
Branch model
public function user_info()
{
return $this->hasMany('User_info','branch_id','id');
}
User controller
public function index()
{
$users = User::with('user_info')->get();
foreach($users as $value)
{
//show data from table users
echo $value->username;
echo $value->email;
//show data from table user_info
echo $value->user_info->fullname;
echo $value->user_info->address;
//how to display data from table branch?
//this code below will trigger property error
echo $value->user_info->branch->branch_name;
}
}
Question is how do I display data from table branch in the list as this code below will trigger Trying to get property of non-object error.
I suspect there is some mistake on how construct the eager loading but cannot find the proper way on how to do it.
echo $value->user_info->branch->branch_name;
Thanks in advance
I don't see any error here, you before displaying any property from relationship you should make sure it really exists. For example user might have not user_info and if he has, its user_info might not to have nay branch.
So correct code for display should look like this:
public function index()
{
$users = User::with('user_info')->get();
foreach($users as $value)
{
//show data from table users
echo $value->username;
echo $value->email;
//show data from table user_info
if ($value->user_info) {
echo $value->user_info->fullname;
echo $value->user_info->address;
//how to display data from table branch?
//this code below will trigger property error
if ($value->user_info->branch) {
echo $value->user_info->branch->branch_name;
}
}
}
}
Related
Hello as the title says I'm not sure why my code is not showing the "First Name" for a user but it shows the ID only I have tried to do a lot of different methods to solve this but I'm rather a beginner in laravel so I thought It would be best if I asked for help by now
To explain a little the field "recieverID" is a foreign key of the table Users that shows the ID of the users
So here is the model named "Remark"
class Remark extends Model
{
protected $guarded =[];
public function user(){
return $this->belongsTo(User::class);
}
}
This is the Remark Controller
public function index()
{
if(Auth::guard('admin')->check())
{
$users = User::all();
$remarks = Remark::latest()->get();
return view('admin.remark.index', compact('users'),compact('remarks'));
}
It has more code under it but I only need it for this part, I added the $users and compact users because I tried to add 2 foreach loops on the view to see how it looks but it didn't quite work as i thought it might
This is the view I want to show the Name instead of the ID
#foreach($remarks as $remark)
<tr>
<td>{{$remark->recieverID->user->first_name}}</td>
<td>{{$remark->title}}</td>
<td>{{$remark->subject}}</td>
<td>{{$remark->message}}</td>
<td>{{$remark->sender}}</td>
</tr>
#endforeach
Thank you for your time
First of all, you need to change your relationship as below. If you don't pass foreign key then it assumes that you have foreign key as(user_id) in the table. but you have recieverID in the table. So, you need to define it.
public function user(){
return $this->belongsTo(User::class,'recieverID','id');
}
Now you can add it blade file.
<td>{{$remark->user->first_name}}</td>
I have a table called users with a column username. Another table called students with a column code. I have made a hasMany relationship in User model like below and it's working fine.
public function students()
{
return $this->hasMany(Student::class,'code','username');
}
I have another table called institutes where a column is similar to students table named inst. I need to show data from institutes table while showing data of an user. How to make this relationship?
users table
username|mobile|address|password
students table
username|name|inst|roll|reg
institutes table
name|inst|address|phone
This is my home controller
public function index()
{
$admins = User::where('username','=',Auth::user()->username)->get();
return view('home', compact('admins'));
}
And this is my view
#foreach($admins as $key => $admin)
#foreach($admin->students as $student)
{{ $student->reg }}
#endforeach
#endforeach
Add migration to your Students table :
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('set null');
Update your model User on students method :
return $this->hasMany(Student::class);
Add "with method"
$admins = User::where('username','=',Auth::user()->username)->with('students')->get();
In my User model in Laravel 5.2 I have a relationship setup with their status to the company.
public function companyStatus()
{
return $this->hasOne('CompanyUser')->select('status');
}
The CompanyUser table has a company_id, user_id, and status field
Then in my controller I do the following:
$company = Company::find($company_id);
$users = CompanyUser::where('company_id', $company_id)->pluck('user_id')->toArray();
$user_data = User::with('companyStatus')->find($users);
but when I dump the user_data array it has all of the users related to the company, but just shows null for their status relationship
{
"id":2,
"name":"Moderator",
"email":"mod#company.com",
"created_at":"2016-09-08 15:26:20",
"updated_at":"2016-09-08 15:26:25",
"company_status":null
}
If I however return just the User collection to the view, and iterate over each user and run
$user->companyStatus->status
the value displays, but I am trying to include this within the collection for a JSON API to consume.
UPDATE
I tried adding the foreign key to the select call on my relationship method:
public function companyStatus()
{
return $this->hasOne('CompanyUser')->select('status', 'user_id');
}
and it now returns the following:
{
"id":2,
"name":"Moderator",
"email":"mod#company.com",
"created_at":"2016-09-08 15:26:20",
"updated_at":"2016-09-08 15:26:25",
"company_status": {"status":"1","user_id":"2"}
}
Not sure if this is the best/correct method or not though.
Okay I figured it out.
I tried adding the foreign key to the select call on my relationship method:
public function companyStatus()
{
return $this->hasOne('CompanyUser')->select('status', 'user_id');
}
Then that returns:
{
"id":2,
"name":"Moderator",
"email":"mod#company.com",
"created_at":"2016-09-08 15:26:20",
"updated_at":"2016-09-08 15:26:25",
"company_status": {"status":"1","user_id":"2"}
}
Without the foreign key Laravel obviously can't determine the related data on the other table.
I have a controller with a function:
public function show(Activity $linkActivity, $id)
{
$activity = $this->activityRepository->getById($id);
$project = $linkActivity::find($activity->project_id)->project;
$employee = $linkActivity::find($activity->employee_id)->employee;
//\Debugbar::info($manager);
return view('activity/show', compact('activity'))->with('project',$project)->with('employee',$employee);
}
and here is my model Activity.php:
public function employee()
{
return $this->belongsTo('App\Employee');
}
The problem is that it is not looking at the right table and it is calling the activity table instead of the employee table. In the debugbar, I see the request to the db done which is:
select * from `activity` where `activity`.`id` = '2' limit 1
And id is well the 2 from the employee I m asking it but it looks in the wrong table.
Why is that?
You are searching for a row in Activity with Employee ID? I'm not sure what exactly you want, but if you want an employee why not simply do this
$employee = $activity->employee;
I think that the error is in find($activity->project_id).
In fact in the find, I need to put the id of the record holding the foreign key and not the id of the foreign key itself.
I am making a social network using Codeigniter and I'm trying to make the users view show a button when you are already following a person how do I do that??
Model
<?php
class User_model extends CI_Model {
function get_All(){
$this->db->select('*');
$this->db->from('membership');
// $this->db->join('following', 'following.id = membership.id');
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach ($q->result() as $rows) {
$data[] = $rows;
}
return $data;
}
}
It's a little bit of work. Assuming that all users can be searched, you might have a list of all users, and of the 'friends' of all users. Then you run through the two comparing them. The following is an idea:
Database Members: All members |ID_User|...other user stuff...
Database Followers: Lists all friendship |ID_User|ID_Follower|
You need two queries for this: One for all, and one for Followers where ID_User=$UserID. As you run through all members as you suggest, then you can
function get_Followers(){
$friends= $this->db->query('SELECT * FROM Followers WHERE ID_User=$UserID');
$follow_array=$row->ID_Follower;
}
Now:
$follow_array //A list of all friends.
$q //Your original list of members
Then you can use:
if($q->num_rows() > 0) {
foreach ($q->result() as $rows) {
if(in_array($rows->ID_Follower, $Follower_array))
{
$data=true;
}
else
{
$data=false;
}
}
return $data;
}
Beware however, this may be a very server-heavy operation.
I'm going to assume you're talking about visiting a persons profile and if you are following that person you see a button. That only requires one query and logic in the view itself.
Going on this assumption you're already passing the person who's profile you're viewing to the view so all you need is a list of people the viewer is following to compare that id to.
I'm not really sure what your query in your code is doing since there's no description of your database so I'll give the code the way the tables should be laid out, which is a user table and a following table that is just a join table on the users. Assuming the following table has 3 columns id, userId, followingId where userId is you and followingId is the person you are following.
Controller
$data['following'] = $this->modelName->getFollowing($userId); //pass current userId
$this->load->view('viewName',$data);
Model:
public function getFollowing($userId)//$userId to be passed as the person viewing.
{
$this->db->where('userId',$userId);
$data = $this->db->get('following');
if($this->db->num_rows() > 0)
{
return $data;
} else {
$data=array();
$return $data;
}
Then in the view it's a simple if statement.
if(in_array($profileId,$following))
{
echo button;
}