Laravel giving error in foreach loop in spatie-permission - php

I was applying Spatie Laravel-permissions and coding to add permissions to roles.
and faced a error.
public function store(Request $request) {
//Validate name and permissions field
$this->validate($request, [
'name'=>'required|unique:'.config('permission.table_names.roles').'|max:10',
]
);
$name = $request['name'];
$role = new Role();
$role->name = $name;
$permissions = $request['permissions'];
$role->save();
//Looping thru selected permissions
if(count($permissions>0)){
foreach ($permissions as $permission) {
$p = Permission::where('id', '=', $permission)->firstOrFail();
//Fetch the newly created role and assign permission
$role = Role::where('name', '=', $name)->first();
$role->givePermissionTo($p);
}
}
return redirect()->route('roles.index')
->with('flash_message',
'Role'. $role->name.' added!');
}
So if someone please help me solve this problem.

In your submit form use this
<input type="checkbox" name="permissions[]" value="{{ $r->id }}"> {{$r->display_name}} </li>
In controller catch these permissions like this
$permissions = $request->permissions;

Related

laravel not updating data, just refresh

hello i have two tables users and profiles and i have a form to update the user profile, whene i try to update, it's just refresh the page but nothing was updated, and there is no errors
this is my code :
ProfilesControllers:
public function update(Request $request)
{
$this->validate($request,[
'name'=>'required',
'email'=>'required|email',
'about'=>'required',
'facebook'=>'required|url',
'instagram'=>'required|url',
]);
$user = Auth::user();
if($request->hasFile('avatar')){
$avatar = $request->avatar;
$avatar_new_name = time() . $avatar->getClientOriginalName();
$avatar->move('uploads/avatars', $avatar_new_name);
$user->profile->avatar = 'uploads/avatars'.$avatar_new_name;
$user->profile->save();
}
$user->name = $request->name;
$user->email = $request->email;
$user->profile->facebook = $request->facebook;
$user->profile->instagram = $request->instagram;
$user->profile->about = $request->about;
if($request->has('password')){
$user->password=bcrypt($request->password);
$user->save();
}
$user->save();
$user->profile->save($user->profile);
return redirect()->back();
}
profile.blade.php :
<form action="{{ route('user.profile.update')}}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
/// here is my input fields
</form>
and i'm using Laravel : 6.20.5
could someone tell me where is the problem in my code? thanks
you could try this:
instead of $avatar = $request->avatar;
use
$avatar = $request->file('avatar');
and instead of $avatar->move('uploads/avatars', $avatar_new_name);
use
$request->file('avatar')->storeAs('uploads/avatars', $avatar_new_name);
and when using back() there's no need for redirect(). back() generates an HTTP redirect.
so
return back();

Can not retrieve the id of a foreign key [Laravel]

I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.
When the User completes the form, I put the User & demands information inside those 2 tables.
But I do not know how to have the User id to put it inside the demands table.
Here is the function inside my Controller:
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user ->numStudent= $request->NumStudent;
$user ->role_id = "3";
$user ->Lastname = $request->LastName;
$user ->FirstName= $request->FirstName;
$user ->numero_etudiant = "12345678";
$user ->email = $request->Email;
$user ->password = bcrypt('idk');
$user ->adress= $request->Adress;
$user ->phone = $request->Phone;
$user ->parcours = $request->Parcours;
$demand->status_id= "3";
//problem below
$demand->User_id= $User;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$user ->save();
$demand->save();
return redirect('/demands_list');
}
But it says "Can't use method return value in write context".
Cordially
You have to save first the instance of your user before using its properties. Your code should look like this.
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user->numStudent= $request->NumStudent;
$user->role_id = "3";
$user->Lastname = $request->LastName;
$user->FirstName= $request->FirstName;
$user->numero_etudiant = "12345678";
$user->email = $request->Email;
$user->password = bcrypt('idk');
$user->adress= $request->Adress;
$user->phone = $request->Phone;
$user->parcours = $request->Parcours;
$user->save();
$demand->status_id= "3";
//problem below
$demand->User_id= $user->id;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$demand->save();
return redirect('/demands_list');
}
Assuming by your tags that you are looking for an Eloquent (i.e. Laravel) way of doing this.
The short answer: use route model binding and keep your controller methods organized and single-focused.
As already answered, your User needs to be saved first. I would recommend you do this step in its own controller:
// UsersController.php
public function store(Request $request) {
$attributes = $request->validate([
// validation rules
]);
$user = User::create($attributes);
return redirect('/users/' . $user->id);
}
Now that you have a User created, you can then attach related models. Create a separate set of routes pointing to a separate controller for handling the relationship:
// routes/web.php
Route::get('/user/{user}/demands', 'UserDemandsController#index');
Route::post('/user/{user}/demands', 'UserDemandsController#store');
// ^^^^^^
// used with route model binding
Here's where route model binding comes into play, loading the model straight from the route parameters ({user}):
// UserDemandsController.php
public function store(Request $request, User $user) { // <-- ROUTE MODEL BINDING
$attributes = $request->validate([
// validation rules
]);
$user->demands()->create($attributes);
}
The result is very clean, simple code.

How to fix "Undefined variable: collaborators"?

