Showing data through foreign keys - laravel

I am trying to get some data through relationships and foreign keys but have gotten myself in a tangle.
I have a Batsmen who user can comment on,the comments can also be edited by the users, the comments have their own page aswell with the option to delete or edit the comment. This is where my problem comes, i am trying to show the nationality of the batsmen but can only retrieve the ID of his nationallity and not the name of the country.
Here are my tables
Batsmen: ID, Name, bio, Nationality_ID,
Nationality: ID, country_name,
User ID, name ,
Comment: ID, comment, Batsmen_ID, User_ID
My Relationships
Comment:
public function batsmen(){
return $this->belongsTo('App\Batsmen');
}
public function author()
{
return $this->belongsTo('App\User','user_id');
}
Controller:
public function show($id)
{
$comment = Comment::find($id);
return view('comments.show')->with('comment', $comment);
}
View :
<h4>{{$comment->batsmen->Nationality_id}}</h4>
So how would i get the country name to display instead of the nationality_ID?

Make another relationship method on your Batsman model class as -
public function nationality(){
return $this->belongsTo('App\Nationality','Nationality_id');
}
And then in your view-
<h4>{{$comment->batsmen->nationality->country_name}}</h4>

try this
public function show($id)
{
$comment = Comment::with('batsmen')->find($id);
return view('comments.show')->with('comment', $comment);
}

You need to add the relationship between bastman and nationality
class Comment extends Model
{
public function nationality(){
return $this->belongsTo('App\Nationality',Nationality_id,id);
}
}
Then you can easily get his country
<h4>{{$comment->batsmen->Nationality->country_name}}</h4>

Related

How to retrieve details of second level tables in laravel relationships

I have 3 tables
bank(id, title),
employee(id, name, bank_id),
payroll(id, employee_id, salary).
Now I want to retrieve bank title of employee_id in payroll table.
I have set model relationships
class Bank extends Model
{
public function employees()
{
return $this->hasMany('App\Employee');
}
}
class Employee extends Model
{
public function bank()
{
return $this->belongsTo('App\Bank');
}
public function payrolls()
{
return $this->hasMany('App\Payroll');
}
}
class Payroll extends Model
{
public function employee()
{
return $this->belongsTo('App\Employee');
}
}
I have tried to retrieve using $payroll->employee->bank->title. But it did not help me
Sorry it was my mistake. some employee ids are not referencing bank. That was why I got error.
I resolved the issue by using isset method to verify reference value set or not.
Thanks.
try to change your code a little bit and try again:
public function bank()
{
return $this->hasOne('App\Bank');
}
Read Laravel Official Documentation
/** We can define the inverse of a hasOne relationship using the belongsTo method: **/

Laravel Relationship not working on server

My project is working fine on local host, but on the server, getting error only on lesson page.
Subject Model is
class Subjects extends Model
{
public function category()
{
return $this->belongsTo('Lea\Category');
}
public function lesson()
{
return $this->hasMany('Lea\Lessons');
}
public function chapter()
{
return $this->hasMany('Lea\Chapters');
}
public function users()
{
return $this->belongsToMany('Lea\User', 'subject_user', 'subject_id', 'user_id');
}
}
And Lesson Model is
class Lessons extends Model
{
public function chapter()
{
return $this->belongsTo('Lea\Chapters');
}
public function subject()
{
return $this->belongsTo('Lea\Subjects', 'subject_id');
}
public function category()
{
return $this->belongsTo('Lea\Category');
}
}
My controller lessons has method index like below.
public function index()
{
$lessons = lessons::orderBy('id', 'asc')->paginate(5);
return view('admin.lessons.index')->withLessons($lessons);
}
The way i am calling subject name is show below. first subject is relationship subject and 2nd subject is the field name where subject name saved in db. using foreach to get data like:
#foreach ($lessons as $lesson)
{{$lesson->subject->subject}}
#endforeach
subjects table schema is
id
subject
admin_id
users_id
category_id
created_at
updated_at
lessons table schema is
id
title
slug
category_id
subject_id
chapter_id
users_id
content
image
That's more like it ;)
Just edit how you are passing the object to the following:
...
return view('admin.lessons.index')->with(compact('lessons'));
What this is doing:
compact() essentially takes the object/variable by it's name ($lessons) and passes it to the view with the same name.
An alternative way is to write it as:
...
return view('admin.lessons.index')->with('lessons', $lessons);
Cheers!
The reason you're getting the error in your server but not your local machine is that your server database is empty (or at least has fewer records).
{{$lesson->subject->subject}}
The lesson has no subject, so it's null. And your tryting to get a proprty subject of a null.
If you're using Laravel 5.5, you can wrap the subject in optional() method.
{{optional($lesson->subject)->subject}}
< Laravel 5.5
{{$lesson->subject ? $lesson->subject->subject : ''}}

