multiple value from dropdown in livewire - php

I have a dropdown and text input in a form. Form creates a course and I want to select classroom for course from dropdown and write its capacity to text input. But a course may have mutiple classrooms. How can I keep these classrooms and their capacity and show them in a table under the form?Like this:
Here's my code that keeps only one classroom and capacity
<div class="sm:col-start-1 sm:col-end-3 col-span-3 ">
<x-select x-on:change="isShowing = $event.target.value" name="classroom_id" label="{!! __('Classroom') !!}" wire:model="classroom_id"
id="classroom_id"
:options="$this->classrooms"/>
<x-jet-input-error for="classroom_id" class="mt-2" />
</div>
<div class="col-span-2 sm:col-span-1 " x-show="isShowing">
<label class="tf-form-label" for="capacity">
{{ __('Capacity') }}
</label>
<input wire:model.debounce.250ms="capacity" type="text" name="capacity" id="capacity" class="tf-input" />
<x-jet-input-error for="capacity" class="mt-2" />
</div>
$this->form->save();// firstly course saved
$classroom = new Classroom();
$classroom->course_id = $this->form->id;
$classroom->classroom_id = $this->classroom_id;
$classroom->capacity = $this->capacity;
$classroom->save();

Add the following codes in your component.
Component
public $classroom_id, $capacity;
$course = Course::create($validatedCourseData); // firstly course saved
// $this->classroom_id is array, because we set "multiple" in blade file
$course->classrooms()->attach($this->classroom_id);
Blade
Please add multiple in in your select box code.
<div class="sm:col-start-1 sm:col-end-3 col-span-3 ">
<x-select x-on:change="isShowing = $event.target.value" name="classroom_id" label="{!! __('Classroom') !!}" wire:model="classroom_id"
id="classroom_id"
:options="$this->classrooms" multiple/>
<x-jet-input-error for="classroom_id" class="mt-2" />
</div>
<div class="col-span-2 sm:col-span-1 " x-show="isShowing">
<label class="tf-form-label" for="capacity">
{{ __('Capacity') }}
</label>
<input wire:model.debounce.250ms="capacity" type="text" name="capacity" id="capacity" class="tf-input" />
<x-jet-input-error for="capacity" class="mt-2" />
</div>

Related

laravel 9 form validation error has space between field name

There are space comes after every character of field name while displaying errors in blade template in laravel 9 as mentioned in uploaded image
my code is mentioned as below
CODE IN HTML IS :
<form action="{{route('saveAsset')}}" method="post">
{{#csrf_field()}}
<div class="form-group">
<label for="assetTitle" class="mt-2 mb-2">{{$assetCategory->category}} TITLE :</label>
<input type="text" class="form-control" name="assetTitle" id="assetTitle" placeholder="Enter Asset Title">
</div>
<div class="inputError">#error('assetTitle') Error: {{ $message }} #enderror </div>
<input type="hidden" name="assetCateId" id="assetCateId" value="{{$assetCategory->id}}">
#if(count($attributes) > 0)
#foreach($attributes as $attribute)
<label for="assetType-{{$attribute->attr_id}}" class="mt-4 mb-2">{{$attribute->attr_title}} : </label>
<div class="form-group">
<select class="form-select" name="{{$attribute->attr_title}}" id="attribute-{{$attribute->attr_id}}" aria-label="Default select example">
<option value="">Select {{$attribute->attr_title}}</option>
#foreach($attrValues as $attrValue)
#if ($attrValue->attr_id == $attribute->attr_id && strlen($attrValue->value) > 0 )
<option value="{{$attribute->attr_id}}-{{$attrValue->value_id}}" > {{$attrValue->value}}</option>
#endif
#endforeach
</select>
</div>
<div class="inputError"> #error("{$attribute->attr_title}") Error: {{ $message }} #enderror </div>
#endforeach
#endif
<div>
<button type="submit" class="btn btn-primary mt-3 px-4">Save</button>
</div>
</form>
CODE IN CONTROLLER IS :
$fields = $req->input();
$ValidationRules=[];
foreach($fields as $fieldName=>$fieldvalue){
if($fieldName == "assetTitle"){
$ValidationRules[$fieldName] = 'required|unique:assets,title';
}else{
$ValidationRules[$fieldName] = 'required';
}
}
$req->validate($ValidationRules);
I guess you have made some changes in resources/lang/en/validation.php file.
in this or any language you have set , there is a attribute named attributes
that you can change the the attribute name displaying in error message.
because the error message of asset field is ok I do not think it's a general error . check this file and attributes or messages key in it.
Don't know if you still need help but I just had the same issue and I think it's because you might have the input names with text uppercase, laravel automaticly adds a space for each uppercase character in the name attribute when showing the errors.
For example:
name="thisModel"
Will display as:
... this Model ...
If you have:
name="MODEL"
Will display as:
... M O D E L ...
Hope this helps someone in the future x)

Laravel 8, how to upload more than one image at a time

I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}

