Laravel: showing selected value in edit form - php

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.

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>

In your edit form you had a particular user information by it ID in one array after that you get the user into a edit page right, using that array you can check with option box like below example
<select type="text" name="location" value="{{ $user->prefName }}">
#foreach(config('pref') as $key => $score)
<option <?php echo($get_array_by_user_id->table's_exist_location_value == $key) ? 'selected' : ''; ?> value="{{ $key }}">{{ $score }}</option>
#endforeach
</select>
I think it is working exactly to you : - )
Thank You,

Related

Check checked checkbox in Laravel

I have this code:
$arrayWithSelectedValues = [[user_id] => 3,[language_id] => 2], [user_id] => 3,[language_id] => 12]]
And I have checkbox :
#foreach($languages as $language)
<fieldset>
<input type="checkbox"
class="icheckbox_square-red"
id="input-15" name="languages[]"
value="{{ $language->id }}">
<label for="input-15">{{ $language->name }}</label>
</fieldset>
#endforeach
How can I mark checkboxes as marked - those that have language_id from the array = $ language-> id?
Use the php function in_array() to check if the $language_id exists in the array of $languages
#foreach($languages as $language)
<fieldset>
<input type="checkbox"
class="icheckbox_square-red"
id="input-15" name="languages[]"
value="{{ $language->id }}"
#if(in_array($language_id, $languages))
checked
#endif
>
<label for="input-15">{{ $language->name }}</label>
</fieldset>
#endforeach
If $language->id value you are looking for, and you create an array of checked language ids from $arrayWithSelectedValues you can do:
<input
type="checkbox"
#if(in_array($language->id, $languages))
checked
#endif
>
You can collected the language IDs like so:
$languages = [];
foreach ($arrayWithSelectedValues as $selectedValues) {
$languages[] = $selectedValues['language_id'];
}

Update url parameters on form submit based on selections

