laravel user registration by roles in many to many relationship - laravel

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.
}

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

How do I get a assign a record value to a variable in Laravel 5.3?

I need to display all the vehicle records belonging to properties of the currenty logged on user.
Before I pass the data to the view I need to filter out all the properties except those owned by the current user id.
I have a relationship in the Vehicle model that performs the foreign key constraint.
public function propiedad(){
return $this->belongsTo('App\Property', 'propiedad_id','id' );
}
My Controller is using this filter before passing the data to the view. I assume I have to acquire the property ids that belong to the user before I filter the vehicles that belong to those properties. This is where I am having trouble.
$user_properties = array(?????);
$Vehiculo = Vehiculo::where('propiedad_id', $user_properties);
If your properties table has a user_id column then on your user model define a vehicles hasManyThrough relationship like
public function vehicles()
{
return $this->hasManyThrough(Vehicle::class, Property::class);
}
Then in your controller you can do:
$users = User::with('vehicles')->get();
Or for a single user
$vehicles= User::find($id)->vehicles;

Laravel user management

In Laravel we can manage Users and Permissions easly but i've a problem with my application.
In my application a User is attached to One or Many department.
But a User can have different Role/Permission between departments. That is the problem. In the department One he can have a Admin Role and in the department Two he can only have a User Role. When the User switch between department i would like that his Role can be update.
How i can manage this in Laravel and Eloquent ?
Thank you for your help.
Jeffrey
Without seeing any of your code, I am forced to be fairly generic here. But here is the basic concept.
Architecture
Assuming you have tables like departments, users, roles, and permissions already, all you would need next is define a joining table. Something like this:
department_role_user
department_id // for this department
role_id // this role is assigned to
user_id // this user
Authorization
Define something like a hasPermissionTo() method on your User model.
Definition
class User
{
public function hasPermissionTo($action, $department)
{
// first get permission
$permission = Permission::where('action', $action)->first();
// get all roles which have this permission
$roles = $permission->roles;
return DB::table('department_role_user')
->where('user_id', $this->id) // current user
->where('department_id', $department->id) // the dept
->whereIn('role_id', $roles->pluck('id')) // any of the roles
->exists();
}
}
Usage
And use it like so.
if ($user->hasPermissionTo('do-something', $someDept)) {
// allow action
} else {
// no way
}
This should also work nicely with Laravel's Gates and Policies. Just use your new hasPermissionTo() method inside your gate/policy definitions.

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!

Laravel - Authorize user to update resource only with foreign key items that belong to same organization as user

I want to authorize a resource in my Laravel application, so that users can only change a foreign key id only to a value of an item, that belongs to the same organization as the user.
As an example:
A user belongs to an organization => user.organization_id
A organization has many item objects => item.organization_id
Now the user wants to update a resource that has some columns and four item columns item1,item2,item3,item4.
The user should only be allowed to set one of these 4 items with an id of an item that belongs to his organization.
I created a Controller and Policy for this case which contains the function
// Controller function
public function update(Request $request, ItemToUpdate $item)
{
//
}
// Policy function
public function update(User $user, ItemToUpdate $item)
{
//return true;
}
Now my question is: What is the most performant way to check if the user is allowed to update the resource with the ids, that are sent in the request.
Of course I could make a DB request for every item and check if item.organization_id === user.organization_id, but is this really the most performant and efficient way?
Thanks
In my opinion the best way is to create a custom Request and inside authorize method do your checks

Resources