Array management and preview with Laravel Livewire

When using an input file to load images with Livewire I found that if the user clicks to load multiple images it works correctly, but if he clicks on the same input a second time, the previews with Livewire are replaced by the selected images. second time. To solve this add an array that loads the images as follows:
My input file
<input wire:change="cargaImagenes" wire:model="imagen" type="file" name="imagen" accept="image/*" class="form-control-file" multiple>
Event Charge
public function cargaImagenes()
{
foreach ($this->imagen as $ima) {
array_push($this->imagenes, $ima);
}
}
The problem is that I do the previews of the images with Livewire in the following way:
#if ($imagenes)
<small>previsualización:</small>
<div class="form-inline">
#foreach($imagenes as $img)
<div wire:key="{{$loop->index}}">
<div class="m-2 img-thumbnail">
<img class="my-2 rounded img-fluid contenedor-img" src="{{ $img->temporaryUrl() }}">
<button class="btn btn-outline-danger" wire:click="eliminarImagen({{ $loop->index }})">
</button>
</div>
</div>
#endforeach
<br>
</div>
#endif
And the problem is that they don't show the first time I select images, it shows when I add more.
For the preview I use the $images property of the array
array_push($this->imagenes, $ima);
Can you give me a suggestion of what I could do to display all the images in the array.
This should work.
Remove wire:change completely.
<input wire:model="imagen" type="file" name="imagen" accept="image/*" class="form-control-file" multiple>
Hook on the updatedImagen() event method:
public function updatedImagen()
{
foreach ($this->imagen as $ima) {
$this->imagenes[] = $ima;
}
}

Laravel form submission with url parameters

When the user accesses a certain brand page, I pull the information associated with that brand. Then the user has the chance to submit an application for this brand.
When the user submits the form, I want the form to post to /apply/brand/{brand_id} because I want to store this application in my application table with the brand_id as one of the fields (the other fields in this table comes from the fields in my form, but the brand_id will be an URL parameter)
The problem is that when I submit the form, the form posts to /apply/brand/undefined and the submission does not work correctly. I do not reach the ApplicationController#apply_store method.
EDIT:
To debug my problem, I printed out the {{$brand -> id }} right before the element and it printed out fine. However, when the form submits, it goes to /apply/brand/undefined instead of /apply/brand/{{$brand -> id }}. The $brand variable somehow becomes undefined inside of my form.
EDIT:
I hardcoded the from to submit to /apply/brand/43. When I press submit, the url shows up as /apply/brand/43 at first but then quickly changes to /apply/brand/undefined before redirecting me to my default page.
Controller Method for Accessing a Brand Page
public function brandProfile(){
$brand = Brand::where('user_id', Auth::user()->id)->first();
$industry = Industry::where('status', 1)->get();
return view('new-design.pages.profile_brand')
->withData($brand)
->withIndustry($industry);
}
Brand Application Form
<form id="application_form" method="post" action="/apply/brand/{{ $data -> id }}" enctype="multipart/form-data">
{{ csrf_field() }}
<ul>
<div class="col-md-6">
<li>
<label>First Name</label>
<input type="text" class="form-control" name="firstname" placeholder="First Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Last Name</label>
<input type="text" class="form-control" name="lastname" placeholder="Last Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Email</label>
<input type="email" class="form-control" name="email" placeholder="Email"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Instagram Handle</label>
<input type="text" class="form-control" name="instagram" placeholder="Instagram Handle"/>
</li>
</div>
<li>
<label>Cover Letter</label>
<p>Please write your message in the space below, or attach a file (-list of file types accepted-)</p>
<textarea cols="30" rows="50" name="message" class="textarea"></textarea>
</li>
<li>
<div class="upload-cover-letter">
<i class="fa fa-paperclip" style="cursor:pointer;font-size:20px;"></i>
<input type="file" name="file" id="myFileDocument" class="inputfile inputfile-1"/>
<label for="myFileDocument" id="myFileDoc"><span>Choose File</span></label>
<span style="font-size: 12px">No File Chosen</span>
<span class='hidden_text' style="font-size: 12px">Upload File (Max 2MB)</span>
</div>
<input type="hidden" id="myFileName" name="file_name" />
</li>
</ul>
<div class="btn-center">
<button type="button" class="btn btn-gradient waves-effect" id="create_campaign">Apply Now</button>
</div>
</form>
Route in web.php
Route::post('/apply/brand/{brand_id}', 'ApplicationController#apply_store');
Store application in database
public function apply_store(Request $request)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $request->get('brand_id'),
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// TODO: add helper message to confirm application did return
return redirect('/apply');
}
In your controoler metohd apply_store, you need to put the variable that will receive the variable sended by url parameter.
public function apply_store(Request $request, $brand_id){}
I typically work with compact or with to send the param to the blade view. So:
return view('new-design.pages.profile_brand', compact('brand'));
or without compact:
return view('new-design.pages.profile_brand')->with('brand', $brand)
I haven't seen the withVar that you are attempting above (doesn't mean it doesn't exist though). Try with compact and dump $brand on the view to make sure its coming through with data (not undefined). If that dumps successfully, but still fails, you may want to try adding the variable outside the quotes or totally within the blade {{}} in the form like:
<form id="application_form" method="post" action={{ "/apply/brand/".$brand-> id }} enctype="multipart/form-data">
Not sure about how the action is getting though like you have in your code above, though - you might wish to use the url() method:
<form id="application_form" method="post" action={{ url("/apply/brand/".$brand-> id) }} enctype="multipart/form-data">
change your method like this
public function apply_store(Request $request,$brand_id)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $rbrand_id,
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// Ngentod lah kalian semua, anjeng
return redirect('/apply');
}

