the_lar
116
10
Laravel

Simple profile update persisting data

Posted 7 months ago by the_lar

Hi,

I'm really struggling grasping some basic concepts I think.

I am building a edit profile page, which is just a simple form that's populated with the users name, username, email. I want to validate the form data, if validation fails, go back to the form, display the error messages AND show the (incorrect) data in the form fields.

So if someone enters their email address as [email protected] I don't want to change that data, just show an error that it's not correct - then they can change it themselves.

Here is what I'm doing:

Routes:

//Profile
Route::get('/profile', '[email protected]')->name('profile')->middleware('verified');
Route::patch('/profile/update', '[email protected]')->name('profile-update');

ProfileController:

public function index()
    {
        $user = Auth::user();
        return view('profile', ['user' => $user]);
    }

    public function save(Request $request)
    {
        $user = Auth::user();
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255'],
            'username' => 'required|string|max:20|unique:users,username,'.$user->id,
            'email' => 'required|string|email|max:255|unique:users,email,'.$user->id,
            'password' => ['string', 'min:6', 'confirmed'],
        ]);

        if($validator->fails()){
            $messages = $validator->errors();
            return back()->withErrors($messages);
        }else{
            //Here is where I will save()
            return Redirect::action('[email protected]');
        }
    }

profile.blade.php extract:

<div class="col-md-6">
        <input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ $user->name }}" autofocus>

        @if ($errors->has('name'))
            <span class="invalid-feedback" role="alert">
    <strong>{{ $errors->first('name') }}</strong>
</span>

Obviously this isn't working how I want it to because I don't know how to pass the submitted data back when the validator fails. Should I use the with() method and extract it from the session in the blade template or is there another way?

Thanks

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.