I am developing collaborators adding methods to my project management application. this is my collaborators add form.
colllaborators/form.blade.php
<div class="col-md-4" style="border:1px solid #ccc;margin-left:15px;padding:10px;">
<h4 class="page-header">
Collaborators
</h4>
#if( $collaborators)
#foreach( $collaborators as $collaborator)
<div>
<div>
<span>
<img src="{{ $collaborator->user()->first()->getAvatarUrl() }}" />
</span>
</div>
<button class="btn btn-sm btn-danger delete" style="margin-top:5px;padding:4px;width:35px;"
data-action="/projects/{{ $project->id }}/collaborators/{{ $collaborator->collaborator_id }}"
routes
Route::post('projects/{projects}/collaborators', [
'uses' => 'Project\Collaborators\Controller#addCollaborator',
'as' => 'projects.collaborators.create',
'middleware' => ['auth']
]);
but when I click to collaborators adding buttons following error messages displayed.
Undefined variable: collaborators (View: C:\Users\Flex\Desktop\ddd\resources\views\collaborators\form.blade.php)
how can I fix this problem
edited
class ProjectCollaboratorsController extends Controller
{
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
return redirect()->back()->with('info', "{$collaborator_username} has been added to your project successfully");
}
private function getId($username)
{
$result = User::where('username', $username)->first();
return (is_null($result)) ? null : $result->id;
}
private function isCollaborator($projectId, $collaboratorId)
{
return Collaboration::where('project_id', $projectId)
->where('collaborator_id', $collaboratorId)
->first();
}
}
see My other part of the form
<form class="form-vertical" role="form" method="post" action="{{ route('projects.collaborators.create', $project->id) }}">
collaborator form route
Route::get('/collaborators', function(){
return view('collaborators.form');
})->name('collaborators.form');
In your form page, you are checking #if( $collaborators) which checks if the $collaborators variable is not empty and then runs the foreach below it.
After you submit your form, you add the collaborator and redirect back with no collaborators. The if condition then tries to check if the variable is empty. At this point the variable has not been defined and hence it throws that error. To fix this error, return redirect back with the collaborators like this:
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
//Get all collaborators
$collaborators = Collaboration::all(); //if this is how you get all collaborators
//Get the project too
$project = Project::findOrFail($id);
return redirect()->back()->with(['collaborators'=>$collaborators,'project'=>$project,'info'=> "{$collaborator_username} has been added to your project successfully"]);
}
EDIT:
Using the with method puts the data in the session, i would suggest that you manually redirect to the view and flash the message to that view.
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
//Get all collaborators
$collaborators = Collaboration::all(); //if this is how you get all collaborators
//Get the project too
$project = Project::findOrFail($id);
return redirect()->route('collaborators.form',['collaborators'=>$collaborators,'project'=>$project])->with('info',"{$collaborator_username} has been added to your project successfully");
}
Edit 2
I have changed all the return redirect()->back()'s
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
//Get the project too
$project = Project::findOrFail($id);
if( is_null($this->getId($collaborator_username)))
{
return redirect()->route('collaborators.form',['project'=>$project])->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->route('collaborators.form',['project'=>$project])->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
return redirect()->route('collaborators.form',['project'=>$project])->with('info',"{$collaborator_username} has been added to your project successfully");
}
And change your routes to
Route::get('/project/{project}/collaborators', function($id){
$collaborators = Collaboration::all();
$project = Project::findOrFail($id);
return view('collaborators.form',compact('collaborators','project'));
})->name('collaborators.form');

Example of CRUD with one to one relationship and image upload laravel

I am having trouble understanding and knowing how to create a one to one relationship with CRUD and file upload together, is it possible to give me a simple example on how to do it? Because when I tried to do it, for some reason my id and user_id doesn't match at all
Example, in user_info table (jack with id 1) has one userImage table(image uploaded with a user_id = 1).
This is the part that I am having trouble with in my controller:
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalExtension() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
//dd($UserImage);
return redirect('/home');
}
Sample of one to one relationship. I wish it can help you.
Example of table of Column of user table:
id
name
email
password
Example of table of Column of userimage table:
id
user_id
image_link
uploaded
User Model
public function userImage()
{
return $this->hasOne(App\UserImage::class);
}
UserImage Model
public function user()
{
return $this->hasOne(App\User::class);
}
CRUD in controller
public function store(Request $request)
{
$user = new App\User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->userImage->create([
'image_link' => $request->image,
'uploaded' => $request->date,
]);
return back();
}
public function update(Request $request, $id)
{
$user = App\User::find($id);
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->userImage->image_link = $request->image;
$user->userImage->uploaded = $request->date;
$user->userImage->save();
return back();
}
public function destroy($id)
{
$user = App\User::find($id)->delete();
return back();
}
Create a foreign key in your user_info table referencing userImage table.
Create unique constraint on the foreign key.

Laravel Redirect with

I got a problem when trying to redirect back with some results from my sql.
I got a function:
public function postSearch() {
$validator = Validator::make(Input::all(), array(
'search' => 'required'
)
);
if($validator->fails()) {
return Redirect::route('search')
->withErrors($validator)
->withInput();
} else {
$search = Input::get('search');
$user = User::where('username', 'like', '%' . $search . '%')->get();
if($user->count() >= 1) {
return Redirect::route('search')
->with('user', $user)
->withInput();
} else {
return Redirect::route('search')
->with('global', 'Could not find user.')
->withInput();
}
}
return Redirect::route('search')
->with('global', 'Something went wrong, try again later.');
}
but when select was successful in other my file with this code:
#foreach ($user as $users)
<p>
$users->username;
</p>
#endforeach
i got exception undefined user variable. But when i trying to search what doesnt exists in table, 'global' attribute showing my message.
Any ideas why is that not working?
Well, your error is just fine. The $user variable is not defined so you can't iterate over it.
There are 2 things you can do. In your view, you can check if the variable is set
#if (isset($user)
#foreach ($user as $users)
{{ $user->name }}
#endforeach
#endif
You can also set a default value on your code, but you will also need to always your variable to the view. For example:
$user = array();
return Redirect::route('search')
->with('user', $user)
->with('global', 'Could not find user.')
->withInput();
// you will need the $user on your last redirect too
This should fix your problem.

Categories