How could i add attribute in database with different languages

/*controller_ problem is that always add the some attribute for the different languages */
`
if ($request->isMethod('POST') && null !== ($request->request->get('ajouter')))` {
$pack = new Packs();
$pack->setPackPrice($request->request->get('pack_price'));
$pack->setDataCreated(new \DateTime('now'));
$pack->setDataStatus($request->request->get('data_status'));
foreach ($listLanguages as $language) {
$packLanguage = new Packs2lng();
$packLanguage->setLanguage($language);
$packLanguage->setPack($pack);
$packLanguage->setPack2lngWording($request->request->get('pack_2lng_wording'));
$packLanguage->setPack2lngDescription($request->request->get('pack_2lng_description'));
$em->persist($packLanguage);
}
//view_ I think that my input request must be variable
{% for i in listLanguages %}
<div class="form-group">
<label class="control-label col-md-3">Titre </label>
<div class="col-md-4">
<input type="text" name="pack_2lng_wording" data-required="1" class="form-control" value="{% if packLanguage.pack2lngWording is defined%}{{packLanguage.pack2lngWording}} {%endif%}"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Description </label>
<textarea cols="60" rows="5" class="span4" name="pack_2lng_description">
{% if packLanguage.pack2lngDescription is defined%}{{packLanguage.pack2lngDescription}} {%endif%}</textarea>
</div>
{%endfor%}
Let's say the users enters a French and English translation. With your current view, the post request would be this:
pack_2lng_wording=foo_FR
pack_2lng_description=bar_FR
pack_2lng_wording=foo_EN
pack_2lng_description=bar_EN
That won't work, because the first pack_2lng_wording would be overridden by the second.
To prevent it, you have to add [] to your name attribute of an input:
<input type="text" name="pack_2lng_wording[]" />
Or add {{ i.code }} to get a associative array (assuming that each Language has a language code, i.e. a ISO 639-1 code) :
<input type="text" name="pack_2lng_wording['{{ i.code }}']" />
That would lead to this post request:
pack_2lng_wording[FR]=foo_FR
pack_2lng_wording[EN]=foo_EN
pack_2lng_description[FR]=bar_FR
pack_2lng_description[EN]=bar_EN
In your controller you have to add [$language]:
foreach ($listLanguages as $language) {
$packLanguage = new Packs2lng();
$packLanguage->setLanguage($language);
$packLanguage->setPack($pack);
$packLanguage->setPack2lngWording($request->request->get('pack_2lng_wording')[$language->getCode()]);
$packLanguage->setPack2lngDescription($request->request->get('pack_2lng_description')[$language->getCode()]);
}
BTW: I would highly recommend to use Symfony Forms. You are now reinventing the wheel. That's OK if you want to learn, but it will make your life easier (and your application) better if you are using components that are well documented, well maintained, etc.

Categories