Reputation: 873
How can I render Blade templates from the database (instead of using a blade template file)?
I've checked this Render template from blade template in database but for some reason is not replacing the variables in the template. It's giving a Notice: Undefined Variable.
Any ideas?
Thanks in advance
Upvotes: 3
Views: 2718
Reputation: 5735
For these, who stumble across this just now: In Laravel 9, it's implemented natively.
https://laravel.com/docs/9.x/blade#rendering-inline-blade-templates
use Illuminate\Support\Facades\Blade;
return Blade::render('Hello, {{ $name }}', ['name' => 'Julian Bashir']);
Upvotes: 3
Reputation: 3217
One simplest approach would be to store the content in a temp blade file and render that.
Let's say we fetch this blade string stored in the DB:
$content_from_db = "Hello {{ $user_name }} This is your message";
Process:
$filename = hash('sha1', $content_from_db);
// temp file location where this file will be uploaded
// it can easily be cleared with 'php artisan view:clear'
$file_location = storage_path('framework/views/');
// filepath with filename
$filepath = storage_path('framework/views/'.$filename.'.blade.php');
file_put_contents($filepath, $content_from_db);
// add framework location so that it won't look into resource/*
view()->addLocation($file_location);
$data = [ 'user_name' => 'John Doe' ];
$rendered_content = view($filename, $data)->render();
$rendered_content = trim(preg_replace('/\s\s+/', ' ', $rendered_content));
Upvotes: 2