How to save JavaScript generate value into mysql? [Laravel] - laravel

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']));

Related

Laravel not detecting multiple file uploads

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',

Backpack for Laravel - Upload CSV and Store as JSON in Database

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.

how to fetch multiple image which are saved in one cell of database table in laravel

**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.

Convert Laravel validation rules to html form fields

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.

Laravel 4 - Showing edit form with OLD data input as well as DB information

Im making a edit form for my app and i was wondering if someone could tell me how to get the data from the database into my text field.
I can locate the record i need to edit based on the users click, and i can display the information if i do the following:
value="{{ $letter->subject }}"
BUT, the problem im having is that when i run it through the validation and there is an error, it comes back with the database information instead of the OLD data.
So my questions is. Is there a way to serve up the database information first and then when it goes through the validatior, validate the information the user has edited?
Currently to validate the text field and bring the data back incase of error, im using
Input::old('subject')
Is there a parameter for that old bit that allows me to put in the DB data?
Cheers,
Hey you could validate and return ->withInput() and then in your actual form, check if there is Input::old() and display it, otherwise display from the db.
example:
<input type="text" name="subject"
value="{{ (Input::old('subject')) ? Input::old('subject') : $letter->subject }}">
Or you could go the other way and define the variable and do a regular if statement, instead of the ternary one! Up to you to decide what you want to use!
All you need is form model binding http://laravel.com/docs/html#form-model-binding:
{{ Form::model($letter, ['route' => ['letters.update', $letter->id], 'method' => 'put']) }}
// your fields like:
{{ Form::text('someName', null, ['class' => 'someHTMLclass' ...]) }}
// no default values like Input::old or $letter->something!
{{ Form::close() }}
This way you form will be populated by the $letter data (passed from the controller for example).
Now, if you have on your countroller:
// in case of invalid data
return Redirect::back()->withInput();
then on the redirect your form will be repopulated with input values first, not the original model data.
Make it more simple and clean
<input type="text" name="subject" value="{{ (Input::old('subject')) ?: $letter->subject }}">
I'm not sure for Laravel 4 but in Laravel 5, function old takes second param, default value if no old data in session.
Please check this answer Best practice to show old value

Resources