1

Is there any utility function in Laravel that allows you to give an alternative value for a specific input field if the old value is empty? Currently I have the following code:

<input type="text" class="form-control" id="title" name="title" value="{{ (!empty(Input::old('title'))) ? Input::old('title') : 'hey' }}">

But its not really that pretty. Any ideas?

2 Answers 2

10

use

Input::old('title', 'fallback value')
Sign up to request clarification or add additional context in comments.

Comments

0

Yes! Don't use the input tag :)

If you use {{ Form you will get this, and much, much more!

{{ Form::text('email', null, array('class'=>'form-control', 'placeholder'=>'Email Address')) }}

Check out the docs here (http://laravel.com/docs/html & http://laravel.com/docs/requests) and you will notice that when the input is flashed to the session, this input box rendered by blade will automatically replace that "null" (the second parameter) with the flashed value from the session.

This removes the need to check for the old input or have any nasty if/else checks inside your template. Also, you no longer need to worry about any HTML code injections or XSS happening, because Form::text will ensure that the text is correctly converted to their HTML entities.


Where you are checking for errors, you should use a Laravel validator. Something similar to this:

protected function createUser(){

$rules = array(
    'email'=>'required|email',
    'password'=>'required|min:6|confirmed',
    'password_confirmation'=>'required'
);

$validator = Validator::make(Input::all(), $rules);

if (! $validator->passes()) {
    Input::flashExcept('password', 'password_confirmation');
    return Redirect::to('my_form');
} else {
    // do stuff with the form, it's all good
}

return Redirect::intended('/complete');
}

Additionally, in your template, you can show all of the errors from the form:

<ul>
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
</ul>

Or just select the first error and show it under the {{ Form::text

@if ($errors->has('first_name'))
       <span class="error">{{$errors->first('first_name')}}</span>
@endif

Laravel has all of this built in, and you get it for free! Using Requests, Validators, Blade/HTML

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.