I'm trying to figure out how to create user roles using model relationships when a user gets created from admin in my app.
I have the following tables:
users
The users
table holds a list of users.
users_roles
The users_roles
table is a pivot table that links roles
to users
.
roles
The roles
table contains a list of roles.
I am trying to use a repository setup so that my controller has no mention of eloquent.
This is my controller:
class ContractorController extends Controller
{
private $user;
/**
* Create a new instance.
*
* @return Middleware
*/
public function __construct(UserRepoInterface $user, TimesheetRepoInterface $timesheet)
{
$this->middleware('actions');
$this->user = $user;
$this->timesheet = $timesheet;
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Response
*/
public function store(CreateUserRequest $request)
{
// create user
$user = $this->user->createUser($request->except('_token'));
// user was created above so we can use $user object
$this->user->createUserRole($user);
return Redirect::back()->withMessage('New user created.');
}
}
My repository:
/**
* Create new user role.
*
* @param $request
* @return mixed
*/
public function createUserRole($user)
{
return $this->user->roles()->attach($user);
}
My User model:
/**
* Get the roles associated with the user.
*
* @return Object
*/
public function roles()
{
return $this->belongsToMany('App\Models\User\UsersRoles', 'users_roles', 'role_id', 'user_id');
}
The above code results in a record getting created in the users_roles
table which is correct, however I do not know how to associate the correct role_id in the table.
Here is the data that gets inserted into users_roles
:
id user_id role_id
1 1 0
As you can see there is no role_id because i'm not sure how I can pass this in. I know that if I was phsically creating a new role in the roles
table, then I coud use this object. But the role already exists so I just need to associate this new user with a role that I specify.
Please can someone point me in te direction of how I can do this or how would I have to adjust my code?
Thanks in advance.
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1X6GBer
via IFTTT
Aucun commentaire:
Enregistrer un commentaire