Laravel Query Builder vs Laravel Eloquent ORM in many to many relation - laravel

Hi i want to get same result in join query builder as we get in many to many eloquent orm..
$users = DB::table('users')->join('role_user','users.id','=','role_user.user_id')
->join('roles','roles.id','=','role_user.role_id')
->get();
if I use this then I got separate array for same user with role.. for example XYZ user has 3 role then it give me 3 array of same user.
but I want to get it like this user has 3 roles like eloquent

you can use laravel relationship in view file for that you need to define relationship in user model
public function userRoles(){
$this->hasMany(UserRole::class);
}
in controller you need to use With that eager load userRole
To get user roles in view file
$user->userRole
// this will return array of user role related to that user

Related

laravel prevent overload data on Auth::user()

My model User have some relation: profile, activites, etc...
on my controller i have this:
$user = Auth::user();
$user->load(['profile', 'activities']);
excpected result on my blade is that my variable $user is with my relationships and the Auth::user() data remain the users table data only;
i have a layout layout.blade.php and a view index.blade.php that extends my layout;
in my index i want to use the relation data and in my layout i want only the users data; but i always have the relation loaded from controller
If you load any relationship, laravel will add that relationship in your user object automatically.
If you don't want this and want the user only, you can duplicate the object first to another variable before loading any relation.
Second option, you can get the user again
If you want to have the same object but without the relationship you have multiple choices:
$user->unsetRelation('profile');//unset specific relationship on the $user Object
$user->unsetRelations();//unset all relationships on the $user Object
$userWithoutRelationships = $user->withoutRelations();//clone the current Object but without relationships

Laravel Relationships, don't know how to display

I have two models. Business and City.
Business:
id
title
-some columns--
city_id
City:
id
name
How to display the city name, when I get business data to view
I was able to display cities using the laravel voyager lessons
When I want to get it like $business->city_id
If you are using models, you can create a relationship by adding hasOne or hasMany to your model codes.
When you call it from your controller, you can call the relationship you wrote in your model with the 'with' query.
Model
public function city()
{
return $this->hasOne(City::class,'id','cityid');
}
Controller
$business=Business::with('city')->first();
$cityname=$business->city->name;
If you don't use model, you can connect with 'join'
You have 2 options. First, you can get city details on the controller:
Business::with('city')...;
On the blade
$business->city->name;
Other option fetching it on the blade directly. I don't recommend this because of extra database queries.
$business->city()->name;

How to make left join in many to many relationship laravel

I am new in laravel. I have 3 tables
users
ingredients
user_ingredients(pivot table)
Now i have established many-to-many relationship but I have a special requirement that I want to get matching records(which is done) with all the ingredients in ingredients table. I can do it using query_builder or raw but I want to do it in eloquent.
I have searched about 4 hours to find any solution in eloquent but did not found.
Here is my code
User Model
public function ingredients()
{
return $this->belongsToMany('App\Ingredient', 'user_ingredients');
}
Ingredient Model
public function user()
{
return $this->belongsToMany('App\User', 'user_ingredients');
}
Controller Code
$ingredients = $user->ingredients()->get();
Query Builder query
select ingredients.*,user_ingredients.liked from ingredients LEFT JOIN user_ingredients on ingredients.id = user_ingredients.ingredient_id and user_ingredients.user_id=129
I have checked has(),with() but nothing according to my requirement.
Please help me. Thanks
If I understand your question correctly, you are just trying to access all the ingredients on the user model? In that case, you should be able to just do $user->ingredients
You can access the relationship as a property on the user object. It's some behind the scenes Laravel magic that handles this.

Get formatted attributes from a related table for eloquent model

I have 3 tables
1. User table[id, name, email]
2. user_roles[user_id, role_id]
3. roles[ id, permission{post:{edit:true,delete:false}} ]
user hasone user_roles
roles belongs to user_roles
userRole.role is eager loaded in user model
Is it possible to get the permission by calling some custom function in user model.
instead of user->userRole->role everytime.
like call like $user->permissions() will return json from roles tables
You can create a method in your User model like this-
public function permissions()
{
return $this->userRole->role;
}
Laravel allows you to call your relation like that. Here $this represents your User model where you created this method. So calling a relation on $this would work without any problem.
Then you can call this with your user collection like this-
$user->permissions();
If you want to use this with logged in user then you can call it like this-
auth()->user()->permissions();

Eloquent relationship with 3 tables

I'm new to Stack Overflow and Laravel.
I try to develop a variable profilesystem in Laravel and I got 3 tables ('User', 'User_Fields', 'Fields').
The structure of the Fields table is following:
The structure of the user_fields table is following:
The User table is the standard table which came with Laravel 5
Now I want to get all fields from user_fields depending on which user is selected or logged in. If the user_field doesn't exists, the model should return null or create a new record for the user_field.
I tried a lot of "solutions" which came with eloquent like (hasManyThrough, belongsToMany) but I don't get the result I wanted.
Is there any solution with relationship methods?
Thanks for your help, and sorry for my bad english :/
You should be using the belongsToMany()->withPivot() to retrieve the intermediate table columns. Your user_fields is your pivot table so on your user model you should have:
class User extends Model
{
public function fields()
{
return $this->belongsToMany(Field::class, 'user_fields')->withPivot('value');
}
}
Then you can access your values for a user by:
$user = User::find($id);
foreach($user->fields as $field) {
$field->pivot->value;
}

Resources