Table column filled later on - php

I'm new on Laravel and as I'm playing around with it I encounter this issue.
I have a registration system which worked fine but now I wanted to add a new field in my table (description field for users).
However, this description field, I don't want to be filled when the user signs up, I want the user to fill this when he gets on his profile and updates a modal window.
The problem is, if I let that filed empty, I get an error when I sign up saying that the description filed can't be empty.
This is what I use in my UserController in order to update the description field but I'm not sure if is correct.
public function postDesc(Request $request){
$this->validate($request, [
'description' => 'required|min:20'
]);
$user = User::all();
$user->description = $request->input('description');
$user->save();
return redirect()->route('user.profile.edit');
}
This is how I opened the form:
{!! Form::open(['method' => 'PUT', 'action' => 'UserController#postDesc', 'class' => 'profile-form']) !!}

You use required validation rule, that's why you get the message. You should use different validation rules for register page and profile update form.
Good practice is to create two Request classes and use them for validation of two forms.

In this scenario, I will prefer to keep your description column nullalbe(). So it won't throw an error that description field is empty at the time of sign up.
And later you can update the description field.
public function postDesc(Request $request)
{
$this->validate($request, [
'description' => 'required|min:20'
]);
// Get the logged in user id using auth and then updating description filed
$user = User::where('user_id', Auth::id())
->update([
'description' => $request->description
]);
return redirect()->route('user.profile.edit');
}

Related

LARAVEL 9 - Get User ID for user management

I'm creating a users management with Laravel 9, I am an administrator and I would like to change users to admins whenever I like :)
For example this user ->
I wrote this code ->
public function UpdateToAdminAction(Request $request) {
$request->validate([
'type' => 'required|exists:users',
]);
DB::table('users')->update(
['type' => $request->type]
);
return redirect('/gestion-administrateurs');
}
But I cannot update THIS user's type, this code changes ALL users' types lol, it's not what I wanted. Do you know with this code, how can I change THIS user's type ?
Thanks, I hope you'll understand my request ^^
you are selecting all the users by this query DB::table('users'),
assuming you are receiving id in request
you must select one row by adding a where condition DB::table('users')->where('id',$request->id)->update(['type' => $request->type])
You need to pass user ID as route part, or as request param
For example, you may create following route for updating users:
// Dont forget to protect this route with middleware like "can:edit-users"!
Route::post('/user/{id}', 'UserController#update');
then, render in template button to made user admin:
<form method="post" action="/user/{{ $user->id }}">
#csrf
<input type="hidden" name="type" value="admin">
<button type="submit">Make admin</button>
</form>
And create update method:
public function update(Request $request)
{
$request->validate([
'type' => 'required|exists:users',
]);
DB::table('users')
->where('id', $request->id)
->update(
['type' => $request->type]
);
return redirect('/somewhere');
}

Laravel admin update users' info, duplicate email entry when updating his own admin account information

I am working on a laravel 8 application and using spatie/laravel-permission for roles and permissions. On the admin page, I'm displaying all users which the admin can do CRUD operations on. The users list also includes his own admin account.
The problem I'm having is when updating user details. The admin can successfully update user account information for other users with validation. However, if the admin tries to edit the information of his own admin account, the validation passes but I get an SQL error :
Integrity constraint violation: 1062 Duplicate entry 'admin#email.com'
for key 'users_email_unique'
See below my UserController update method for updating user information with validation:
public function update(Request $request, User $user)
{
$edit_user_rules = array(
// ... other validation rules ...
//'email' => "required|email|unique:users,email,{{$user->id}}", //. auth()->user()->id,
'email' => ['required', 'string', 'email', Rule::unique('users')->ignore($user->id)],
// ... other validation rules ...
);
$validator = Validator::make($request->all(), $edit_user_rules);
if ($validator->fails()) {
Session::flash('failed', 'Failed to save User details!');
return redirect(route('editUser', ['user' => $user->id]))->withErrors($validator)->withInput();
} else {
$validated = $validator->validated();
$updatedUser = User::find($user)->first();
// ... other user fields ...
$updatedUser->username = $validated['username'];
$updatedUser->email = $validated['email'];
// ... other user fields ...
if ($updatedUser->save()) {
return redirect(route('allUsers'));
} else {
return redirect(route('allUsers')); // with errors
}
}
}
I've tried to use different validation rules on the email field, for example,
"required|email|unique:users,email,{{$user->id}}"
"required|email|unique:users,email," . auth()->user()->id
but none worked. So I used a validation Rule to validate the unique email field. It works fine when I try to update other users' information but I get the SQL duplicate email error when updating the admin's own account.
Would appreciate any help I can get
The error is getting passed the validation rules, but it's failing when it saves the rule. This is because you're not getting the user properly. find() automatically gets the first record, so first() is unneeded, and is actually probably pulling the wrong account. When I try User::find(3)->first() locally, I'm getting user 1 instead of user 3. Remove first() from your call.
$updatedUser = User::find($user->id);
You didn't determined which column should be unique to ignore him self.
Change your email validation line to :
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user->id)],
Don't forget to put this like to top of your code use Illuminate\Validation\Rule; .

