I'm trying to upload multiple images in one request with Laravel. However, it only seems to be seeing one file regardless of the fact that my file input has multiple files attached.
Markup:
<input class="file-input" type="file" name="fileUpload" multiple>
Controller:
$this->validate($request, [
'fileUpload' => 'image|nullable',
...
foreach ($request->file('fileUpload') as $image) {
dd('stop');
}
dd('fail');
In this case, it always returns "fail". However, if I try to just $request->file('fileUpload') it will return to me a single file, like so:
Like multiple selects, if you want to send multiple values then you need to use the array syntax in your input’s name attribute. So it should be fileUpload[] instead of just fileUpload
Change the name of the input fileUpload to fileUpload[] :
<input class="file-input" type="file" name="fileUpload[]" multiple />
Also in the controller for validating multiple fields, change 'fileUpload' to 'fileUpload.*' :
$this->validate($request, [
'fileUpload.*' => 'image|nullable',
Related
I made contact form in Laravel.
some of input field are just normal input field.
And rest of them are JS generate data which are 'product', 'quantity' and 'price'.
I can store ONLY normal input field data.
Here is my dd() image.
And this is my blade file.
<select id="product" name="product" onchange="caliculate()"></select>
<input id="v_product" type="hidden" name="product">
Controller
//Store data in database
Contact::create($request->all());
Could you teach me how to store product, quantity and price data into Mysql please?
If you want to exclude the other fields when getting request parameters, you can do the following:
Contact::create($request->only(['product', 'quantity', 'price']));
I have successfully configured Backpack for Laravel to handle all of the CRUD ops for my app except for one particular field. I need to import a CSV, convert it to JSON and then store the JSON in my database to later display as an HTML table.
I created a custom field in Backpack, which does in fact create a field to upload the file, but I can't figure out how to point it to a custom method to handle the logic to handle the conversion and storing of the CSV.
I have combed the documentation but I don't see any mention of anything like this. https://backpackforlaravel.com/docs/3.4/crud-fields#creating-a-custom-field-type
//Placed in the Controller CrudPanel Configuration
$this->crud->addField([
// CSV to JSON
'label' => "Specs Table",
'name' => "specifications_table",
'type' => 'csv2json', //custom field name
], 'update/create/both');
//Placed in csv2json.blade.php file
<div #include('crud::inc.field_wrapper_attributes') >
<label>{!! $field['label'] !!}</label>
<input
type="file"
name="{{ $field['name'] }}"
value="{{ old($field['name']) ? old($field['name']) : (isset($field['value']) ? $field['value'] : (isset($field['default']) ? $field['default'] : '' )) }} "
#include('crud::inc.field_attributes')
>
{{-- HINT --}}
#if (isset($field['hint']))
<p class="help-block">{!! $field['hint'] !!}</p>
#endif
</div>
If you need extra logic for a custom field type, it's always a good idea (imho) to do it inside the model, as an accessor for that particular model attribute.
Take the image field type as an example: it requires you to have a setImageAttribute() accessor, where the actual uploading and storing is done.
You could add a new method on your model:
public function setSpecificationsTableAttribute($value) {
// read $value
// convert it to JSON
// $this->attributes['specifications_table'] = $fileConvertedToJson;
}
Hope it helps.
**i took multiple image input in this way**
<div class="form-group" style="width: 100%">
<label for="inputEmail4">Images</label>
<input type="file" class="form-control" id="Image" name="Image[]" multiple="multiple" placeholder="">
</div>
i have already inserted images on database. In database each cell containing more than one image path
like this.
Now i want to fetch and display each image using laravel framework. please suggest what will be the controller code..
I would change your data structure, so it easier to store and fetch your images from your database.
You could use a json column and use Mutators to cast the images to a normal php array https://laravel.com/docs/5.7/eloquent-mutators#array-and-json-casting.
This way you can just loop through the array and display each image.
Also if you are saving the data in one field separated by colon then you can do(considering your column name is images) :
$model = ModelName::first();
$images = explode(';', $model->images); // This fives image1;image2;image3 etc
$images = array_filter(array_map('trim', $images));
// This will give you array ['image1','image2','image3'}
However, this is not a good approach as every-time you need to explode it if you want to get a usable data.
Instead, you can specify this column in protected $casts = ['images' => 'array']
Then when you do $model->images, it w ill directly give you an array of image paths instead of a single string separated by a delimiter. See documentation for more help.
Say I have a validation rules for some Model, for example validation for a person model will be:
'first_name' => ['required', 'string'],
'last_name' => ['required', 'string'],
'birthday' => ['before:today', 'date'],
'salary' => ['min:0', 'max:2000', numeric],
....
So if I wrote that rules, it feels wrong to write the same rules manually but for the HTML form fields like:
<input type="text" name="first_name" required />
<input type="text" name="last_name" required />
<input type="date" name="birthday" max="2016-06-09"/>
<input type="number" name="salary" min="0" max="2000"/>
So if the product owner ask me for change the rules like changing the mandatory fields, or even change the maximum salary from 2000 to 5000, I have to change it manually in the validation rules and the form itself.
So it makes me wonder, is there any automatic way to convert Laravel validation rules to the HTML form fields?
You have to parse your rules, then loop on the parsed datas for building a form. And then, I suggest you to use partial views for doing the trick.
I already did this for building automatic forms and documentations. So i wrote a Laravel package here : https://github.com/Ifnot/ValidationParser.
In the example of my package you just have to create two files :
A form blade view (contains the code for parsing the validation)
A field blade view (used for display a form item)
To have the validation rules be in one place, set the rules to variables. Then, pass the variables into the laravel validation page and in your blade template (html).
So, where you are setting the variable:
$MaxSalary = 2000;
Next, pass in your variable to the Laravel form validation rules:
'salary' => ['min:0', "max:$MaxSalary", numeric],
Then, pass it into your blade template form:
return view('form', ['MaxSalary' => $MaxSalary]);
Then, in your blade template, use the variable:
<input type="number" name="salary" min="0" max="{{ MaxSalary }}"/>
I had problems finding some one else thinking about this same idea. I must have not been using the right terms for the search. I implemented this same concept today 2023 in the following project: https://github.com/arielenter/ValidationRulesToInputAttributes
In it, I'm using laravel's Illuminate\Validation\ValidationRuleParser to explode and parse the rules, and later I used a 'translator' that convert applicable rules to input attributes.
My concern is why it seems nobody has made a laravel package that can do this on 2023. I'm not sure if I'm up to the task, but if nobody has done it I'll try. I just think it'll be very odd if nobody more capable has done it. The most difficult part I think would be to make an extend dictionary for every possible attribute that could be apply depending of the rule. I might end up leaving to the user to provide its own dictionary or something, but some cases are conditional so I'm not sure if that could work. For now I'll just keep adding translation every time I need it.
I know browsers only support POST and GET requests, and Laravel supports PUT requests using the following code:
<?= Form::open('/path/', 'PUT'); ?>
... form stuff ...
<?= Form::close(); ?>
This produces the following HTML
<form method="POST" action="http://example.com/home/" accept-charset="UTF-8">
<input type="hidden" name="_method" value="PUT" />
... form stuff ...
</form>
How does the framework handle this? Does it capture the POST request before deciding which route to send the request off to? Does it use ajax to send an actual PUT to the framework?
It inserts a hidden field, and that field mentions it is a PUT or DELETE request
See here:
echo Form::open('user/profile', 'PUT');
results in:
<input type="hidden" name="_method" value="PUT">
Then it looks for _method when routing in the request.php core file (look for 'spoofing' in the code) - and if it detects it - will use that value to route to the correct restful controller.
It is still using "POST" to achieve this. There is no ajax used.
Laravel uses the symfony Http Foundation which checks for this _method variable and changes the request to either PUT or DELETE based on its contents. Yes, this happens before routing takes place.
You can also use an array within your form open like so:
{{ Form::open( array('route' => array('equipment.update', $item->id ),
'role' => 'form',
'method' => 'put')) }}
Simply change the method to what you want.
While a late answer, I feel it is important to add this for anyone else who finds this and can't get their API to work.
When using Laravel's resource routes like this:
Route::resource('myRoute','MyController');
It will expect a PUT in order to call the update() method. For this to work normally (outside of a form submission), you need to make sure you pass the ContentType as x-www-form-urlencoded. This is default for forms, but making requests with cURL or using a tool like Postman will not work unless you set this.
PUT usually refers to update request.
When you open a form inside laravel blade template using,
{{ Form::open('/path/', 'PUT') }}
It would create a hidden field inside the form as follows,
<input type="hidden" name="_method" value="PUT" />
In order for you to process the PUT request inside your controller, you would need to create a method with a put prefix,
for example, putMethodName()
so if you specify,
{{ Form::open('controller/methodName/', 'PUT') }}
inside Form:open. Then you would need to create a controller method as follows,
class Controller extends BaseController {
public function putMethodName()
{
// put - usual update code logic goes here
}
}