Laravel having trouble sending decimals - laravel

I have a blade template form that takes a price
{!!Form::open(array('method'=>'POST','route'=>array('order.store'))) !!}
<div class="form-group">
{!! Form::label('price', 'Price:', ['class' => 'control-label']) !!}
{!! Form::number('price', null, ['class' => 'form-control']) !!}
</div>
{!! Form::submit('Submit Order', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
The controller takes price and send it to email:
class OrderController extends Controller
{
public function store()
{
$data=Input::all();
//Validation rules
$rules = array (
'price' => 'required|regex:/[\d]{2}.[\d]{2}/',
);
$validator = Validator::make ($data, $rules);
//If everything is correct than run passes.
if ($validator -> passes()){
//Send email using Laravel send function
Mail::send('emails.order_received', $data, function($msg) use ($data)
{
//email 'From' field: Get users email add and name
$msg->from($data['email'] , $data['owner']);
//email 'To' field: change this to emails that you want to be notified.
$msg->to('on#dx.com', 'Rn')->subject('New Order');
});
return Redirect::route('order.index')->with('flash_notice', 'Thank you');
}
else
{
//return contact form with errors
return Redirect::route('order.index')->withErrors($validator)->with('flash_error', 'This is not how one shops');
}
}
}
The table is passed to a email template.
<?php
//get the first name
$item = Input::get('item');
$manufacturer = Input::get ('manufacturer');
$price = Input::get('price');
$quantity = Input::get ('quantity');
$product_code = Input::get ('product_code');
$owner = Input::get ('owner');
$email = Input::get("email");
$created_at = Input::get("date");
?>
When ever I try to add a price i.e. (3.65) the blade form continues to return an error message for an integer. My migration takes price as a decimal(2,2) I can't understand why my form is throwing errors. Any help would be much appreciated.
P.S. Other than the regex rule I have tried float and decimal. Now if I try entering 2 instead of 02.00 with the regex rule it throws an error based on the regex. However if I try adhering to the regex rule it wants an integer (error says between X and Y).
Thanks
M

First, you'll definitely want to use the numeric rule for your validation.
Secondly, you are using the HTML5 input field number which by default only accepts integers, not floats.
If you want it to also accept floats and therefore not trigger the browser built in validation change your code to the following:
{!! Form::number('price', null, ['class' => 'form-control', 'step' => 'any']) !!}
Or, of course, you could just use an text input and do the inline validation yourself.

Related

Laravel Collective drop-down to mysql in Laravel 5.8

I get the error:
SQLSTATE[01000]: Warning: 1265 Data truncated for column 'level'..
My guess is that Form::select should be used somehow differently, how?
// in my migration:
$table->enum('level', ['easy', 'hard']);
// in my controller Store function:
$tablee = new Tablee; // this is view file called Tablee.php
$tablee->level = $request->input('level');
$tablee->save();
// and part of my code in create.blade.php
<div class="form-group">
{{Form::label('level', 'Please choose level')}}
{{Form::select('level', ['easy' => 'easy', 'hard' => 'hard'], ['class' => 'form-control'])}}
</div>
The third argument of Form::select is the selected element.
public function select($name, $list = [], $selected = null, $options = [])
So you should change yours to be
{{ Form::select('level', ['easy' => 'easy', 'hard' => 'hard'], null, ['class' => 'form-control']) }}

selected value tag of Form::model doesn't bind property from Model

I'm learning Laravel and have an issue when trying to bind a property of the Model to selected values of the select tag. I tried to leave the 3rd parameter null because I believe Form Model Binding will automatically take care of it but it doesn't work. Here is what I already tried:
{{$article->tag_list}} // show [1,3]
//it doesn't work
{!! Form::select('tag_list[]', $tags, null , ['class' => 'form-control', 'multiple'] ) !!}
-------------
//it doesn't work as well
{!! Form::select('tag_list[]', $tags, $article->tag_list , ['class' => 'form-control', 'multiple'] ) !!}
-----------
//it works
{!! Form::select('tag_list[]', $tags, [1,3] , ['class' => 'form-control', 'multiple'] ) !!}
In the model I have the getTagListAttribute() which works fine.
public function getTagListAttribute(){
return $this->tags->lists('id');
}
With Text Input, the form works fine. Btw, I'm using 5.2.1 version. What am I missing here ?
I found the missing piece. the select function expects an array but getTagListAttribute() return an Collection object.
public function getTagListAttribute(){
return $this->tags->lists('id')->all();
}
or I can do this
public function getTagListAttribute(){
return $this->tags->lists('id')->toArray();
}

Laravel changing function/text of a button depending on value

I'm using Laravel 5 and I have a button "Enable" that once pressed sets a flag in the DB to 1. This all works fine with my code below:
Blade view
{!! Form::open(['url' => '/cms/user/' . $user->id . '/flag', 'method' => 'PUT']) !!}
{!! Form::hidden('flagged', !$user->flagged) !!}
{!! Form::submit('Flag', ['class' => 'btn btn-success'])!!}
{!! Form::close() !!}
Controller
/**
* Update the specified resource in storage.
*
* #Middleware({"auth"})
*
* #param int $id
* #Put ("cms/user/{user}/flag",as="cms.users.update.flag")
* #return Response
*/
public function updateflag($id)
{
$user = User::find($id);
//dd(Input::get('flagged'));
$user->flagged = Input::get('flagged');
$user->save();
Session::flash('message', 'Successfully flagged idea!');
return redirect()->route('cms.users.index');
}
Now what I'm trying to work out is changing the button once the user flags it. I.e.: The first time the button should say "Enable" (DB value is 0). Then I press the button and it updates the flag in the DB to 1 (which works fine).
But now, after the button is pressed, how do I change the button text to "Disable" so I can then disable the user on pressing the button. Kind of like an on/off switch that I can enable/disable the user but updating the button text and function based on what the flagged value is in the DB.
Pass a boolean variable to the view (apparently you already have a variable that contains this information):
return redirect()->route('cms.users.index')->with(['flag' => $flag]);
Then in view make an if/else:
#if($flag)
{!! Form::submit('Enable', ['class' => 'btn btn-success', 'disabled' => 'disabled']) !!}
#else
{!! Form::submit('Enable', ['class' => 'btn btn-success']) !!}
#endif

Laravel date format in submission form (d-M-Y)

In the submit form in the blade template I have the following date form and it works fine with default date like Y-m-d.
But I want to show the date like d-M-Y, I have tried to find a usable solution with out luck
Here is the code that works with default date:
Here is the model
public static $rules = [
'birthday' => 'date'
];
protected $fillable = ['birthday'];
Here is the Controller method
public function update($id)
{
$kid = Kid::findOrFail($id);
$validator = Validator::make($data = Input::all(), Kid::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$kid->update($data);
return Redirect::to('kids/list');
}
Here is the Blade template
{{ Form::model($kid, ['method' => 'PATCH', 'route' => ['kids.update', $kid->id], 'files' => true], ['class' => 'form-horizontal']) }}
{{ Form::text('birthday', null, ['class' => 'form-control']) }}
{{ Form::submit('Confirm update', ['class' => 'btn btn-primary']) }}
{{ Form::close() }}
UPDATE
This works for all Laravel versions from 4.2 and newer.
For Laravel 5.1 and newer, you will need to install it as a separate package as it's no longer part of the Laravel 5 core.
It was decided that the html/form builder are not a core requirement for the framework so it was removed from the core. The package I linked to is the one that was included with the L4 core and is being maintained as a separate package for L5 compatibility and usage, so you're safe using that if you choose to do so.
Thanks to #Bogdan for this update.
If you need one date format for db storage and another for the user interaction, you need to process it before you display it and before you store it into the database. So you should do something like this:
1. Convert the date value for your form input:
{{ Form::text('birthday', date('d-M-Y', strtotime($kid->birthday)), ['class' => 'form-control']) }}
2. Before saving convert it to the database required format:
public function update($id)
{
$kid = Kid::findOrFail($id);
// Convert birthday format to be compatible with database ISO 8601 format
$data = Input::all();
$data['birthday'] = date('Y-m-d', strtotime($data['birthday']));
$validator = Validator::make($data, Kid::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$kid->update($data);
return Redirect::to('kids/list');
}
If you want a more object oriented way of handling dates you can use Carbon which is already included by Laravel.

check if value already exists in db

I have an insert form and a dropdownbox which displays all cars names and when selected one it saves the id in column "car_id" which is unique. What I want is to check if this id already exists and if yes to display a validation message:
create controller
public function create() {
$cars = DB::table('cars')->orderBy('Description', 'asc')->distinct()->lists('Description', 'id');
return View::make('pages.insur_docs_create', array(
'cars' => $cars
));
}
insur_docs_blade.php
<div class="form-group">
{{ Form::label('car', 'Car', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('car', $cars, Input::old('class'), array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid car',
'class' => 'form-control'))
}}
</div>
</div>
You can use Laravel's Validator class for this. These are a few snippits of how it works. This methods works by using your data model. Instead of writing everything out I added a few links that provide you all the information to complete your validation.
$data = Input::all();
$rules = array(
'car_id' => 'unique'
);
$validator = Validator::make($data, $rules);
if ($validator->passes()) {
return 'Data was saved.';
}
http://laravelbook.com/laravel-input-validation
http://laravel.com/docs/validation
http://daylerees.com/codebright/validation
You can use Laravel's "exists" method like this:
if (User::where('email', $email)->exists()) {
// that email already exists in the users table
}

Resources