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

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.

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

Laravel having trouble sending decimals

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.

Update / post database colum in Laravel

I have a general question.
I have a search form in larvel which returns results form the database.
in these i have an input field to enter a price if price is == 0
what my problem is when i enter price and submit it returns to the search page without my previous search results i.e it doesn't refresh the same page with results and the newly updated field etc.
form in view
{{ Form::open(['action' => 'price_input'])->with($gyms) }}
{{ Form::text('enter_price', null, ['class' => 'form-control', 'size' => '50', 'id' => 'enter_price', 'autocomplete' => 'on', 'runat' => 'server', 'required' => 'required', 'placeholder' => 'enter price!', 'style' => 'margin-bottom: 0px!important;']) }}
{{ Form::submit('Search', ['class' => 'btn btn- primary', 'style' => 'margin-left: 10px;']) }}
{{ Form::close() }}
route
Route::post('/', [ //not used yet
'as' => 'price_input',
'uses' => 'PagesController#priceUpdate'
]);
Model
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
return Redirect::back()->withInput();
}
Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gym);
}
not bothering with model as that works fine.
any ideas guys?
Thanks for your answer,
i have changed my controller to this
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
but when i run it i get
Missing argument 1 for PagesController::priceUpdate()
with the $gyms being passed into the method.
if i take out the $gyms that goes away but not sure if its still being passed with session or not, sorry im a novice.
orignally i had a search box which when run returns
return View::make('pages.home')->with($data);
what is the difference between that and
return View::make('pages.home')->with($data);
when i do the above line it returns to the search page with no search options from before update the form, any ideas?
Currently, you are just retrieving an existing session and doing nothing with it. You need to do:
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
Or
return Redirect::to('pages.home')->with('gyms', Session::get('gyms'));
Then you can access the gyms in the view with $gyms.
Alternatively, you could access Session::get('gyms') in the view as well.
Also, not sure if it's just the way you pasted it here, but you have an unnecessary space before the ->with. Just wanted to make sure that's not part of the issue, too!

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
}

Get the model ID when updating a resource

I have a form that will submit a Patch request to the controller's update method.
But the update method requires to have $id, as you can see below whenever I try that I get a
No query results for model [Item]. Since the update method did not receive the $id of the model
public function update($id)
{
$item = Item::findOrFail($id);
$update = Input::all();
// some codes to save changes
return Redirect::route('items.index');
}
Another thing is that whenever I submit the form, url turns into something like this:
mw.dev/items/%7Bitems%7D
Edit
routes.php
Route::resource('items','ItemsController');
ItemController
public function edit($id)
{
$item = Item::findOrFail($id);
return View::make('items.edit')->with('item',$item);
}
I have included the code on my edit.blade.php
{{Form::open(array('route' => 'items.update', 'method'=>'patch'))}}
{{Form::text('barcode', $item->barcode, array('placeholder' => 'barcode'))}}
{{Form::text('imei',$item->imei, array('placeholder' => 'imei'))}}
{{Form::text('item_name', $item->item_name, array('placeholder' => 'item name'))}}
{{Form::submit('edit')}}
{{Form::close()}}
You have to pass the model to your view and need to pass the id parameter when generating the form. Assume that you have a User model and it's available in the view. So you may generate the form action using something like this:
// Using Form::open method with route
Form::open(array('route' => array('route.name', $user->id)))
// Using Form::model method with route
Form::model($user, array('route' => array('route.name', $user->id), 'method' => 'patch'))
// Using Form::open method with action
Form::open(array('action' => array('Controller#update', $user->id), 'method' => 'patch'))
// Using Form::open method with url
Form::open(array('url' => 'something/update/' . $user->id, 'method' => 'patch'))
Check more on Opening A Form.
The URL
mw.dev/items/%7Bitems%7D
is most likely the url-encoded form of
mw.dev/items/{items}
I suppose there is a problem in the form submission or in the <form>'s action paremeter or in the Route::* declaration in routes.php.
This could also explain why you don't get any $id upon submission.

Resources