I want the user to create a profile for himself, but I do not know exactly what to do. When I do this code, the profiles of all the users change and become one this is controller for user panel
public function UpdateUser(Request $request, User $user)
{
if (!is_null($request->user_image && $request->job)) {
$data = $request->validate([
'user_image' => ['required', 'mimes:jpg,png,jpeg', 'max:5120'],
'job' => ['required', 'min:3', 'max:14'],
]);
$file = $request->file('user_image');
$file_path = '/images/' . 'user' . '/';
$file->move(public_path($file_path), $file->getClientOriginalName());
$data['user_image'] = $file_path . $file->getClientOriginalName();
}
User::query()->update($data);
return redirect('/user-profile');
}
this is code for blade:
<form method="post" action="{{route('user.update')}}" enctype="multipart/form-data">
@method('PATCH')
@csrf
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">آپلود عکس</span>
</div>
<input type="file" name="user_image" class="form-control" placeholder="user_image" aria-label="user_image"
aria-describedby="basic-addon1" value="{{old('user_image')}}">
</div>
<div hljs-string">">
<label for="inputEmail3" hljs-number">2 control-label">تخصص</label>
<input type="text" hljs-string">" name="job" id="job" placeholder=" تخصص خود را وارد کنید"
value="{{old('job')}}">
</div>
<div hljs-string">">
<button type="submit" hljs-string">">
<div>ثبت</div>
</button>
</div>
</form>
CodePudding user response:
in this line your query on all users not specific user
User::query()->update($data);
try this
$user->update($data);
CodePudding user response:
User::query()->update(...)
is going to update every row in the table since you're not constraining it in any way.
Since this page is for the currently authenticated user, use the user()
method from the $request
. You could use the Auth
facade or the auth()
helper function instead.
$request->user()->update($data);
This isn't your only issue though. !is_null($request->user_image && $request->job)
will always be true
since $request->user_image && $request->job
will always produce a boolean
value which will never be considered null
so you might as well just remove the if
statement.
Also, (not that it really matters in this case since the if
statement would always run) if you have a variable defined in a if
statement, you should also define a default value i.e. for when the condition is false
.
public function UpdateUser(Request $request)
{
$data = $request->validate([
'user_image' => ['required', 'mimes:jpg,png,jpeg', 'max:5120'],
'job' => ['required', 'min:3', 'max:14'],
]);
$file = $request->file('user_image');
$file_path = '/images/' . 'user' . '/';
$file->move(public_path($file_path), $file->getClientOriginalName());
$data['user_image'] = $file_path . $file->getClientOriginalName();
$request->user()->update($data);
return redirect('/user-profile');
}