How to display the name of the user instead of id. Laravel - laravel

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>

Related

Eloquent Queries and Blade Display

I have my users table and a profile table with a user_id
in my User Model I have
public function profiles()
{
return $this->belongsTo('App\Models\Profile');
}
and the reverse in my Profile Model.
For my function to display on profile page I have
$profiles = Profile::get()
->where('users', 'user_id', '=', 'profile.user_id');
return view('profile.profile')->with('profiles', $profile');
but I am not sure this is correct. Trying to stay eloquent. I also don't understand how to display the info from users and profile table on my profile page. Can someone please help?
It may be as easy as this:
$profiles = $user->profiles;
return view('profile')->with('profiles', $profiles);
As long as you follow normal laravel naming conventions, which means that the users table is called users and has a primary key of id which is autoincrement. The profiles table is called profiles and has a FK called user_id.
If not, you may need:
public function profiles()
{
return $this->hasMany("App\Profile", "user_id");
}

Laravel - Filter records by distinct relation

Right now I have the following models structure,
Country -> State -> City -> Student
And the Student model includes first_name and last_name.
So, I want countries to by filtered by giving student's first name. Like if I give John then I want list of countries which has students whose first name is John.
I was trying something like this,
I added a method called Students() in Country model and returning Student instances from that method. But now I stuck to find out how to filter countries.
Thanks in anticipation.
I came across a similar question recently and I came with the following solution myself. Probably, there are easier ways, but this will get you going for now, I guess.
First we query all the users with first_name == John, as you described, and we limit the query to output only the ID's.
$users = User::where('first_name', 'John')->get()->pluck('id');
We then cross-compare this with the result of Students() from the country model. As I don't know what you're querying for to get the country that you want, I'll just take the Netherlands as an example — that's where I'm from.
$users = Country::where('name', 'the Netherlands')->students()->whereIn('id', $users)->get();
For this to work, you must make sure that within the Students()-function in your model, the get() is left out.
Final 'result':
$users = User::where('first_name', 'John')->get()->pluck('id');
$users = Country::where('name', 'the Netherlands')->students()->whereIn('id', $users)->get();
in the Student Model create this:
public function city()
{
return $this->belongsTo(City::class,'city_id', 'id');
}
and in the City Model create this:
public function state()
{
return $this->belongsTo(State::class,'state_id', 'id');
}
Finally in the State Model:
public function country()
{
return $this->belongsTo(Country::class,'country_id', 'id');
}
For example if you made things like that in controller:
$students = Student::where('name', 'John')->get();
in the view:
#foreach($students as $student)
$student->city->state->country->country_name;
#endforeach
You can access like that.
If you have setup the model and relationship properly then you need to call them using in with function
$students = Student::where('name','John')->with('city.state.country')->get();
Loop through the $students
#foreach($students as $student)
{{ $student->city->state->country }}
#endif

Loop through relationships Laravel

Stackoverflow,
What I want to accomplish:
I want to Loop through the database to find all the (Heroes) with their related (Interview). I want to also pull each Interview with it's related (Story) and (Image). So far I can dd($heroes) and I can see the array correctly grab each hero with their interview and each interview has it's associated image and story. How do I loop through this correctly?
Error
Invalid argument supplied for foreach() (View: /Users/plastics1509moore/Desktop/elephant_gin/resources/views/administration/index.blade.php)
This is what I have done:
Controller:
$heroes = Hero::with('Interview', 'Interview.stories', 'Interview.images')->orderBy('position', 'asc')->get();
Model Relationships:
Hero:
public function Interview()
{
return $this->hasOne('App\Interview', 'heroInt_id');
}
Interview:
public function relationships()
{
return $this->belongsTo('App\Hero');
}
public function stories()
{
return $this->hasMany('App\InterviewStory');
}
public function images()
{
return $this->hasMany('App\InterviewImage');
}
InterviewImage:
public function relationships()
{
return $this->belongsTo('App\Interview');
}
InterviewStory
public function relationships()
{
return $this->belongsTo('App\Interview');
}
Html:
Loop:
#foreach($heroes as $hero)
#foreach($hero->Interview as $story)
<div>{{$story->id}}</div>
#endforeach
#endforeach
You can't loop on Interview because this a hasOne relationship. What you might want to do is
#foreach($heroes as $hero)
#foreach($hero->interview->stories as $story)
<div>{{$story->id}}</div>
#endforeach
#endforeach
I think your problem is because not following laravel "assumes". In documentation:
Additionally, Eloquent assumes that the foreign key should have a
value matching the id column of the parent. In other words, Eloquent
will look for the value of the user's id column in the user_id column
of the Phone record. If you would like the relationship to use a value
other than id, you may pass a third argument to the hasOne method
specifying your custom key:
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
What is the id of Hero? If it's different than id, then you have to add the local_key name.

Fluently updating an existing one to one relationship with Eloquent in Laravel 5

I have a one-to-one relationship between my User model and an additional UserInformation model in which I store additional needed information which would bloat the "normal" user table.
I set up my models like this:
# User.php
public function information()
{
return $this->hasOne(UserInformation::class);
}
# UserInformation.php
public function user()
{
$this->belongsTo(User::class);
}
I have a profile page where the User can update information from both tables.
The view has inputs like this:
<input name="email"> // is a field in the users-table
<input name="information[size]"> // is a field in the users-information table
I read in different locations that I should be able to save both my User model and its relation in with:
$user->fill($request->all())->save();
But this throws the following error:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
So my current solution looks like this:
auth()->user()
->fill($request->except('information'))
->save();
auth()->user()
->information
->fill($request->input('information'))
->save();
That works very good but doesn't look good in my opinion. So my question is: how can I clean that code up and save both in one go?
Have you tried including this
protected $guarded = array('information');
in your User.php model file
and then
auth()->user()
->fill($request->all())
->information->fill($request->input('information'))
->save();
I think your current solution looks fine, but if you want, you could always extract it out to your own custom method in your User model.
public function saveWithInformation($attributes)
{
$this->fill($attributes)->save();
$this->information->fill($attributes['information'])->save();
}
Then you can just call:
auth()->user()->saveWithInformation($request->all());
Since I was looking for a pretty flexible solution I came up with this function which I implemented into my User model (but it could also be included in a BaseModel)
public function fillWithRelation(array $request)
{
foreach ($request as $key => $value)
{
if (is_array($value) && method_exists($this, $key))
// check if the value is an array and if a method with the name of
// the key exists (which would be the relationship
{
$this->{$key}->fill($value);
unset($request[$key]);
}
}
return $this->fill($request);
}
This is definitely working if you include the information for a hasOne relationship like posted in my question.

How to get all related items like "with" in Laravel?

I'm sorry, I don't even know how to ask for what I need...
User:
id
MyItem:
id
item_id
user_id
Item:
id
How to get $user->items()?
I guess hasManyThrough() won't help here.
Thank your very much for help.
If you have defined your relationship and have items relation in your User model, you can get them using:
foreach ($user->items as $item) {
echo $item->id;
}
As it's many to many relationship, in class User you need to define your relationship this way:
public function items() {
return $this->belongsToMany('Item');
}
and in Item class this way:
public function users() {
return $this->belongsToMany('User');
}
And your pivot_table should have here name item_user. If it's not, pass your table name as 2nd argument to belongsToMany method
I don't know what you want exactly but
i think you need user relative more information
if you want user relative in formation
so please try this
you get all information about user
$users = User::all();

Resources