2
votes

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

use Laravel\Octane\Facades\Octane;
use Symfony\Component\HttpFoundation\Response;

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 !

1
Is there something wrong with return view(...)?miken32
Yes I had a 404 on the home page and I tried with another URL and I have this error : TypeError: Laravel\Octane\Octane::invokeRoute(): Return value must be of type Symfony\Component\HttpFoundation\Response So not possible to return a view :( I tried return Response::view(), but doesnt works.user2916349
Then I would suggest returning a RedirectResponse to another route that can then send the view. (To be clear, I have no idea what Octane is, just making suggestions based on my Laravel experience.)miken32

1 Answers

2
votes

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 Illuminate\Http\Response, which extends from the Symfony response class.

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

// Using the Router class
return Illuminate\Routing\Router::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 Illuminate\Http\Response;

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 Symfony\Component\HttpFoundation\Response;

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.