Laravel - Get articles from feeds for one user

I have three tables:
articles :
id
feed_id
title
feeds :
id
user_id
name
users :
id
name
I want get all articles from feeds for one user, I search the Eloquent Relationships...
Could you help me please?
First, define the relation on User model. Best option for you situation is to use a Has Many Through relation:
public function articles()
{
return $this->hasManyThrough(
'App\Article',
'App\Feed',
'user_id', // Foreign key on feeds table...
'feed_id', // Foreign key on articles table...
'id', // Local key on users table...
'id' // Local key on feeds table...
);
}
Then make a user object and get his articles:
$user = /App/User::with('articles')->find($id);
foreach($user->articles as $article) {
// do whatever you need
}
laravel documentation is always a good start for researching, read about hasManyThrough
https://laravel.com/docs/5.5/eloquent-relationships#has-many-through
don't mind if it is in 5.5, there are no significant differences between them
in model
in Articles.php
public function Feed()
{
return $this->belongsTo('App\Feed');
}
in Feed.php
public function User()
{
return $this->belongsTo('App\User');
}
public function Articles()
{
return $this->hasMany('App\Articles');
}
in User.php
public function Feed()
{
return $this->hasMany('App\Feed');
}
in controller
// To get all articles of user with id = $id
$reports2 = Articles::with(array('Feed'=>function($query)use($id){
$query->with('User');
$query->where('user_id',$id);
}))->orderBy('id', 'desc')
->get();

Laravel eloquent -getting user info based on id, for each comment in a query

I have an API endpoint where I am suppose to send all the relevant data for articles. I have tables users, comments, articles. Users table has fields id, first_name, last_name, table comments has fields id, article_id, user_id. Relationships are defined like this:
Article model:
public function comments()
{
return $this->hasMany('App\Comment');
}
User model:
public function comments()
{
return $this->hasMany('App\Comment');
}
Comment model:
public function user()
{
return $this->belongsTo('App\User');
}
Now in my function I am getting articles and then creating an array with info about comments. I should get user first_name, and last_name for each comment, but I am not sure how to do this and if it is possible to do it when getting a collection from eloquent query?
This is the function:
$result = Article::where('publish', 1)->orderBy('created_at', 'desc')->paginate(15);
foreach($result as $article){
$articles[$article->id] = $article;
$articles[$article->id]['comments'] = $article->comments()->get();
}
return $articles;
Now that you have defined the relationships use it like :
$article = Article::with('comments.user')->where('publish', '1')->orderBy('created_at', 'desc')->paginate(15);
now in your view do like this :
#foreach($article->comments as $comment)
{{$comment->body}} by {{$comment->user->name}}
#endforeach

laravel display only specific column from relation

I have read a few topics about this, but they managed to solve my problem partially ...
this is my controller
class DeskController extends BaseController{
public function getDeskUsers($deskId){
$user = DeskUserList::where(function($query) use ($deskId){
$query->where('deskId', $deskId);
})->with('userName')->get(array('deskId'));
if (!$user->isEmpty())
return $user;
return 'fail';
}
this is the model
class DeskUserList extends Eloquent {
protected $table = 'desk_user_lists';
public function userName(){
return $this->belongsTo('User', 'userId')->select(array('id','userName'));
}
}
the method getDeskUsers may returns ALL the DeskUserList table records, related with the User table record (on deskUserList.userId = User.id).
practically I want each record returned is composed of:
DeskUserList.deskId
User.userName
eg. [{"deskId":"1","user_name":antonio}]
What i get is
[{"deskId":"1","user_name":null}]
As you can see the user name is a null value...
BUT
if I edit my controller code:
->with('userName')->get(array('userId')); //using userId rather than deskId
then i get
[{"userId":"2","user_name":{"id":"2","userName":"antonio"}}]
By this way I still have two problem:
the userId field is twice repeated
I miss the deskId field (that I need...)
hope be clear, thanks for your time!
You need belongsToMany, no need for a model representing that pivot table.
I assume your models are Desk and User:
// Desk model
public function users()
{
return $this->belongsToMany('User', 'desk_user_list', 'deskId', 'userId');
}
// User model
public function desks()
{
return $this->belongsToMany('Desk', 'desk_user_list', 'userId', 'deskId');
}
Then:
$desks = Desk::with('users')->get(); // collection of desks with related users
foreach ($desks as $desk)
{
$desk->users; // collection of users for particular desk
}
// or for single desk with id 5
$desk = Desk::with('users')->find(5);
$desk->users; // collection of users
$desk->users->first(); // single User model

Resources