Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yankeekid's avatar

Using the old() function within custom blade directive

In order to avoid duplicating logic within my form views, I decided to take advantage of Blade's custom directives and create a directive to clean up my views a bit.

So rather than this:

{{ in_array( 'Miami', old('city) ) ? 'selected' : '' }}

on every select option, I can just say:

@selected('Miami', old('city'))

However, when using this new directive, I'm consistently getting an error:

Too few arguments to function Providers\{closure}(), 1 passed and exactly 2 expected

In attempting to diagnose this issue, I realized that the old() function is sending a null value for old('city'), even though it SHOULD contain an array of values.

I'm not sure why this is happening, however, I have some ideas as to why it might.

Has anybody else run into this issue? And if this can't be done, what would be the best way to avoid having to duplicate this logic on forms without using a custom directive?

Thanks!

0 likes
4 replies
gitwithravish's avatar
Level 16

@yankeekid old() fetch data from session. So it will only work if you are redirecting back from controller. Make sure you are redirecting back and not calling view().

If this still does not solve your problem, share your controller code and explain when exactly you are expecting this to work.

1 like
Snapey's avatar

you can pass a fallback value into old() the first parameter is the data flashed to the session, the second is the default

try

@selected('Miami', old('city',[]))

custom blade directives are very rarely worth the effort (because the effort is considerable). Better with Laravel7+ to use components

MichalOravec's avatar

If you have it like this then you don't have any duplications. So I think your blade directive is not necessary.

<select name="cities[]" multiple>
    @foreach ($cities as $city)
        <option value="{{ $city }}" {{ in_array($city, old('cities')) ? 'selected' : '' }}>
            {{ $city }}
        </option>
    @endforeach
</select>
yankeekid's avatar

Thanks! I think that this is the issue. I'm using this on a search form that uses the GET method, so there is no redirect. I am, however, grabbing the $request data and flashing it to the session so that I can use the old() helper, but apparently it isn't being flashed to the session until AFTER the boot method has run.

Please or to participate in this conversation.