Fixing Laravel 10 return type error in Controller
1 min read

Fixing Laravel 10 return type error in Controller

How to fix return type mismatch issue in Laravel 10

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 App\Http\Controllers;
 
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
 
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 Illuminate\Http\Response, Illuminate\View\View returned

The fix is 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 could also use response()->view(...), Response::view  or update the default return type to Response | View