laravel form model binding - date formatting - forms

I have Laravel. I have a form. I have a MySQL database. There are some dates in it. When I bind the model and the form, the form is dutifully populated with raw MySQL dates. This is obviously not what I need.
My question is: How do I get a model bound form to display dates in a more readable way?!? There is not chance to intercept and format the data. Or maybe for a more general solution, is there any way to do some proessing on any data between the model and the form, before the user sees it?
Am I thinking of this all wrong? A billion thanks!

You may add an accessor method in your model like this:
public function getCreatedAtAttribute($date)
{
$date = new \Carbon\Carbon($date);
// Now modify and return the date
}
This will be called for created_at. Also check date-mutators if you need to override defaults. Check Carbon Docs.

You can format the date in the form using the format() method.
If you're using it in a form element:
{{ Form::text('name', $model->created_at->format('d/m/Y H:i')) }}
If you're displaying it as plain text:
{{ $model->created_at->format('d/m/Y H:i') }}
If you would like the user to be able to modify the date in a nice way, you could use three different select fields. Here's an excerpt from a project I worked on that allows the user to change the date of birth:
<div class="form-group {{ $errors->has('date_of_birth') ? 'has-error' : '' }}">
{{ Form::label('date_of_birth', 'Date of Birth', ['class' => 'control-label']) }}
<div class="form-inline">
{{ Form::selectRange('date_of_birth[day]', 1, 31, null, ['class' => 'form-control']) }}
{{ Form::selectMonth('date_of_birth[month]', null, ['class' => 'form-control']) }}
{{ Form::selectYear('date_of_birth[year]', date('Y') - 3, date('Y') - 16, null, ['class' => 'form-control']) }}
</div>
{{ $errors->first('date_of_birth', '<span class="help-block">:message</span>') }}
</div>
This is contained within a form that has the model bound to it.
Side Note
The alternative answer posted in here actually overrides the default way that laravel handles dates, and unless you actually return a carbon object, you'll never have the luxury of using the format method, or any of the other handy things that carbon has.
If you have other columns that contain dates, add them to the data mutators list:
public function getDates()
{
return ['created_at', 'updated_at', 'date_of_birth', 'some_date_column'];
}
This will now make it so that each of those is an instance of Carbon allowing you to format as you please, whenever you please and easily modify, duplicate and a whole host of other things. For more information regarding this, see: http://laravel.com/docs/eloquent#date-mutators

You can format all fields retrieved from the database with creating an Accessor in your model. For example if your database field is created_at use getCreatedAtAttribute.
public function getCreatedAtAttribute($date)
{
return Carbon::($date)->format('d/m/Y');
}

Related

Laravel 6 relation with()

I have a Posts model which has many Comments and every comment has one User model.
If I run
#foreach( $post->comments as $comment )
<div>{{ $comment->text }} <br>{ $comment->user->name }}</div>
#endforeach
it generates one query to user for every loop in comments foreach. How to write this code so the Laravel makes only one query for all users?
Controller code looks like
public function detail(Post $post)
{
return view('home.detail')->with([
'post' => $post->with('comments', 'comments.user')->get()->first()
]);
}
Thanks a lot.

Put the current value of combobox or the html select box from DB

