DominikN.
DominikN.

Reputation: 1255

How to use Laravel blade custom function with the use view-passed variables

Inside a partial for creating and editing form I had this to decide whether to display the current value (when editing) or an old value (when editing or creating and not passing the validator)

<input type="text" name="title" value="{{ old('title')?old('title'):$model->title }}">

This became a pain, so I created a custom blade function in app/helpers.php

function decide($inputName, $model){
    return old($inputName)?old($inputName):$model->$inputName;
}

This works well however, what I want to achieve is ultimately this

<input type="text" name="title" value="{{ decide('title') }}">

Without the need to pass in $model

Upvotes: 3

Views: 2227

Answers (2)

Prince Lionel N&#39;zi
Prince Lionel N&#39;zi

Reputation: 2588

You can use Extending Blade, which allows you to create your own custom blade function.

Read documentation here

Upvotes: 2

user320487
user320487

Reputation:

You can pass a default to old.

old('title', $model->title)

A null old value for title will use the default, no need for the ternary.

I don't know how you'd make the association without the model, however.

Upvotes: 2

Related Questions