Skip to content
Advertisement

Return a view with Laravel Octane Route

I’m trying to use Octane routing with Laravel in the routes/web.php file.

use LaravelOctaneFacadesOctane;
use SymfonyComponentHttpFoundationResponse;

Octane::route('GET', '/url', function(){
   return new Response('hello world');
});

The code above works, but how can I return a view with data. I tried many things, but nothing is working. Is it possible to return views like the Route facade with Octane ?

Thank’s for help !

Advertisement

Answer

Laravel has a lot of magic under the hood that translates views returned from a controller into a response object. More specifically, the response object is an instance of IlluminateHttpResponse, which extends from the Symfony response class.

To leverage this magic yourself, you can invoke it directly:

// Using the Router class
return IlluminateRoutingRouter::toResponse($request, $response);

// or using the facade (which points to the router class)
return Route::toResponse($request, $response);

Here’s an Octane specific example:

Octane::route('GET', '/url', function($request) {
    return Route::toResponse($request, view('...'));
});

Taking this approach would allow you to return anything you’re normally able to return (array, model, string, redirect, etc.) from a traditional route.

However, if you wanted something view specific, this would work as well:

use IlluminateHttpResponse;

Octane::route('GET', '/url', function() {
    return new Response(view('...'));
});

Laravel’s Response class knows how to convert renderables (which a view is an instance of) to a string.

The full blown Symfony specific implementation would look like this:

use SymfonyComponentHttpFoundationResponse;

Octane::route('GET', '/url', function() {
    return new Response(view('...')->render());
});

Just to reiterate, all of these options would work. Use whichever solution you’re most comfortable with.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement