Standard Laravel Input Value

Asked

Viewed 346 times

3

In the Laravel, I want that when a certain value does not exist in the Input, i can set a default value.

With pure PHP, it is possible to do so:

$text = isset($_POST['text']) ? $_POST['text'] : 'padrão';

In Laravel I know it’s possible to do it in a similar way, something like that:

 $text = Input::has('text') ? Input::get('text') : 'padrão';

Bearing in mind that the Laravel is an excellent frameworks with some features that decrease the continuous rewriting of codes, is there an easier way to get a parous value for an input value? Or this is the only way there is?

'Cause sometimes it gets tiring doing it:

$a = Input::has('a') ? Input::get('a') : 'Valor padrão';
$b = Input::has('b') ? Input::get('b') : 'Valor padrão';
$c = Input::has('c') ? Input::get('c') : 'Valor padrão';

2 answers

3


You can use it this way Input::get('nome_campo','valor'); in case the second parameter identifies the default value if the Input returns null.

2

Laravel includes a helper that does just that:

array_get($array, 'campo', 'valor padrão'); // null como default

The advantage is that you can do this anywhere, not necessarily only on input.

Personally, I don’t like array_get, I’m more the operator Null coalescing of PHP 7.

  • Well remembered. Thanks for the contribution, not everyone knows that the array_get function has this feature. It’s almost an Egg Easter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.