I want to update the url with the selected options in the form and send it to session but i keep receiving : (Undefined variable: country).
How can fix this please ? and i am very beginner so excuse my dumb mistakes .
My route :
Route::post('/{country}/{region}/{city}', [
'as' => 'locationFinder',
'uses' => 'User\UserLocationsController#store']);
My controller :
class UserLocationsController extends Controller
{
public function store(Request $request, Country $country, Region $region, City $city)
{
session()->put($country->name, $region->name, $city->name);
return redirect()->route('welcome.index', [$country, $region,
$city]);
}
}
My view :
<form action="{{ route('locationFinder',[$country, $region, $city]) }}" method="POST">
<div class="form-group">
<select class="form-control" name="country_id" id="country_id">
<option value="0" disable="true" selected="true"> Select Country </option>
#foreach ($countries as $key => $value)
<option value="{{$value->id}}">{{ $value->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<select class="form-control" name="region_id" id="region_id">
<option value="0" disable="true" selected="true"> Select Region </option>
</select>
</div>
<div class="form-group">
<select class="form-control" name="districts" id="districts">
<option value="0" disable="true" selected="true"> Select City </option>
</select>
</div>
<div class="form-group">
<button class="btn btn-primary">submit</button>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
My CountryController :
class CountryController extends Controller
{
public function countries(){
$countries = Country::all();
return view('welcome', compact('countries'));
}
public function regions(){
$countries_id = Input::get('country_id');
$regencies = Region::where('country_id', '=', $countries_id)->get();
return response()->json($regencies);
}
public function cities(){
$regions_id = Input::get('region_id');
$districts = City::where('region_id', '=', $regions_id)->get();
return response()->json($districts);
}
}
in the controller you pass "$country"... but in your view you are using "$countries" in the foreach
controller:
..
return redirect()->route('welcome.index', [$country, $region,
$city]);
..
view:
#foreach ($countries as $key => $value)
<option value="{{$value->id}}">{{ $value->name }}</option>
#endforeach

Adding data with multiple tables in one form many to many relationship in laravel 5.4

I am trying to insert with two tables with many to many relationship: Assignments and Collectors. I also make a intermediate or pivot table between them named assignment_collector.
create.blade.php in assignment folder
<form method="POST" action="{{ route('assignments.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="area_id">Area: </label>
<select class="form-control" name="area_id">
#foreach ($areas as $area)
<option value= "{{ $area->id }}">
{{ $area->campus }} {{ $area->building }} {{ $area->floor }}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="mts_id">MTS: </label>
<select class="form-control" name="mts_id">
#foreach ($mts as $mt)
<option value= "{{ $mt->id }}">
{{ $mt->location }}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<input type="hidden" class="form-control" id="status" name= "status" value="Active">
</div>
<div class="form-group">
<label for="collector_id">Collector: </label>
<select class="form-control" name="collector_id">
#foreach ($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<option value= "{{ $collector->id }}">
{{ $collector->firstname }} {{ $collector->lastname }}
</option>
#endforeach
#endforeach
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
AssignmentsController
public function store(Request $request)
{
$this->validate($request, [
'area_id' => 'required',
'mts_id' => 'required',
'status' => 'required',
'collector_id' => 'required'
]);
$assignment = new Assignment();
$assignment->area_id = $request->area_id;
$assignment->mts_id = $request->mts_id;
$assignment->status = $request->status;
$assignment->save();
$assignment_collector = new AssignmentCollector();
$assignment_collector->collector_id = $request->collector_id;
$assignment_collector->assignment_id = $assignment->id;
$assignment_collector->save();
return redirect('/assignments');
}
Assignment Model
public function collectors()
{
return $this->belongsToMany(Collector::class);
}
Collector Model
public function assignments()
{
return $this->belongsToMany(Assignment::class);
}
I got an error on this: App\AssignmentCollector since there is no AssignmentCollector and as I read the tutorials, you don't need to make a model for the pivot table. I reading the other articles but I get even more confused. Please help me because I'm still new in Laravel and I have get confused. Thanks!
You don't need a Model for your assignment collector table. What you want to do is create the Assignment then assign
$assignment->collectors()->create([
// all the collector data
]);

Select Selected value of a dropdown in laravel 5.4

I have a dropdown called designation, where a user will select one of it, and after submitting it, if there is some error then I want to select the selected designation.
I am using this in laravel 5.4.
Controller
$info = DB::table("designation")
->where('status','=',1)
->pluck("name","id");
return view('regUser.add',['check' => 'userList','designation' => $info]);
View Files
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
#foreach ($designation as $key => $value)
<option value="{{ $key }}" />{{ $value }}</option>
#endforeach
</select>
#if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
#endif
</div>
Now if the validator found some error then I want to select the previously selected one.
How can i achive this in laravel 5.4.
After submiting the form it comes to addUserInformation function, where I validate the user information which have this piece of code
public function addUserInformation(Request $request){
$this->validate($request, [
'name' => 'required|string|min:5',
'email' => 'required|string|email|unique:users,email',
'designation' => 'required|exists:designation,id',
'password' => 'required|min:6',
'confirm_password' => 'required|same:password',
'userimage' => 'required|image',
]);
$selectedID = $request->input('designation');
}
Larvel passes the inputs back on validation errors. You can use the old helper function to get the previous values of form. A simple comparison should do the trick.
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
#foreach ($designation as $key => $value)
<option value="{{ $key }}" {{ old('designation') == $key ? 'selected' : ''}}>{{ $value }}</option>
#endforeach
</select>
#if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
#endif
</div>
You have to maintain the state of old input by using return redirect() like:
return redirect('form')->withInput();
Retrieving Old Data
To retrieve flashed input from the previous request, use the old method on the Request instance.
$oldDesignation = Request::old('designation');
and check it like:
#foreach ($designation as $key => $value)
$selected = '';
#if( $value == $oldDesignation )
$selected = 'selected="selected"';
#endif
<option value="{{ $key }}" {{ $selected }} />{{ $value }}</option>
#endforeach
Reference

Highlight multiple select options after validations fails - Laravel 5.2

I'm learning Laravel 5.2 for first time, and I need to repopulate a form when the validation fails.
I was able to do so with single inputs as 'name' or 'description', but I couln't find out how to do it with the 'category' which is a multiple select.
View:
<form action="{{ url('addproduct') }}" method="POST">
{!! csrf_field() !!}
<div class="form-group">
<label for="#productName">Name:</label>
<input id="productName" class="form-control" name="name" type="text" placeholder="Product name" value="{{ old('name') }}">
</div>
<div class="form-group">
<label for="#productDescription">Description:</label>
<textarea id="productDescription" class="form-control" name="description" rows="3" placeholder="Product description" value="{{ old('description') }}"></textarea>
</div>
#if ($categories)
<div class="form-group">
<label for="#productCategory">Category:</label>
<select id="productCategory" class="form-control" name="category[]" multiple>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
#endif
<div class="form-group">
<label for="#productQuantity">Quantity:</label>
<input id="productQuantity" class="form-control" name="quantity" type="number" min="0" value="0">
</div>
<button class="form-control btn btn-success" type="submit">Add Product</button>
</form>
Controller:
public function add(Request $request) {
$data = array();
$data['msgAdded'] = false;
$data['categories'] = Category::select('name', 'id')->get();
if ($request->isMethod('post')) {
$this->validate($request, [
'name' => 'required|max:50',
'description' => 'required|max:200',
'category' => 'required',
'quantity' => 'required|min:0',
]);
$product = new Product;
$product->name = $request->name;
$product->description = $request->description;
$product->quantity = $request->quantity;
$product->save();
foreach ($request->category as $cat) {
$category = Category::find($cat);
$category->products()->attach($product->id);
}
$data['msgAdded'] = true;
}
$data['view'] = 'addproduct';
return view('products/add', $data);
}
I would like to know if it can be achieve with blade, or the best way to achieve that.
Thank you!
Option 1
You would have to write the select part of your form like this:
<div class="form-group">
<label for="#productCategory">Category:</label>
<select id="productCategory" class="form-control" name="category[]" multiple>
#foreach ($categories as $category)
<option value="{{ $category->id }}"{{ !empty(old('category')) && in_array($category->id, old('category')) ? ' selected="selected"' : '' }}>{{ $category->name }}</option>
#endforeach
</select>
</div>
Option 2
And arguably the more elegant solution is to install the html package from the laravel collective
composer require laravelcollective/html
follow the installation instructions on the laravel collective Forms & HTML documentation.
then just enter this where your select would be:
{!! Form::select('category[]', $categories, old('category'),['class' => 'form-control', 'multiple' => 'multiple'] ) !!}

Categories