Search code examples
phptype-hintinglaravel-5.7php-7.1laravel-controller

Php 7.1 Return Type-hint failing in Laravel 5.7


I just cloned a repository for a project I was working on. Don't quite remember the specifics of the previous machine it was running on but on this one it's using php 7.1 and I upgraded to Laravel 5.7. The issue is that in my previous machine, this piece of code was working:

class ProductsController extends Controller
{
    public function index() : Object
    {
        $products = Product::all();
        return view('products.index', ['products' => $products]);
    }
}

Notice the Object return type.

After running migrations and everything else, when accessing index I'm getting the following error in the new machine:

Return value of App\Http\Controllers\ProductsController::index() must be an instance of App\Http\Controllers\Object, instance of Illuminate\View\View returned

which is related to the return type hint being Object. How do I know that? Because if I remove it everything works like charm.

Why is that happening?


Solution

  • So, for any one interested, I've got the answer from a different forum:

    Simply import the class first:

    use Illuminate\View\View;
    

    and then use it as return type:

    /**
     * @return View
     */
    public function index(): View
    {
        $products = Product::all();
    
        return view('products.index', ['products' => $products]);
    }