laravellaravelcollectivelaravel-8

Laravel 8 with laravelcollective/html 6.2, Action Controller@function not defined


I am new to Laravel and Stackoverflow

When Laravel7 is released, I started to learn Laravel. The new version 8.0 was introduced not long ago and I started to try it.

I cannot define that the problem is caused by a newer version of Laravelor any misconfiguration.

When I try the following (edit.blade.php)

{!! Form::open(['action' => ['ProductController@update', $product->id], 'method' => 'POST']) !!}

or

{!! Form::open(['action' => [[ProductController::class, 'update'], $product->id], 'method' => 'POST']) !!}

an error occurred

Action ProductController@update not defined

then I tried to replace the controller name with a path like

{!! Form::open(['action' => ['App\Http\Controllers\ProductController@update', $product->id], 'method' => 'POST']) !!}

or

{!! Form::open(['action' => [[App\Http\Controllers\ProductController::class, 'update'], $product->id], 'method' => 'POST']) !!}

It works!

so I think this is about namespace

but I have a namespace heading namespace App\Http\Controllers; in my App\Http\ProductController.php

although I can solve the problem by typing the full path of the controller in the collective form, I am worried that my code has configuration error or syntax errors, etc.


Solution

  • This is a change to Laravel 8. There is no namespace prefix applied to your routes by default and there is no namespace prefix used when generating URLs to "actions".

    To have the namespace prefixed to the Controller you are trying to reference when generating URLs to actions you would need to define the $namespace property on your App\Providers\RouteServiceProvider:

    protected $namespace = 'App\Http\Controllers';
    

    Now you can reference your action with that namespace prefix:

    Form::open(['action' => ['ProductController@update', $product->id], 'method' => 'POST'])