Home / Snippets / How to Rendered Blade View as a String in Laravel
How to Rendered Blade View as a String in Laravel cover

How to Rendered Blade View as a String in Laravel

1.2K

3 years ago

0 comments

In this short snippet, you will learn how to render a blade view into a string from within the backend of Laravel application. This allows you to generate the HTML code in advance which you can return separately to the front end.

Laravel Controller Return View


The typical way of returning the view form controller method in Laravel look as follows.
<?php // PostController.php

public function show() {
  return view('posts.show', ['post' => Post::first()]);
}

Laravel Controller Render View Beforehand


To render the view beforehand you can call the "render()" method available from the "view()" helper method. By calling the render method you will instruct Laravel to render the code beforehand and you can store it as a variable.
<?php // PostController.php

public function show() {
  $partialView = view('partial.some-view', ['post' => Post::first()])->render();

  // do whatever you want with the code

  return view('posts.show', ['post' => Post::first(), 'partialView' => $partialView]);
}
If this tutorial is helpful do make sure to share it with your friends cheeers!
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this