DEV Community

JohnDivam
JohnDivam

Posted on

Laravel function to replace vars in text

#conversation is your model example.
$body = $conversation->replaceTextVars($body, ['user' => $user]);

#in App\Models\Conversation 
public static function replaceTextVars($text, $data = [], $escape = false)
    {
        // Available variables to insert.
        $vars = [];

        if (!empty($data['conversation'])) {
            $vars['{%subject%}'] = $data['conversation']->subject;
            $vars['{%conversation.number%}'] = $data['conversation']->number;
            $vars['{%customer.email%}'] = $data['conversation']->customer_email;
        }
        if (!empty($data['mailbox'])) {
            $vars['{%mailbox.email%}'] = $data['mailbox']->email;
            $vars['{%mailbox.name%}'] = $data['mailbox']->name;
        }
        if (!empty($data['customer'])) {
            $vars['{%customer.lastName%}'] = $data['customer']->last_name;
            $vars['{%customer.company%}'] = $data['customer']->company;
        }
        if (!empty($data['user'])) {
            $vars['{%user.phone%}'] = $data['user']->phone;
            $vars['{%user.email%}'] = $data['user']->email;
            $vars['{%user.jobTitle%}'] = $data['user']->job_title;
            $vars['{%user.lastName%}'] = $data['user']->last_name;
        }

        if ($escape) {
            foreach ($vars as $i => $var) {
                $vars[$i] = htmlspecialchars($var ?? '');
                $vars[$i] = nl2br($vars[$i]);
            }
        } else {
            foreach ($vars as $i => $var) {
                $vars[$i] = nl2br($var ?? '');
            }
        }

        return strtr($text, $vars);
    }
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay