Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value must be of type Laravel 10

Tags:

laravel

I am working on a Laravel 10 project and trying to create a controller that displays records. However, I have run into a problem while attempting to do so :

App\Http\Controllers\StudentController::index(): Return value must be of type Illuminate\Http\Response, Illuminate\View\View returned

I have attached below what I have tried so far:

Student Controller

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\Student;

class StudentController extends Controller
{

    public function index(): Response
    {
        $students = Student::all();
        return view ('students.index')->with('students', $students);
    }

If I remove the Response class, the code works, but I need to implement the Laravel 10 standard. I am unsure how to solve this issue. Can you please provide a solution?

Routes

Route::resource("/student", StudentController::class);
like image 852
Gowry Kanth Avatar asked Oct 25 '25 16:10

Gowry Kanth


1 Answers

Laravel utilized all of the type-hinting features available in PHP at the time. However, many new features have been added to PHP in the subsequent years, including additional primitive type-hints, return types, and union types.

Release notes.

If you are using view function, you need to use the Illuminate\View\View class for type-hinting.

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use App\Models\Student;

class StudentController extends Controller
{
    public function index(): View
    {
        $students = Student::all();

        return view('students.index')
            ->with('students', $students);
    }
}
like image 103
Wahyu Kristianto Avatar answered Oct 28 '25 03:10

Wahyu Kristianto