EDDYMENS

Last updated 2022-09-04 08:33:17

Laravel PHP 8 Throws Error Too Few Arguments To Function | Fix

Table of contents

Laravel PHP 8 error [→]Generally, when you get this error your controller is likely expecting more arguments than you are passing to it.

However, if you got the above error after updating to PHP 8 then it's likely an issue with PHP 8s expected parameter arrangement.

Parameter arrangement in PHP 8

In PHP 8, all required parameters need to be in the first position of the method/function signature followed by optional parameters.

01: function person($name, $age=null) { 02: echo $name; 03: } 04: 05: person('eddymens');

If you happen to place optional parameters before required ones, PHP 8 will throw a deprecation error, which in itself is not a show-stopper.

01: function person($age=null, $name) { 02: echo $name; 03: } 04: 05: person('eddymens', 25);

Deprecated: Required parameter $name follows optional parameter $age in /tmp/dxhracul7n453yt/tester.php on line 3 25

Parameter placement error in Laravel

In Laravel however, you might end up with an ArgumentCountError: error instead of a deprecation message. The deprecation error is only thrown when you call on the function directly, when you use a function like call_user_func() to call on your function you end up with the ArgumentCountError: error, and laravel relies a lot on such functions to call on different parts of your code.

And this is why you end up with an error that doesn't clearly state the problem.

Fixing the error

Laravel controllers typically have the $request argument passed in as a required parameter which is then resolved using a dependency container. You are likely to hit the ArgumentCountError: if you do not have the $request argument as the first argument if you have optional parameters.

01: public function index($slug = null, $tag = null, Request $request) { 02: ... 03: } 04: ...

To fix this place the $request variable as the first parameter of the method and this should fix it.

01: public function index( Request $request, $slug = null, $tag = null) { 02: ... 03: } 04:

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"