Laravel 10 added support for types and it’s great. In some cases, you might see errors if the defined types and actual return types do not match.
When you create a new Controller using php artisan make:controller IndexController
, you get this default stub.
<?php
namespace AppHttpControllers;
use IlluminateHttpRedirectResponse;
use IlluminateHttpRequest;
use IlluminateHttpResponse;
class IndexController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(): Response
{
//
}
/**
* Display the specified resource.
*/
public function show(): Response
{
//
}
// ...
}
In this case, if you try to return a view inside of either index or show methods using the view
helper, you will see an error.
TypeError:
Return value is expected to be IlluminateHttpResponse, IlluminateViewView returned
The fix is to update the return type of the method from Response
to View
from the IlluminateViewView namespace.
use IlluminateViewView;
public function index(): View
{
//
}
Alternatively, you could also use response()->view(...)
, Response::view
or update the default return type to Response | View