I added a drop down list in the user registration form in Laravel. Now I want to make a form to edit it but I’m stuck.
What I did is I made a drop down list which a new user can register where he/she lives. I used a list of cities(pref.php) in the configuration folder to make this drop down list. I want the user to be able to see the cities that they have registered default when opening the edit form and then change it or leave it alone but I couldn’t figure out how to do this.
Here are my codes.
editprofile.php
<form action="/profile" method="post" enctype="multipart/form-data"> {{ csrf_field() }} {{ method_field('patch') }} <p> <label><b>name</b><br> <input type="text" name="name" value='{{ $user->name }}'><br> </label> </p> <p> <label><b>location</b><br> <select type="text" name="location" value="{{ $user->prefName }}"> @foreach(config('pref') as $key => $score) <option value="{{ $key }}">{{ $score }}</option> @endforeach </select> </label> </p> <p> <label><b>mail adress</b><br> <input type="text" name="email" value='{{ $user->email }}'><br> </label> </p> <p> <label><b>profile image</b><br> <input type="file" name="profile_image"><br> </label> </p> <input type="hidden" name="id" value="{{ $user->id }}"> <input type='submit' value='edit' class="btn btn-primary mt-3"> </form>
ProfileController.php
public function edit() { $user = Auth::user(); return view('profile.editprofile', ['user' => $user]); } public function update(ProfileRequest $request, User $user) { $user = User::find($request->id); $user->name = $request->name; $user->email = $request->email; $user->location = $request->location; if ($request->hasFile('profile_image')) { Storage::delete('public/profile_image/' . $user->profile_image); $path = $request->file('profile_image')->store('public/profile_image'); $user->profile_image = basename($path); } $user->update(); return redirect('/profile'); }
pref.php
<?php return array( '0' => 'not selected', '1' => 'New York', '2' => 'Los Angeles', '3' => 'Dallas' );
I thought this page had a similar problem but it was a little different.
Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.
Advertisement
Answer
to make an option selected you have to put selected property in that option. putting value on select won’t work. you can do it like
<select type="text" name="location"> @foreach(config('pref') as $key => $score) <option value="{{ $key }}" {{ $user->location == $key ? 'selected' : '' }}>{{ $score }}</option> @endforeach </select>