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

ATR22's avatar

Convert a Closure to an array.

Hi. can you help me with that code please. I try everything, like use '(array)' or anything to make the closure output right to an array for this Filamnet method validationMessages(). My code:

protected function applyModelRules(string $name): static
    {

        $valMsg = $this->getMsgClosure($name);

        // I need do something here to convert Closure to an array.

        $this->validationMessages($valMsg);// This gives me an error that said validationMessages just accepts array, but you gave it a Closure.

        return $this;
    }


    protected function getMsgClosure(string $name)
    {
        return function (Component $component) use ($name) {
            $model = $component->getRecord() ?? $component->getModel();

            if (!$model || !in_array(HasValidationRules::class, class_uses_recursive($model))) {
                return (array) $this->evaluate('validationMessages') ?? [];
            }

            $modelInstance = is_string($model) ? app($model) : $model;

            $msg = $modelInstance->getValMessages($name);
            //dd($msg); //It shows an array correctly.
            return $msg;
        };
    }

Thank you for any help.

0 likes
2 replies
Glukinho's avatar

Maybe you should execute the closure to make it return an array, like that (note $valMsg() instead of $valMsg):

$this->validationMessages( $valMsg() );
ATR22's avatar

@Glukinho Thank you for your advice. I did this:

$this->validationMessages($valMsg($this));

and I get this error:

 Typed property Filament\Forms\Components\Component::$container must not be accessed before initialization 

it's becuse getRecord() cant work before Filamnet component rendered completly. so that why we use a Closure. and when we use a closure we can't convert it to an array for validationMessages().

So I kinda stuk in a loop here! If I use closure a dont get an array result and if I dont I get this arrer that I mentioned here.

I realy dont know what to do.

Please or to participate in this conversation.