lsblsb
168
4
Laravel

Use MessageBag in custom classes to retrieve information about method results

Posted 1 year ago by lsblsb

Since i can't provide an URL for a contribution at laracasts, i want to share this here:

If you want to use a MessageBag in your custom class, just implement the MessageProvider interface and therefore the getMessageBag method.

If a method of your class returns false, you can get the MessageBag of the CustomClass and e.g. merge it with the MessageBag of a Validator in a Controller by using the MessageBag::merge() method.

namespace App\MyApp;
use Illuminate\Contracts\Support\MessageProvider;

class CustomClass implements MessageProvider
{
    protected messages = null;

    public function getMessageBag()
    {
        $this->messages = $this->messages ?: new MessageBag;
        
        return $this->messages;
    }

    public function customFunctionWithBooleanResult()
    {
        $result = true;
        $false1 = ...
        $false2 = ...

        [...]

        if($false1)
        {
            $result = false;
            $this->getMessageBag()->add(__FUNCTION__, 'Function returned false, because of false1');
        }
        elseif($false2)
        {
            $result = false;
            $this->getMessageBag()->add(__FUNCTION__, 'Function returned false, because of false2');
        }

        return $result;
    }
}

Please sign in or create an account to participate in this conversation.