0
votes

I make controller by using php artisan make:controller newsController --resource

And after that when I go to my controller in function index, I want to add Request $request

public function index(Request $request)
{   

}

It's return error:

Declaration of App\Http\Controllers\Admin\NewsController::index(Illuminate\Http\Request $request) should be compatible with App\Http\Controllers\Controller::index()

How to fix it? I try many way but it still didn't work!

EDITController

namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

UPDATEDRoutes

Route::post('admin/news', 'Admin\NewsController@store');
Route::resource('admin/news', 'Admin\NewsController');
4
Make sure you have "use Illuminate\Http\Request;" as namespace - ankit patel
@ankitpatel I updated my question and already add it - test1321
can you please share your route file? - ankit patel
updated I@ankitpatel - test1321
did you run the command "composer dump-autoload" ? - ankit patel

4 Answers

3
votes

It's quite simple, just create your Resource controller without the index route Or Create new get route, like this:

Route::resource('admin/news', 'Admin\NewsController', ['except' => ['index']]);

Then add your route before the resource declaration, something like this:

Route::post('admin/news', 'Admin\NewsController@index');

Route::resource('admin/news', 'Admin\NewsController', ['except' => ['index']]);

Hope this helps you!!

3
votes

This doesn't require any Laravel work arounds.

Fix:

a) Remove the index method from the base controller

or

b) Make the index method in the base controller take a Illuminate\Http\Request as an argument and use that same method signature in every controller's index method that inherited from the base in the entire application.

or

c) Figure out why there is an index method defined in the base in the first place and, if needed, move it to a trait to use in child classes instead. (allows you to override the method completely)

b is not a good option, it is just to illustrate a point

Issue demonstrated:

class Foo
{
    public function index()
    {
        //
    }
}

class Bar extends Foo
{
    public function index(\Illuminate\Http\Request $request)
    {

    }
}

Declaration of Bar::index(Illuminate\Http\Request $request) should be compatible with Foo::index()

1
votes

You want to override the index action.

You also want to pass parameters into this index action.

The App\Http\Controllers\Controller::index() does not take parameters.

So they are not "compatible".

Try this "helper-funtion" way:

public function index() {

$request = request() // use the helper function

// ...you code here...
}
0
votes

You can disable index from resources and define route with different method name before or after resource:

    Route::get('resources', 'ResourceController@getResources');
    Route::resource('resources', 'ResourceController', $restResource)->except(['index']);