laravel prevent overload data on Auth::user() - laravel

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

Related

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

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

Laravel Eager-loading works only when calling attribute

I've defined my Slot model to load the relations from User model like so :
public function userAssignedFull(): HasOne {
return $this->hasOne(User::class,'id','user_assigned');
}
('slots' table contains 'user_assigned' field by which I connect to User records on 'id')
The following code finds Slot model but without 'userAssignedFull'. I get only the user ID in 'user_assigned'.
$slot = Slot::with('userAssignedFull')->find($slot_id);
But calling this afterward returns me the wanted relation:
$fullUserModel = $slot->userAssignedFull;
Can anyone tell me what am I doing wrong ?
Builder::with() returns the Builder instance.
So you have to call $slot->userAssignedFull; to get the collection of data.
From the docs:
When accessing Eloquent relationships as properties, the relationship
data is "lazy loaded". This means the relationship data is not
actually loaded until you first access the property.
And this $slot->userAssignedFull; is your "first access the property".
Try this
$slot = Slot::where('id', $slot_id)->with('userAssignedFull')->first();
$slot->userAssignedFull;

laravel user registration by roles in many to many relationship

In my application, I have two types of users "title" & "notary".
I have connected some users to these roles by many to many relationship [there is a table 'role_user', which is pivot table and contains 'user_id' from users table and 'roles_id' from roles table].
I have made seeds to give the users, specific roles. till this point my application is fine.
Now, I want to set a users role, when he registers [the idea is to select a radio button before registration].
When someone registers, he will be given selected role. How to do this in many to many relationship?
When user selects radio button then you will get that value and call a relationship on user to assign role.
$role = $request->role //get this value from radio
Since this is registration method so you will first create user and call a relationship to attach role.
$user = User::create($request->only('required fields ...'));
Now attach role to created user.
$user->roles()->attach($role); //this line is actual answer to your question
This will fill your pivot table with user role
Make sure you have defined roles() method in User.php model
public function register (Request $request){
$role = $request->role; //this is not necessary to save role value in variable you can get it directly from request object
$user = User::create($request->only('required fields'));
$user->roles()->attach($role or $request->role); // you can get role value directly from $request object.
}

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();

Create multiple objects from api post in laravel

Im at a bit of a loss. I have an api that will create a user upon a request. This is done no problem.
I also want to create another controller action or add to my current action the ability to create an address for the same user.
Is there an easy way to do this? Or should I stick to the
$user = new User(Input::all());
$user->save();
$address = new Address(Input::all());
$address->save();
You should set up relationships between your User and Address model - http://laravel.com/docs/eloquent#relationships and use associate/sync() to connect the dots.
This is a relationship problem. An address to a user will most likely be One-to-One (i.e., each Userhas a unique Address). A User might have an Address, but an Address must have a User. So in essence, the Address belongs to User.
Create two tables users and addresss, and add user_id to the address table as a column.
Then you define your relationships:
// In your User.php model
public function address()
{
return $this->hasOne('Address');
}
// In your Address.php model
public function user()
{
return $this->belongsTo('User');
}
Note when you use the correct notation, you can just define the model name, and not specify the pivot column. That is why I have defined the class addresss with an extra 's' to make it plural. I personally don't care about the spelling and rather Laravel take care of everything. Otherwise read the documentation on how to define the pivot column
Then you can use associate easily:
$user = new User();
// Fill $user however you want
$address = new Address();
// Fill $address however you want
$user->associate($address);
$user->save();
I was able to figure it out!
I wound up utilizing the Ardent package to help me validate my models before they hit the save method.
if my models didnt validate i will return all the errors to the user.
If they did validate my models would be created.
As for the association I am using the has many relation ship on the User and belongs to on the Address.
I used the following to save the address to the user
$address = $user->address()->save($address);
however I could only preform this after the initial user object was saved.
Thanks for all the responses guys they lead me in the right direction!

Resources