I Have this code
{{Form::select('area_id', Area::lists('area_description','area_id') ,'',array('class' => 'form-control'))}
How do I get the current value of Select box from database. BTW I'm using Laravel with Blade Template.
You can use use something like this:
{{
Form::select(
'area_id',
Area::lists('area_description','area_id'),
old('area_id'), // or Input::old('area_id')
['class' => 'form-control']
)
}}
In this case, instead of using Area::lists('area_description','area_id') inyour template use pass it from your controller, for example (in your controller):
$area_ids = Area::lists('area_description','area_id');
return view('view_name')->with('area_ids', $area_ids);
Then use the following in your template:
{{ Form::select('area_id', $area_ids, old('area_id'), ['class' => 'form-control']) }}
For Laravel-5.1.x
The lists method now returns a Collection instance instead of a plain
array for Eloquent queries. If you would like to convert the
Collection into a plain array, use the all method:
$area_ids = Area::lists('area_description','area_id')->all();
Check the upgrade guide for details.
I Have already solved my own problem wew.
with this code:
{{Form::select('area_id', $area_ids , $person->area_id ,array('class' => 'form-control'))}}
I forgot that it should be the id or the option value not the option content. The option that I mean is the <option> tag.

How to generate input select in laravel blade form and customize its options value?

I'm trying to create a laravel form that have an input select generating from array of strings coming from controller.
How can I set values of options manually?
In controller :
public function create()
{
$eventTypes = EventType::all()->lists('title');
return View::make('events.create')->with(compact('eventTypes'));
}
In view (blade) :
{{ Form::label('eventType', 'Type') }}
{{ Form::select('eventType', $eventTypes, null, array('class'=> 'form-control')) }}
And select created as :
<select class="form-control" id="eventType" name="eventType">
<option value="0">Sport Competition</option>
<option value="1">Movie</option>
<option value="2">Concert</option>
</select>
I just want to set values manually.
The value in the options is just the key of the array. The second parameter to the lists() method will let you choose a field to use as the key:
// use the 'id' field values for the array keys
$eventTypes = EventType::lists('title', 'id');
If you want to do something more custom than that, you'll need to manually build your array with the key/value pairs you want.
Edit
As mentioned by #lukasgeiter in the comments, there is no need to call all() first.
EventType::all()->lists() will first generate a Collection of all the EventType objects. It will then call lists() on the Collection object, meaning it will loop through that Collection to build an array with your requested fields.
EventType::lists() will call lists() on the query builder object, which will just select the two requested fields and return those as the array. It will not build any EventType objects (unless you select a field built by a Model accessor).

Laravel4 Repopulate Search Form after submit

I have a get method search form with a field like this:
{{ Form::text("name", null, array('class' => 'form-control')) }}
My controller look like this:
public function index()
{
...
$result= $this->repo->search($data, $page, $perPage);
return View::make('index', compact('result'));
}
The route look like this:
Route::get('/search', 'controller#index');
and the form:
<form action="/search" id="searchForm" class="search-form">
I want to repopulate the name field to keep his value even after the search submit.
To do this I added to my controller before the view::make:
Input::flash();
I have problems with this flashing, because when I open one of my result line from the search for editing, the old input is not empty and cause false values on the form model binding of this editing page.
How can I repopulate the search form in an other way ? (No model binding possible for this search form)
Finally, I found what I was searching:
{{ Form::text("name", Input::get("name"), array('class' => 'form-control')) }}
With all the magical in Laravel, I thought there is a possibility to do this automatically, but this what I was searching.

Unlimited value for a select in form Symfony2

I want a select in my form, but the value of the select are dynamic (with ajax)
My entity:
/**
* #ORM\Column(type="string", nullable=true )
* #Assert\NotBlank()
*/
private $city;
My form:
$builder->add('city', 'choice',array('empty_value' => 'choice city', 'choices' => array() ));
But, I have:
This value is not valid..
Because the city are not in the empty array!
Since the city field is a simple string and is not related to a table, simply:
Render the field as a simple input text;
Attach to the input field the Javascript for city-autocompletion through Ajax to fill the input
Then you are ready to submit
or:
Render the field as text.
Hide it in the template
Attach a select through javascript in place of the text-input
Use that select to render the list of cities
On submit get the value from the select and put it as value of the input field.
This approach can be used also to set value for visual widgets, like a star rating.
An other solution with extend form theme:
In my form:
$builder->add('city', 'text',array('data' => 'choice city'));
And in my twig template
{% form_theme form _self %}
{% block _template_defaultbundle_membertype_city_widget %}
<select {{ block('widget_attributes') }} ><option>{{ value }}</option></select>
{% endblock %}
with "template_defaultbundle_membertype_city" is the id of the input