How to fix return type mismatch issue in Laravel 10
As part of the new releases of Laravel 10, on Feb, 13 2023, Method Signature + Return Types has been added to controllers in laravel. Laravel 10.x thoroughly updates the application skeleton and all stubs utilized by the framework to introduce argument and return types to all method signatures.
This return type In some cases, might throw errors if the defined types and actual return types do not match.
When you create a new Controller using the artisan command php artisan make:controller TestController
, you get this default stub.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class TestController extends Controller
{
public function index(): Response
{
//
}
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 Illuminate\Http\Response, Illuminate\View\View returned
To fix this, you need to update the return type of the method from Response
to View
from the Illuminate\View\View namespace.
use Illuminate\View\View;
public function index(): View
{
//
}
Alternatively, you can as well use response()->view(...)
, Response::view
or update the default return type to Response | View
Enjoy this article ? drop a comment below and add your own contribution.