Adding value to a model from url params in laravel 5

Playing around with a referral system in laravel 5.4. I have been able to create a unique shareable link for each user.
When another user clicks on that, I want the portion of the url with the referral id of the link's original owner to be added to the referrer field of the user.
I tried this method and been getting this error, what better way is there to do this.
use Illuminate\Support\Facades\Input;
protected function create(array $data)
{
$ref = Input::get('ref');
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'referrer' => $ref
]);
return $user;
}
I am getting an error complaining that the referrer column cannot be null even though there is a ref on the link.
Sample link.
http://localhost:8000/register?ref=1b0a6294-043d-11e7-86bf-56847afe9799
User Model
protected $fillable = [
'name', 'email', 'password', 'level', 'btc_address', 'referrer'
];`
I think the problem might be your routes and url you use in form for registering user.
The url you showed is probably for displaying registration form, but when you send the form, you send it to http://localhost:8000/register url so you don't have ref defined in your url.
You should make sure, that you send form also to http://localhost:8000/register?ref=1b0a6294-043d-11e7-86bf-56847afe9799 url or put hidden field with ref value from get action.

Laravel 5 Validations

I want to validate my form fields using laravel 5.
Form field 1 -> User ID :
Form Field 2 -> Other Name :
Either of the form field is required.
i mean if user id is present other name should be blank and if other name is present user_id should be blank.
I am trying to use:
$validator = Validator::make(
[
'user_id ' => $user_id,
'user_name' => $user_name
], [
'user_id' => 'required_without:user_name',
'user_name' => 'required_without:user_id'
]);
if ($validator->fails()) {
return Utility::validation_err($validator);
}
While updating record even if user id is present it gives me error user id is required when other name is not present. also if i am filling out both it accepts both. It should accept one of both fields.
Any help will be appreciated.
You can use your own validation rule, for exmaple "only_one_id_name_required". It should be applied to both of fields. Next put extend Validator in App\Providers\AppServiceProvider
Validator::extendImplicit('only_one_id_name_required', function($attribute, $value, $parameters, $validator) {
return (request()->has('user_id') xor request()->has('user_name'));
});
Use extendImplicit() instead of extend() to cover empty fields request.

Laravel 5 - MethodNotAllowedHttpException when validation is false

Always when the validation fails, I get a MethodNotAllowedHttpException
routes.php
Route::post('download', 'UrlController#download');
Route::post('search', 'UrlController#search');
UrlController.php
public function download(DownloadRequest $request)
{
dd($request->all());
}
DownloadRequest.php
public function authorize()
{
return true;
}
public function rules()
{
return [
'format' => 'required|between:1,13'
];
}
name.blade.php
{!! Form::open(['url' => 'download']) !!}
{!! Form::select('format', [
'Please select format',
'FormatGrp1' => [1 => 'best', 'p1','p2', 'p3', 'p4'],
'FormatGrp2' => [6 => 'p5', 'p6']
]) !!}
When "Please select format" is chosen and the form is submitted, I always get this error because "Please select format" has value 0 and i specified values must be between 1 and 13. (Look at DownloadRequest.php)
Thanks for help!
The error didn't come from the validation.
It was because it called the URL to go back and display the errors. And this is the search method.
So cause of the logic in search method the exception has been thrown.
When you have this error, in your if ($validator->fails()) { } consider that you are going to open the view you are working on for the first time, and add ->withErrors($validator)
For example:
public function edit($id)
{
$exams = Exam::all();
return view('exams.index', compact("exams"));
}
...
public function update(Request $request,$id)
{
$validator = Validator::make($request->all(),[
'start' => 'required',
'end' => 'required|after:start'
]);
if ($validator->fails())
{
$exams = Exam::all();
return view('exams.index', compact("exams"))->withErrors($validator);
}
//Your update code if validator not fails
}
I didn't exactly understand what this user was trying to explain as the actual problem or solution - I came across this question as I had the same issue and thought I would describe what I had done in error and how I solved it...
For me, I was building a site where users would submit photos. When the user clicked on the "add photo" it took them to a page where they had to check a box to accept a legal disclaimer. This form with the checkbox was a POST request. After they accepted it they would get re-directed to the photo submission page... WHICH WAS ALSO A FORM WITH A POST REQUEST. This was my issue: back to back POST request pages. If the user entered invalid data on the submission form, or didn't enter data in a field at all Laravel tries to essentially hit the "back button" in your browser and keep the form filled with the data the user did enter. The problem is that the "back" button (or the way the user came to this page) was from a POST request, so it couldn't do it. It gave me the error described above. Once I switched the legal acceptance page to a GET request form and updated the route to match everything started working fine. It was a foolish error on my part, I just hope to mitigate this frustration for others as they are learning to develop in Laravel. Have a great day!

Categories