i have a multiple product when i get the default value of that product, but when i get that value in input field the default value doesn't show ?
<x-filament::page>
<form wire:submit.prevent="submit">
<div>
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
</div>
<select wire:model="user_type">
<option value="">Select User Type.....</option>
<option value="admin">Admin</option>
<option value="distributor">Distributor</option>
<option value="retailer">Retailer</option>
</select><br><br>
<input wire:model="name" type="text" placeholder="Name"><br><br>
<input wire:model="email" type="email" placeholder="Email Address"><br><br>
<input wire:model="password" type="password" placeholder="Password"><br><br>
<div align = "center">Products</div>
** #foreach($product as $val)
<br><br> {{ $val->name }} :
<input type="number" wire:model="default_price" value = "{{$val->default_price}}">
#endforeach<br><br>**
<button type="submit">
Submit
</button>
</form>
</x-filament::page>
Check these screencasts. They are very helpful! https://laravel-livewire.com/screencasts/data-binding
<input type="number" wire:model="default_price" value = "{{$val->default_price}}">
Livewire doesn't use value attribute!
If you want to update Product->default_price, you can use https://laravel-livewire.com/docs/2.x/properties#binding-models or if you want to only output the default_price, then remove wire:model.
Also #foreach($products as $val) $products should be plural,
and $val should be $product, because it is a product variable. Naming is important, if you don't want to confuse yourself and others constantly.
In my edit view I have code like this
<div class="form-group">
<label class="col-md-12">Last Name</label>
<div class="col-md-12">
<input type="text" placeholder="Enter Last Name" name="lastName" class="form-control form-control-line" value="{{$profile->personal_detail['last_name']}}" required>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Department</label>
<div class="col-md-12">
<select class="custom-select form-control col-md-11" id="department" name="department">{{ $profile->personal_profile['department'] }}
#foreach($listDepartment as $departmentList){
<option value='{{$departmentList->nameOfDepartment}}'>{{$departmentList->nameOfDepartment}}</option>
}
#endforeach
</select>
</div>
</div>
In edit view my last name field it gives me last name from database, in department it display me drop down of department but I want that inserted name of department in that field.
how can i get it??
I have other drop down like this
<div class="row">
<label class="col-md-6"><b> Mode </b></label>
<div class="col-md-6">
<select class="custom-select form-control col-md-12" name="mode" id="mode" required>
<option value=""> --- Select Interciew Mode --- </option>
<option value="telephonic">Telephonic</option>
<option value="facetoface">Face 2 face</option>
<option value="skype">Skype</option>
</select>
</div>
</div><hr>
This is my controller
public function candidateDetail($id)
{
$empDetails = User::all();
$candidateDetail = EmployeeHire::find($id);
$interview = [
'' => '--- Select Interciew Mode ---',
'telephonic' => 'Telephonic',
'facetoface' => 'Face 2 face',
'skype' => 'Skype'
];
return view('pages.candidatedetails', compact('id', 'candidateDetail', 'empDetails', 'interview'));
}
You can check in your foreach if the value of nameOfDepartment match the one from your user.
<div class="form-group">
<label class="col-md-12">Department</label>
<div class="col-md-12">
<select class="custom-select form-control col-md-11" id="department" name="department">
#foreach($listDepartment as $departmentList)
#if ($profile->personal_profile['department'] == $departmentList->nameOfDepartment)
<option value="{{$departmentList->nameOfDepartment}}" selected="selected">{{$departmentList->nameOfDepartment}}</option>
#else
<option value="{{$departmentList->nameOfDepartment}}">{{$departmentList->nameOfDepartment}}</option>
#endif
#endforeach
</select>
</div>
</div>
For your second select field, create an array with all possible values in your controller.
$interview = [
'' => '--- Select Interciew Mode ---',
'telephonic' => 'Telephonic',
'facetoface' => 'Face 2 face',
'skype' => 'Skype'
];
Then you can do the same as your previous select :
<select class="custom-select form-control col-md-12" name="mode" id="mode" required>
#foreach($interview as $key => $name)
#if ($profile->personal_profile['interview'] == $key)
<option value="{{ $key }}" selected="selected">{{ $name }}</option>
#else
<option value="{{ $key }}">{{ $name }}</option>
#endif
#endforeach
</select>
I have created a Laravel form, but I have encountered a few problems. When the form submits with information that does not meet the requirements, I want the form to redirect and to display the validation errors on the form (under the input). Furthermore, when the form redirects, I want it to keep the previous (old) values. Please give me some guidance.
Problem:
When I input information that does not match the validation requirements, the form refreshes, but none of the validation errors show up and none of the old input stays. (I simply get a brand new form with none of the old inputs and no validation errors.)
HTML:
<form role="form" action="" method="post" class="registration-form">
<fieldset>
{{ csrf_field() }}
<div class="form-top">
<div class="form-top-left">
<h3>Insight Contributor Account Info</h3>
</div>
<div class="form-top-right">
</div>
</div>
<div class="form-bottom" style="height: 400px">
<!--Name-->
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<div class="col-md-8 col-md-offset-2">
<input id="name" type="text" class="form-control" name="name"
placeholder="Full Name (e.g. John Doe)" value="{{ old('name') }}">
<br>
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
<h3> name is required</h3>
</span>
#endif
</div>
</div>
<!--Email-->
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<div class="col-md-8 col-md-offset-2">
<input id="email" type="email" class="form-control" name="email"
placeholder="Primary Email Address (e.g.Jdoe#gmail.com)"
value="{{ old('email') }}"><br>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<!--Password-->
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<!-- <label for="password" class="col-md-4 control-label">Password</label>-->
<div class="col-md-8 col-md-offset-2">
<input id="password" type="password" class="form-control"
placeholder="Password (at least 6 character)" name="password"><br>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<!--PasswordConfirm-->
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
<div class="col-md-8 col-md-offset-2">
<input id="password-confirm" type="password" class="form-control"
placeholder="Confirm Password" name="password_confirmation"><br>
#if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
<h3> password mismatch</h3>
</span>
#endif
</div>
</div>
</div>
<div class="form-top" style="margin-top: 10px">
<div class="form-top-left">
<h3>Professional Information</h3>
</div>
</div>
<div class="form-bottom" style="height: 460px">
<!--Primary Industry(single value)-->
<div class="form-group{{ $errors->has('industry') ? ' has-error' : '' }}">
<div class="col-md-8 col-md-offset-2"><br>
<select class="form-control selectpicker" name="industry" id="industry">
<option selected disabled>Primary Industry</option>
<option>Art</option>
<option>Business</option>
<option>Law</option>
<option>Media</option>
<option>Medicine</option>
<option>Education</option>
<option>Technology</option>
<option> Science</option>
<option>Service</option>
<option>Other</option>
</select>
#if ($errors->has('industry'))
<span class="help-block">
<strong>{{ $errors->first('industry') }}</strong>
</span>
#endif
</div>
</div>
<!--Primary Job Function (single value)-->
<div class="form-group{{ $errors->has('job_function') ? ' has-error' : '' }}">
<div class="col-md-8 col-md-offset-2"><br>
<select class="form-control selectpicker" name="job_function"
id="job_function">
<option selected disabled>Primary Job Function</option>
#foreach($professions as $profession)
<option #if ($profession->id == old('job_function_id')) selected
#endif value="{{ $profession->id }}">{{ $profession->name }}</option>
#endforeach
</select>
#if ($errors->has('job_function'))
<span class="help-block">
<strong>{{ $errors->first('job_function') }}</strong>
</span>#endif
</div>
</div>
<!--Add relative experience (multi tag)-->
<div id="tags" class="form-group" style="margin-top: 30px">
<div class="col-md-8 col-md-offset-2"><br>
<select id="test" style="width: 100%;margin-left: 10%;" name="tags[]"
multiple>
<option value="root" disabled="disabled">Tags</option>
<option value="level11" parent="root" disabled="disabled">Subjects
</option>
<option value="level12" parent="root" disabled="disabled">Grades
</option>
<option value="level13" parent="root" disabled="disabled">Relationship
Management
</option>
<option value="level14" parent="root" disabled="disabled">Classroom
Management & Design
</option>
<option value="level15" parent="root" disabled="disabled">Curricula &
Resources
</option>
<option value="level16" parent="root" disabled="disabled">Professional
Growth & Career Management
</option>
<option value="level17" parent="root" disabled="disabled">More</option>
#foreach($tags as $tag)
#if($tag->category =='Subjects')
<option value='{{ $tag->id }}'
parent="level11"> {{$tag->name}}</option>
#endif
#if($tag->category =='Grades')
<option value='{{ $tag->id }}'
parent="level12"> {{$tag->name}}</option>
#endif
#if($tag->category =='Relationship Management')
<option value='{{ $tag->id }}'
parent="level13"> {{$tag->name}}</option>
#endif
#if($tag->category =='Classroom Management & Design')
<option value='{{ $tag->id }}'
parent="level14"> {{$tag->name}}</option>
#endif
#if($tag->category =='Curricula & Resources')
<option value='{{ $tag->id }}'
parent="level15"> {{$tag->name}}</option>
#endif
#if($tag->category =='Professional Growth & Career Management')
<option value='{{ $tag->id }}'
parent="level16"> {{$tag->name}}</option>
#endif
#if($tag->category =='More')
<option value='{{ $tag->id }}'
parent="level17"> {{$tag->name}}</option>
#endif
#endforeach
</select>
#if ($errors->has('tags'))
<span class="help-block">
<strong>{{ $errors->first('tags') }}</strong>
</span>
#endif
</div>
</div>
<!--Bio-->
<div class="form-group{{ $errors->has('bio') ? ' has-error' : '' }}">
<!-- <label for="bio" class="col-md-4 control-label">Short Bio</label> -->
<div class="col-md-8 col-md-offset-2"><br>
<textarea id="bio" class="form-control" placeholder="Brief profile bio"
name="bio">{{ old(nl2br('bio')) }}</textarea><br>
#if ($errors->has('bio'))
<span class="help-block">
<strong>{{ $errors->first('bio') }}</strong>
</span>
#endif
</div>
</div>
</div>
<div class="form-top" style="margin-top: 10px">
<div class="form-top-left">
<h3> Agreements </h3>
</div>
<div class="form-top-right">
</div>
</div>
<div class="form-bottom">
<!--Terms-->
<h2 class="section-heading">Cypress Community Principles</h2>
<p class="lead">
<br>
Teachers value each other for their expertise.<br><br>
Teachers believe in the power of collaboration and will work together to engage
in
open and honest dialogue, provide guidance and mentorship, and create content
that
supports growth and success for fellow teachers.<br><br>
Teachers will respect each other and be mindful of what they post. We encourage,
open and honest communication, a diversity of perspectives, and thoughtful
disagreement. Harassment, disrespect, and inappropriate content are not
tolerated.<br><br>
Teachers will actively engage in fostering a positive community of learning and
growth.<br><br>
Teachers are the most significant influence on a student’s academic achievement
and
will support fellow teachers as agents of change and innovators of
education.<br><br>
</p>
<form action="#"
onsubmit="
if(document.getElementById('agree').checked) {
return true;
} else
{ alert('Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy');
return false;
}">
<input type="checkbox" name="checkbox" value=0 id="agree"/> I have read and
agree to
the Community Principle,
<a href="/terms" style="color: #5dc19f">Terms
and Conditions
</a> and
<a href="/privacypolicy" style="color: #5dc19f">Privacy
Policy</a><br><br>
</form>
<!--Signup botton-->
<button type="submit" id="submit" class="btn btn-default"
style="background-color: #a5d5a7">
<i class="fa fa-btn fa-user"></i> Sign me up!
</button>
<button type="button" class="btn btn-default" style="background-color: #a5d5a7">
<a class="btn btn-link" href="{{ url('/') }}" style="color: whitesmoke">
Cancel </a>
</button>
</div>
</fieldset>
</form>
PHP:
public function register(Request $request)
{
$tags = Tag::all();
$professions = Profession::all();
if ($request->isMethod('post')) {
$validator = $this->validateRegister($request->input());
if ($validator->fails()) {
return back()->withErrors($validator)->withInput(); //TODO
}
$user = Iuser::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password']),
'bio' => $request['bio'],
'industry' => $request['industry'],
'confirmation_code' => str_random(30),
'job_function' => $request['job_function'],
]);
$user ->tags()->sync($request['tags']);
#event(new NewUserWasRegistered($user));
if($user->save()){
return redirect('/insight/login')->with('success', 'Welcome to Cypress!');
}else{
return back()->with('error', 'Register failed!')->withInput();
}
}
$datas = array('tags' => $tags, 'professions'=>$professions);
#return $user;
return view('iauth.register')->with($datas);
}
protected function validateRegister(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:6',
'bio' => 'required',
'industry' => 'required|string',
'job_function' => 'required|string',
], [
'required' => ':attribute is required',
'min' => ':attribute is too short',
'confirmed' => 'different passwords',
'unique' => 'This email exits',
'max' => ':attribute is too long'
]);
}
Allow me to take a different and a more structured approach to organizing your backend code.
First let's arrange that validator function into a class
https://laravel.com/docs/5.6/validation#creating-form-requests
write down: php artisan make:request RegisterUser
https://laravel.com/docs/5.6/validation
This will create something like this under App\Http\Requests:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterUser extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$content = [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6', //confirmed means it will receive password_confirmed aswell
'bio' => 'required',
'industry' => 'required|string',
'job_function' => 'required|string'
];
return $content;
}
}
On your Controller, you'd have:
use App\Http\Requests\RegisterUser;
.
.
.
public function register(RegisterUser $request)
{
//fetch the validated data to this $data variable, that is now an array
$data = $request->validated(); //Or all, whatever you'd like
//add this variable to the array
$data['confirmation_code'] = str_random(30);
//since all inputs have the same name as your table, you can just give it to him and he'll insert
//Whatever is in your $fillable array in Iuser, it will be filled and only that.
//If you send more data than needed, theres no worries as he will only insert what is in that array.
$user = Iuser::create(data);
//? dunno but sure
$user ->tags()->sync($request['tags']);
//Something about some event
#event(new NewUserWasRegistered($user));
return redirect('/insight/login')->with('success', 'Welcome to Cypress!');
}
Now, why I removed so much code:
Instead of having all in one place (you still have a few different operations in the controller), you have now separated it's logic structure. Validations of the requests made to the backend are in FormRequests and by the time it reaches the controller, they are validated and the Controller just needs to insert and outputs what is expected.
Q1. Should you have a try catch? If there is a chance the database is not local or something unexpected, yes.
Q2. Can I abstract even more code from the controller? Yes and you should, controller, in my opinion, should just call someone else (another class) to handle insert or update operations and return answers.
Q3. This is pretty and all but, how do I get my old values from the inputs? Whenever you're handling with FormRequests, Laravel returns a 422 status code, alongside an object called MessageBagError (not of much interest for now) but as long as you have old in your inputs (and the old('inputname') equals the name of the variable that is going to be received in this FormRequest - that is on your rules btw), blade will detect it and fill them. If, in on another situation, you want to redirect()->back()->withInput(); you can just set the $request or the array inside of withInput($data) and remember to keep {{ old ('value') }} and it SHOULD be automatically filled by Laravel (because {{ }} is explicit to laravel's blade and allows you to write php code in it if needed).
https://laravel.com/docs/5.6/requests#old-input
Q4. Why did I remove the HTTPPost validation? Because on your route folder, you can establish the routes and the httpverbs (e.g.
Route::get('home',function(){
return view('home');
})->name("home");
Route::post('register', "RegisterController#register");
//Meaning, anyone who attempts to access host/register by not using HTTPost will receive a 405 Status code (Method not allowed)
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
I can update text field of a form but i can not update checkbox field,option field and file field in Laravel 5.2. I i going to update then i can see all text value is perfectly shown in update blade view but in option field, checkbox field i see it is default value its don't comes from database. Again if i update with another option then its not saving.What i have tried so far:
My Controller:
public function update(Request $request, $id=0)
{
//
$id = $request->input("id");
$product = Product::find($id);
$product->product_name = $request->input('product_name');
$product->product_storage = $request->input('product_storage');
$product->product_percentage = $request->input('product_percentage');
$product->can_draw = $request->input('can_draw');
$product->real_price = $request->input('real_price');
$product->product_image = $request->input('product_image');
$product->save();
$request->session()->flash('alert-info', 'Product Successfully Updated!');
return Redirect::to('admin/product/all');
}
My update.blade.php View:
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('common.can_be_draw') }}</label>
<div class="col-md-9">
<div class="input-icon">
<i class="fa fa-money" aria-hidden="true"></i>
<select name="can_draw" class="form-control">
<option value="{{ $product->can_draw }}">{{ trans('common.open') }}open</option>
<option value="{{ $product->can_draw }}">{{ trans('common.close') }}close</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('common.real_prize') }}</label>
<div class="col-md-9">
<div class="input-icon">
<input type="radio" class="form-control" name="real_price" value="{{ $product->real_price }}"> {{ trans('common.yes') }}yes
<input type="radio" class="form-control" name="real_price" value="{{ $product->real_price }}" checked="checked"> {{ trans('common.no') }}no
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-md-3 control-label">{{ trans('common.product_picture') }}</label>
<div class="col-md-9">
<input type="file" id="exampleInputFile" name="product_image" value="{{ $product->product_image }}">
<small>{{ trans('common.pic_summery') }}</small>
</div>
</div>
Just use this:
<input type="radio" {{$product->can_draw == 'Yes' ? 'checked' : ''}} class="form-control" name="real_price" value="Yes"> {{ trans('common.yes') }}yes
<input type="radio" {{$product->can_draw == 'Yes' ? '' : 'checked'}} class="form-control" name="real_price" value="No" > {{ trans('common.no') }}no
EDIT
I have edited the above*
You should change the value to Yes and No and use this to check if the value saved is Yes or No. It does not matter how much is real_price
your option field have same value ({{ $product->can_draw }})
<option value="value1"{{( $product->can_draw=='value1'?selected)}}>{{ trans('common.open') }}open</option>
<option value="value2 " {{( $product->can_draw=='value1'?selected)}}>{{ trans('common.close') }}close</option>
and for file field must use file not input:
$product->product_image = $request->file('product_image');
You just can save option value by requesting from select name.
In your example:
select name = "can_draw"
Just save value from request:
$product->can_draw = $request->can_draw;
For checkbox same:
$product->real_price = $request->real_price;
Not necessary indicate input() helper in request.
To retrieve all value for option and check box value, please use foreach methods:
#foreach($can_draws as $can_draw)
<option value="{{ $can_draw->id }}">{{ $can_draw->name}}</option>
#endforeach
I have database with types such as:
Entertainment & Food,
Health & Care
etc.
I insert it into a dropdown like this:
<div class="form-group{{ $errors->has('type') ? ' has-error' : '' }}">
<div class="type_message form-control alert-warning" style="display: none;"></div>
<label id="type2" for="type" class="col-md-4 control-label">Type</label>
<div class="col-md-6">
<select class="form-control" name="type" id="type">
<option selected value="{{ $entity->type }}">{{ $entity->type }}</option>
#foreach ($entities as $entity_select)
<option value={{ $entity_select->type}}>{{ $entity_select->type }}</option>
#endforeach
</select>
#if ($errors->has('type'))
<span class="help-block">
<strong>{{ $errors->first('type') }}</strong>
</span>
#endif
</div>
</div>
The problem is that when I check the value of the field it looks like this:
<option value="Entertainment & Nightlife" selected="">Entertainment & Nightlife</option>
Therefore in the database it only adds "Entertainment" how can I avoid that?
<option value="{!! $entity_select->type !!}">{!! $entity_select->type !!}</option>
https://laravel.com/docs/5.4/blade#displaying-data
As mentionned in the documentation :
Be very careful when echoing content that is supplied by users of your
application. Always use the escaped, double curly brace syntax to
prevent XSS attacks when displaying user supplied data.