Eloquent Queries and Blade Display - laravel

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");
}

Related

Laravel - Find value is available in relationship

I need to check if the given user_id, location_id, and sub_location_id is belongs to the user on user_locations table. Based on this I need to give login permission to the user for the specific site.
Currently, I have the written code like below. But, don't know how to check the condition.
User::select('id')->with('user_locations:location')->where('user_id',$request->user_id)->get();
I need to put these conditions
is user found and active?
if user active. Then find the given sub location is tagged for the user.
if sub location found, then is the sub location active?
Below are the table structure.
Users Table
id (PK, AI),
user_id (UQ),
password,
status, ("Y"=> Active, "N"=> Inactive)
//other fields
public function user_locations(): HasMany
{
return $this->hasMany(user_locations::class);
}
User_Locations Table
id (PK, AI),
user_id (FK),
location_id (FK),
sub_location_id (FK),
status ("Y"=> Active, "N"=> Inactive)
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
I think you need to check relation existing
You can try this way for find user model
User::select('id')
->with('user_locations:location')
->where('user_id',$request->user_id)
->where('status','Y')
->whereHas('user_locations', function ($q) use ($request) {
$q->where('user_locations.user_id', $request->user_id);
$q->where('user_locations.status', 'Y');
})
->get();
If you want just to check user existing you can try this
User::where('user_id',$request->user_id)
->where('status','Y')
->whereHas('user_locations', function ($q) use ($request) {
$q->where('user_locations.user_id', $request->user_id);
$q->where('user_locations.status', 'Y');
})
->exists();
You can read mode about this here

How to display the name of the user instead of id. 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>

Invalid argument supplied for foreach() in laravel when use Eloquent: Relationships

I wanna get the class name of a user via the user ID. When I input the ID of a user so I will wanna get the class name. I have three tables such as users table, classes table, and class_users table. The class_users table is born from two users table and classes table.
A users table has an id, name, email, password.
A classes table has an id, class_code, class_name.
A class_users table has an id, class_id, user_id
And this problem relates to Eloquent Relationships.
Thank you for help.
My Route:
Route::get('/find_classes/{id}','StudentController#find_classes');
My Controller function:
public function find_classes($id)
{
$users = User::find($id);
foreach($users->classes as $class)
{
echo $class->name . '<br';
dd($class);
}
}
My User Model:
public function classes()
{
return $this->belongsTo('App\Classes','class_users','user_id','class_id');
}
Looks like you might have the wrong relationship set up on your User model. You have a one to many set up, but your DB is setup to handle a many to many. I suggest you change your User model relationship:
public function classes()
{
return $this->belongsToMany('App\Classes');
}
Note, you may need to name the FK on that relation, as I see you have class_id on the table, but your actual class is named 'Classes'. Check through your relationships to ensure this is explicit on the FK where it doesn't follow Laravel convention exactly.
With this relationship, your foreach loop should work. It would be a good idea for efficiency, as mare96 noted, to eager load the classes on the $users collection when you query:
$users = User::with('classes')->find($id);

Query all where list id has user id

I'm trying to get all the properties, in a watchlist(s) where the list has a user id.
The relationship is set up as follows.
Each watchlist is related to a user id. Each Property has a watchlist id.
I need all properties, in all the watchlists belonging to that user.
The watchlist gets the user_id automatically upon creation.
Here are my models
Watchlist
public function properties(){
return $this->hasMany('App\WatchedProperties');
}
public function user(){
return $this->belongsTo('App\User');
}
WatchedProperties
public function watchlist(){
return $this->belongsTo('App\Watchlist');
}
Query
Gets all books in every list disregarding user ids and list ids
$Watchlists = WatchedBooks::all();
Currently gets all books regardless of userid.
I need all books in all of the user's lists.
A user could have multiple lists
List A
List B
So something like
All books from all lists where the list id is related to user id.
This is what the Watchlist DB looks like
WatchlistDB
This is what the WatchedBooks DB looks like
Books in watchlist
Laravel has a beautiful solution for this: you can add a ->hasManyThrough relation to the user model. You can find more information about this type of relation in the Laravel documentation about Eloquent relationships.
The user model will look like this:
class User extends Model {
[...]
public function watchedBooks()
return $this->hasManyThrough('App\WatchedBook', 'App\Watchlist');
}
[...]
}
Then you can get all the WatchedBooks, associated with the user, using
$user->watchedBooks;
or
$user->watchedBooks()->yourBuilderQueryHere()->get();
whereHas allows you to query in relationships. More information on this can be found at https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence
$Watchlists = WatchedBooks::whereHas('watchlist', function($query) use ($user_id){
$query->where('user_id', $user_id)
})->get();
The script above gets all WatchedBooks that are associated with a Watchlist that is owned by a user ($user_id).

Laravel Counting and retrieving many to many relationships

I have a many to many Laravel Relationship Many Users have Many Roles
I know that I can do User::find(1)->roles()->get() to get all roles with an ID of 1 for a User but this requires me to know the ID of the role as oppossed to just its names
What sort of eloquent query could I put in my user Repository to do something like
public function getAllUsersWithRole($roleType){
//Query goes here
}
Where $roleType is the name of the Role. So I need to look up the ID of the role based on hte name and then return users that have that role ID in the pivot table
does this look like what you want:
public function getAllUsersWithRole($roleType){
$role= Role::where('name', $roleType)->first();
$users= $role->users;
return $users;
}
If you have correct relation definitions in your Eloquent models you should be able to get the users by the role name this way:
$roleType = 'YourRoleName';
$users = Role::whereType($roleType)->first()->users;
Grab the users, then get the roles for all the users.
public function getAllUsersWithRole($roleType){
$users = User::where('role_type', '=', $roleType)->get();
$roles = $users->roles()->get();
return $roles;
}

Resources