what is laravel render() method for?

Render(), when applied to a view, will generate the corresponding raw html and store the result in a variable.

Typical reasons for which I use render are:

When converting pages to pdf (ex. using dompdf, pass this into loadhtml()), returning HTML content to ajax calls


You can get php blade file with passing dynamic value in a string form

Like this

Blade

 <link rel="apple-touch-icon" sizes="60x60" href="{{$url}}/assets/images/favicon/apple-icon-60x60.png">

Controller

$html = view('User::html-file',['url'=>'https://stackoverflow.com'])->render();

O/P

<link rel="apple-touch-icon" sizes="60x60" href="https://stackoverflow.com/assets/images/favicon/apple-icon-60x60.png">\r\n

Given that you've tagged the question with Blade, I'll assume you mean render inside Laravel's View class.

Illuminate\View\View::render() returns the string contents of the view. It is also used inside the class' __toString() method which allows you to echo a View object.

// example.blade.php
Hello, World!

// SomeController.php
$view = view('example');
echo $view->render(); // Hello, World!
echo $view;  // Hello, World!

Laravel typically handles this for you, I.e. calls render or uses the object as a string when necessary.

Blade's @include('viewname') directive will load the view file and call the render method behind the scenes for example.

You may use it yourself when you want to get the compiled view to perform some subsequent action. Occasionally I have called render explicitly rather than to string if the view itself is causing an exception and in PHP explains

Fatal error: Method a::__toString() must not throw an exception in /index.php on line 12

Calling render() in the above case gives a more useful error message.

Tags:

Php

Laravel

Blade