How to show the old data in a form input in the Laravel

I write the form.blade.php like this:

<div class="form-group">
    <label>Start at</label>
    <div id="start_date" class="input-group date form_datetime col-md-4" data-date-format="yyyy-mm-dd hh:ii:ss">
        <input class="form-control" name="start_at" size="16" type="text" value="{{  $activity->start_at }}">
        <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
        <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
    </div>
</div>

Both Create and Edit method use the view to display the form. In the Edit method, the $activity is used and everything is normal. But in the Create method, the $activity is null, so I have a error in {{ $activity->start_at }}.

I know I can use if(!empty($activity)) to prevent this error. but I do not want to use this anywhere.

What is the better way?

Answers


You could use this,

{{ $activity->start_at or '' }}

I also like to reuse code and use the same view to create or edit an object. What I do is to pass a brand new instance of the object to the create view. This way I have the object on its initial state including defaults (if any) and I am able to prefill those defaults (if any) on the displayed form. It gives me an additional benefit: if anything goes wrong with the validation at the server level the user doesn't lose any data, I just need to do something like this in the view:

<div class="form-group">
    <label for="test_field" class="control-label">Fecha de firma</label>
         <input type="text" value="{{ ( !empty($isabi) ? $isabi->fecha_firma : old('fecha_firma')) }}" 
                name="fecha_firma" id="isabi-fechafirma" class="form-control" placeholder="Este campo es obligatorio">
</div>

This is the create method with extra functionality removed for clarity (check if the user is authenticated, linking the created object with the company the user works for and other stuff):

public function create()
{
    return view('isabis.create', [
    "isabi" => new Isabi()
    ])->with($this->data);

}

I use $this->data for view configuration. Hope this helps.


Need Your Help

.Net MVC3 resource file and multi-tenancy

asp.net-mvc localization embedded-resource multi-tenant

I have learned much and solved a lot of problems coming up with multi-tenancy.

What's the difference between app_data folder in web application and in web site?

c# asp.net .net security web

I want to ask what the difference is between the app_data folder in a web application and in a web site .