I want to add record using many to many relationship with Laravel 6.
I have a User which may have many roles like admin, blogger etc
Here is my function in User Model
public function roles()
{
return $this->belongsToMany(
'App\Role', 'user_roles', 'user_id', 'role_id', 'id'
);
}
Here is the Request data after form submission
array:5 [▼
"_token" => "asdnkasdjisajdmasnduajid"
"email" => "admin#admin.com"
"roles" => array:2 [▼
0 => "2"
1 => "3"
]
]
I have Tried this method to save my records
$users = [
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
'status' => 'active',
];
$user = User::create($users);
if ($user) {
$role = $user->roles()->attach($request->roles);
if (!$role) {
Session::flash('error', "Unable to create Role at this moment");
return redirect()->back();
}
Session::flash('status', 'User Created Successfully');
return redirect()->back();
}
I am getting
Unable to create Role at this moment
The attach() method of a many to many relationship doesn't return anything.
Your role variable will therefore always be empty, even when a role is successfully attached to a user.
Try this instead:
$users = [
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
'status' => 'active',
];
$user = User::create($users);
if (!$user instanceof User) {
Session::flash('error', "Unable to create User at this moment");
return redirect()->back();
}
$user->roles()->attach($request->roles);
if (!$user->roles) {
Session::flash('error', "Unable to create Role at this moment");
return redirect()->back();
}
Session::flash('status', 'User Created Successfully');
return redirect()->back();
Related
I am trying to delete an row from my database when user unlike a post but delete or destroy method not work !!!!
this my code:
public function like(Request $request)
{
$post = Post::find($request->post_id);
$like =Like::where('post_id', $request->post_id)->where('user_id', \auth()->id())->first();
DB::beginTransaction();
try {
if (!$like) {
Like::create([
"user_id" => \auth()->id(),
"post_id" => $request->post_id
]);
$post->update([
"likes_count" => $post->likes_count + 1
]);
DB::commit();
$notif = [
'text' => $request->user()->fullName() ." liked the post \"$post->title\".",
'type' => "post-like",
'data'=>["post_id"=>$post->id,"user_id"=>$request->user()->id]
];
Notification::send($post->user, new Notify($notif));
return response()->json([
'status' => 'success',
'message' => 'The post was liked!',
]);
} else {
Log::info($like);
Log::info($like->id);
$delete = Like::destroy($like->id);
Log::info("delete status");
Log::info($delete);
return response()->json([
'status' => 'success',
'message' => 'The post was unliked!',
]);
}
in laravel.log $delete value is 1 !
I am working on a Web Application using Laravel-5.8 as the backend. I am combining two classes: User and Role
ApiController.php
public function store(Request $request)
{
if(!Auth::user()->hasPermissionTo('Add Users'))
return response()->json([ "message" => 'User do not have permission'], 401);
$request->validate([
'name' => 'required|string|min:2',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed|min:6'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
'activation_token' => str_random(60),
'address' => $request->email,
'about' => $request->email,
]);
if($request->role)
foreach($request->role as $role)
$user->assignRole($role);
else {
return response()->json([
'error' => 'Role Not Found!'
], 401);
}
$user->school_id = Auth::user()->school_id;
if($request->address)
$user->address = $request->address;
if($request->about)
$user->about = $request->about;
$user->save();
$avatar = Avatar::create(strtoupper($user->name))->getImageObject()->encode('png');
Storage::put('avatars/'.$user->id.'/avatar.png', (string) $avatar);
$user->notify(new SignupActivate($user));
return response()->json([
'message' => 'Successfully Added New User!'
], 201);
}
From the code above, I don't want to display all the Roles. I want to use the foreach statement to only select and display these two Roles: Admin, Staff.
That is, where role_name = Admin, Staff.
foreach($request->role as $role)
$user->assignRole($role);
How do I achieve this?
I think you can go about that in this way.
You can use the Laravel filter method which is in the documentation here Laravel Collection filter Method
This method returns an array of items that have passed a given condition
You convert your roles request into a collection first
Then use a condition like
return if($role == 'Admin' || $role == 'Staff')
Where you see return $value > 2;
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]
I am working in laravel and i am using the spatie permission package
and I want to assign the different role for the user while registration I am using the radio button to get the role from a user such as editor ,writer,blogger
how to I assign the different role to user based on the user input
In Laravel Auth\RegisterController you can modify the create() function.
This is valid if you are using Spatie package.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->assignRole('customer'); //assign role to user
return $user;
}
Take that user input and use assignRole function as described in the package readme file
Something like
public function someController(Request $request)
{
....
$user->assignRole($request->input('role'));
...
}
assuming you have a form input (checkbox, radio, text) with name role
I have finally found a way to attach the different role to the user based on the user selection
In my register create function
$role = $data['userType'];
if ($role == 'User') {
$user->assignRole('User');
}elseif ($role =='Vendor') {
$user->assignRole('Vendor');
}
You can try the following code:
protected function create(array $data)
{
$user=User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'user_name' => $data['user_name'],
'role_name' => $data['role_name'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role_a = $data['role_name'];
if($role_a == 'student') {
$role = Roles::select('id')->where('admin_name', 'student')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'clg_admin'){
$role=Roles::select('id')->where('admin_name','clg_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'univ_admin'){
$role=Roles::select('id')->where('admin_name','univ_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'gov_admin'){
$role=Roles::select('id')->where('admin_name','gov_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'hod'){
$role=Roles::select('id')->where('admin_name','hod')->first();
$user->roles()->attach($role);
return $user;
}
}
what i need is to save some data besides creating the user, here is what I've been trying to do in my RegisterController.php :
protected function create(array $data)
{
if (isset($data['checkbox'])) {
$type = 1;
$available = 1;
} else {
$type = 0;
$available = 0;
}
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'type' => $type,
'available' => $available,
'company' => $data['company'],
'job' => $data['job'],
]);
$user->profilesInfoModel()->create([
'bio' => $data['bio'],
'site' => $data['site'],
'location' => $data['location'],
'education' => $data['education'],
]);
return $user->with('profilesInfoModel');
}
The User.php (Model) has a one to one relationship with profilesInfoModel (yes, i know i should change the name of the model to make it more comfortable).
But after trying to register a user... i get this error message: Method Illuminate\Database\Query\Builder::profilesInfoModel does not exist.
What is actually going on?
The relationship should be like this
User Model
public function profile()
{
return $this->hasOne(ProfileInfo::class, 'user_id');
}
Assuming you have ProfileInfo as Profile model and it has user_id as foreign key references users table id field
Now you can create profile from $user like this
$user->profile()->create([
'bio' => $data['bio'],
'site' => $data['site'],
'location' => $data['location'],
'education' => $data['education'],
]);
$user->load('profile'); //lazy eager load
return $user;
1.in App\Model\User
public function profilesInfoModel()
{
return $this->hasOne(App\Model\User);
}
2.to call
use App\Model\User
in RegisterController
I can not pass a foreign key value (which is user_id) to my newly created article.
Here is my code...
<?php
if (is_null($request->user_id)) {
$request->user_id = $user->user_id;
}
$request->validate(['title' => 'Required|string|min:3', 'body' => 'Required|string|min:5', 'user_id' => 'Required|exists:users,user_id']);
if ($article = Article::create($request->all())) {
event(new ArticleCreated($user));
return response()->json(['success' => true, 'reason' => 'Article Created successfully', $article]);
} else {
return 'Article could not be created';
}
Change this:
if($article = Article::create($request->all())) {
$article->user_id = $request->user_id;
$article->save();
event(new ArticleCreated($user));
return response()->json(['success' => true, 'reason' => 'Article Created successfully', $article]);
}
Try this,
public function store(Request $request)
{
$request->validate([
'title' => 'Required|string|min:3',
'body' => 'Required|string|min:5',
]);
$data = $request->all();
//you don't need to validate user_id is correct
//if you are using auth middleware in the route
$user = auth()->user()
$data['user_id] = $user->id
if ($article = Article::create($data)) {
event(new ArticleCreated($user));
return response()->json([
'success' => true,
'reason' => 'Article Created successfully',
$article
]);
} else {
return 'Article could not be created';
}
}
Hope this helps
Check your fillable array in Article model, there must be user_id, and check if the user id is passed in the $request->all().