Hello i have this code in blade where i select dynamic product and amount and i insert it in an array but i have a problem that the values are not added but replaced, this is my code:
<div class="row mb-3">
<label for="products" class="col-md-4 col-form-label text-md-end">{{ __('Product') }}</label>
<div class="col-md-6">
<select name="productOrder[product][product_id]" id="products" type="text" class="form-control #error('products') is-invalid #enderror" required autocomplete="products"> #foreach($products as $product) <option value="{{$product->id}}">{{$product->name}}</option> #endforeach </select> #error('products') <span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span> #enderror
</div>
</div>
<div class="row mb-3">
<label for="amount" class="col-md-4 col-form-label text-md-end">{{ __('Amount') }}</label>
<div class="col-md-6">
<input id="amount" type="text" class="form-control #error('amount') is-invalid #enderror" name="productOrder[product][amount]" required autocomplete="amount"> #error('amount') <span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span> #enderror
</div>
</div>
I have selected 2 products and insert 2 amounts for them but when i make dd i get this:
array:2 [▼ // app/Http/Controllers/OrderController.php:39
"product_id" => "2"
"amount" => "20"
]
The result im trying to get is this:
array:2 [▼ // app/Http/Controllers/OrderController.php:39
"product_id" => "2"
"amount" => "20"
"product_id"=>"4"
"amount" => "30"
]
I get the array fixed if i just delcare it productOrder[][] but then my result show up like this:
array:4 [▼ // app/Http/Controllers/OrderController.php:42
0 => array:1 [▼
0 => "1"
]
1 => array:1 [▼
0 => "10"
]
2 => array:1 [▼
0 => "2"
]
3 => array:1 [▼
0 => "20"
]
]
But i need it with nametag so i can fetch it like this in Controller:
foreach ($request->productOrder as $product)
{
dd($product['amount']);
}
You can not use multiple inputs with the same input name. To make them unique you can use an index for each set of options.
#foreach($rows as $index => $row)
<input name="product[{{ $index }}][product_id]"/>
<input name="product[{{ $index }}][amount]"/>
#endforeach
Related
Hello i am wondering if its possible to have an array in view blade that is filled with values that user selects and then to be passed to controller. I am asking if its possible to do such a thing and avoid this type of code i already have that works:
foreach ($request->products as $index => $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product,
'amount' => $request->amount[$index],
];
So for the foreach i dont need to write $index => $product
This is the request that comes from view:
$request->validate([
'order_number' => 'required',
'client_id' => 'required|exists:clients,id',
'description' => 'required',
'products' => 'required|exists:products,id',
'amount' => 'required',
]);
And this is the view im using:
<div class="row mb-3">
<label for="products" class="col-md-4 col-form-label text-md-end">{{ __('Product') }}</label>
<div class="col-md-6">
<select name="products[]" id="products" type="text" class="form-control #error('products') is-invalid #enderror" required autocomplete="products">
#foreach($products as $product)
<option value="{{$product->id}}">{{$product->name}}</option>
#endforeach
</select>
#error('products')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-3">
<label for="amount" class="col-md-4 col-form-label text-md-end">{{ __('Amount') }}</label>
<div class="col-md-6">
<input id="amount" type="text" class="form-control #error('amount') is-invalid #enderror" name="amount[]" required autocomplete="amount">
#error('amount')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
We can use the input name to create an associative array using the product id as the key in the array.
You can achieve this by subbing in the product id for the array index and labelling the fields that will go into it.
<input type="number" name="products[ {{$product_id}} ][amount]">
<input type="text" name="products[ {{$product_id}} ][otherField]">
This will product a structure like
["products"]=> array(2)
{ [101]=> array(2) {
["amount"]=> string(2) "10" ["otherField"]=> string(7) "LABEL 1" }
[102]=> array(2) {
["amount"]=> string(2) "20" ["otherField"]=> string(7) "LABEL 2" }
}
While you will still have to iterate using foreach($request->products as $productID => $data) the data structure is all relational regarding where the data is stored.
If I understand your question correctly, you want to avoid JQuery? It depends on what environment and language you're using. In ASP .NET Core you can use a hidden input field and pass something through as text.
<input hidden type="text" name="productsString" value="#JsonSerializer.Serialize(products)" />
Then in your controller you can deserialize it (C# example).
var products = JsonSerializer.Deserialize<Object>(productsString);
Maybe that's what you're looking for but it really depends on what you're doing, which I'm not sure about.
in Laravel and my web application i have a simple form which i pasted below line:
<form class="form-horizontal" action="{{url('/addToContactUs')}}" method="POST">
#csrf
<div class="form-group required">
<label class="col-md-2 col-sm-3 control-label" for="name">Your Name</label>
<div class="col-md-10 col-sm-9">
<input type="text" name="name" value="{{old('name')}}" class="form-control"/>
</div>
</div>
<div class="form-group required">
<label class="col-md-2 col-sm-3 control-label" for="email">Your Email</label>
<div class="col-md-10 col-sm-9">
<input type="text" name="email" value="{{old('email')}}" class="form-control"/>
</div>
</div>
<div class="form-group required">
<label class="col-md-2 col-sm-3 control-label" for="enquiry">Your Enquiry</label>
<div class="col-md-10 col-sm-9">
<textarea name="enquiry" rows="10" class="form-control">{{old('enquiry')}}</textarea>
</div>
</div>
<div class="buttons">
<div class="pull-left">
<input class="btn btn-primary" type="submit" value="SUBMIT"/>
</div>
</div>
</form>
when i try to validate form fields, i get this error:
array:3 [▼
1 => array:1 [▼
0 => "The 1 field is required."
]
3 => array:1 [▼
0 => "The 3 field is required."
]
5 => array:1 [▼
0 => "The 5 field is required."
]
]
and when i try to log $request i have:
array:4 [▼
"_token" => "W8xPG039mlT0WGs0kw9lWV0FivYxKSx4XHg6LPkQ"
"name" => "this is my name"
"email" => "hello#gmail.com"
"enquiry" => "hello hello hello hello hello hello "
]
it seems all implementations are correct and i don't know why i get this error.
route for submitting this form:
Route::post('/addToContactUs', 'HomeController#addToContactUs');
and controller action:
public function addToContactUs(Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name', 'required|string|min:5|max:191',
'email', 'required|string|min:5|max:191|email',
'enquiry', 'required|string|min:5',
]
);
if ($validator->fails()) {
dd($validator->errors()->messages(),$request->all());
}
}
After seeing your full validation method again & again, I got the error here, 'name', 'required… it will be 'name' => 'required…. Its just a typo, so your code will be :
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string|min:5|max:191',
'email' => 'required|string|min:5|max:191|email',
'enquiry' => 'required|string|min:5',
]
);
I want to insert candidate language information into db and only for authenticated user. Candidate can add more languages. All info insert for the authenticated user.Authenticated Candidate can also
Here is my view code:
<form action="{{url('/candidate/addLanguage')}}" method="post">
#csrf
<!-- Education -->
<div class="form with-line">
<h5>Language Proficiency</h5>
<div class="form-inside">
<!-- Add Education -->
<div class="form boxed box-to-clone education-box">
<i class="fa fa-close"></i>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4"> Language</label>
<input type="text" name="txt_language[]" class="form-control" id="inputEmail4" placeholder="Language">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Reading</label>
<select name="txt_reading[]" id="" class="form-control">
<option value="#" selected>Choose..</option>
<option value="High">High</option>
<option value="Medium">Medium</option>
<option value="Low">Low</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4"> Writing</label>
<select name="txt_writing[]" id="" class="form-control">
<option value="#" selected>Choose..</option>
<option value="High">High</option>
<option value="Medium">Medium</option>
<option value="Low">Low</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Speaking</label>
<select name="txt_speaking[]" id="" class="form-control">
<option value="#" selected>Choose..</option>
<option value="High">High</option>
<option value="Medium">Medium</option>
<option value="Low">Low</option>
</select>
</div>
</div>
</div>
<i class="fa fa-plus-circle"></i> Add Language
</div>
</div>
<button type="submit" class="btn btn-success btn-sm float-right">Submit</button>
</form>
My Controller :
public function addLanguage(Request $request){
$candidateID = Auth::guard('candidate')->user()->id;
if (count($request->txt_language) > 0){
foreach ($request->txt_language as $language => $l){
$data = array(
'candidate_id' => $candidateID,
'language' => $request->txt_language[$language],
'reading' => $request->txt_reading[$language],
'writing' => $request->txt_writing[$language],
'speaking' => $request->txt_speaking[$language],
) ;
Language::insert($data);
}
}
return redirect('/candidate/referencesForm')->with('success','Language Information Save Successfully..');
}
I get this error :
Attempt to assign property 'candidate_id' of non-object
Where I missing anything? How can I solve this error? Please Help
its "dd($request->all()); " output:
array:5 [▼
"_token" => "pcKuRe8xI8WzRYQefwY7GMw1Zo6vighrZ6k7PUNi"
"txt_language" => array:3 [▼
0 => "English"
1 => "Bangla"
2 => null
]
"txt_reading" => array:3 [▼
0 => "Medium"
1 => "Medium"
2 => "High"
]
"txt_writing" => array:3 [▼
0 => "High"
1 => "Low"
2 => "High"
]
"txt_speaking" => array:3 [▼
0 => "High"
1 => "High"
2 => "High"
]
]
Jquery Code:
$('.box-to-clone').show();
$('.add-box').on('click', function(e) {
e.preventDefault();
var newElem = $(this).parent().find('.box-to-clone:first').clone();
newElem.find('input').val('');
newElem.prependTo($(this).parent()).show();
var height = $(this).prev('.box-to-clone').outerHeight(true);
$("html, body").stop().animate({ scrollTop: $(this).offset().top-height}, 600);
});
$('body').on('click','.remove-box', function(e) {
e.preventDefault();
$(this).parent().remove();
});
Please follow the below format,
foreach ($request->txt_language as $language => $l){
$data = new Language;
$data->candidate_id => $candidateID,
$data->language => $request->txt_language[$language],
$data->reading => $request->txt_reading[$language],
$data->writing => $request->txt_writing[$language],
$data->speaking => $request->txt_speaking[$language],
$data->save();
}
Hope this would fix your issue. Let me know if you face further issue.
Try this :
public function addLanguage(Request $request){
$candidateID = Auth::guard('candidate')->user()->id;
if(!empty($candidateID)){
if (count($request->txt_language) > 0){
foreach ($request->txt_language as $language => $l){
Language::create([
'candidate_id' => $candidateID,
'language' => $l,
'reading' => $request->txt_reading[$language],
'writing' => $request->txt_writing[$language],
'speaking' => $request->txt_speaking[$language],
]);
}
}
return redirect('/candidate/referencesForm')->with('success','Language Information Save Successfully..');
}
abort(404);
}
So I have created looped generated radio-buttons:
<div class="custom-control custom-radio guest-form">
#foreach(config('const.res_site') as $id => $res)
<div class="form-radio">
<input class="custom-control-input" type="radio" onchange="otherResSite({{$id}})" id="{{$res}}" value="{{$id}}"
name="reservation_site" {{ old("reservation_site") == $id ? "checked" : "" }}>
<label for="{{ $res }}" class="custom-control-label">{{ $res }}</label>
</div>
#endforeach
<div class="otherField" id="ifOtherSite" class="otherSite" style="display: {{ old('reservation_site') == 4 ? 'display:inline-flex' : 'none' }}">
<input type='text' class="form-control" id='otherSite' name='otherSite' value="{{ old('otherSite', '') }}"><br>
</div>
</div>
#if ($errors->has('otherSite'))
<div class="form-group">
<p class="text-danger">{{ $errors->first('otherSite') }}</p>
</div>
#endif
const.php
'res_site' => [
0 => 'site1',
1 => 'site2',
2 => 'other',
],
This one is to validate the otherSite value if selected option is other. It now works well but the validation message returned is like this:
The other site field is required when reservation site is 2.
My validator is like this:
return [
'reservation_site' => ['required'],
'otherSite' => ['required_if:reservation_site,2'],
]
Now, how can I make its return message as
The other site field is required when reservation site is other
Is there any way I can do that?
Okay. If someone might need this someday, I did it this way:
<input class="custom-control-input" type="radio" id="{{$res}}" value='{{$id == 4 ? "other" : $id}}'>
and in my validation:
return [
'reservation_site' => ['required'],
'otherSite' => ['required_if:reservation_site,other'],
]
I am trying to do registration with user profile picture upload.(I am forced to do it this way)
I created the migration like this:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->string('prenom');
$table->string('type')->default('visiteur');
$table->boolean('confirme')->default(false);
$table->string('email')->unique();
$table->string('password');
$table->string('photo_url')->default('default_photo_profile.jpg');
$table->rememberToken();
$table->timestamps();
});
the create function :
$request = request();
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
and the form for the file field is like this:
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
everything is working fine except the photo_url field, it always sets the default value in the migration and not the value I set in the create function.
$fullname is initiated and already declared.
the entire form :
<form method="POST" action="{{ route('register') }}" aria-label="{{ __('Register') }}" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label for="nom" class="col-md-4 col-form-label text-md-right">Nom</label>
<div class="col-md-6">
<input id="nom" type="text" class="form-control{{ $errors->has('nom') ? ' is-invalid' : '' }}" name="nom" value="{{ old('nom') }}" required autofocus>
#if ($errors->has('nom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('nom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="prenom" class="col-md-4 col-form-label text-md-right">Prénom</label>
<div class="col-md-6">
<input id="prenom" type="text" class="form-control{{ $errors->has('prenom') ? ' is-invalid' : '' }}" name="prenom" value="{{ old('prenom') }}" required autofocus>
#if ($errors->has('prenom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('prenom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Mot de pass</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Mot de pass confirmation</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Envoyer
</button>
</div>
</div>
</form>
What is the problem?
Assuming you have a value for $photo_url, make sure you have 'photo_url' in your $fillables.
When you have $fillables, it only inserts (via User::create) what has in that array, otherwise it doesn't submit for that variable.
Your $fillables should look like this:
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
Add 'photo' in $fillable array in User model:
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'photo_url',
];
so according to your code in your model you have to add the photo_url in $fillable array like below.
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
okay now there are 3 ways to do it with $fillable is first way and you are doing it right now.
2nd way:
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
else
{
$fullname = "default_photo_profile.jpg";
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
and in your migration change this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
3rd way:
$fullname = "default_photo_profile.jpg";
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
okay these are the ways to do it. i would prefer first and second way 3rd one is lengthy.
Note: for 2nd and 3rd case you have to change your migration from this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
Hope you get it.