Error on finding controller from Laravel API Router
10,567
Solution 1
There is no success
method on the ResponseFactory
. You can find the available methods here.
Solution 2
You are calling a macro function that is not registerd to the responseFactory.To use success method,Create your custom responseServiceProvider and write this inside boot()
Response::macro('success',function($data){
return Response::json([
'data'=>$data,
]) ;
});
And then register your ResponseServiceProvider to app.php by adding your Class name to the array called providers. This is how you add to the array
App\Providers\ResponseMacroServiceProvider::class
Related videos on Youtube
Author by
Roham Rafii
Hello. My name is Roham Tehrani. I'm a Senior Front End / Back End Developer and Software Architect ..
Updated on June 04, 2022Comments
-
Roham Rafii over 1 year
I created a fresh Laravel framework.
I created a controller named PostsController:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; use App\Http\Controllers\Controller; class PostsController extends Controller { public function index() { $posts = Post::get(); return response()->success(compact('posts')); } }
Then I created a route in the file
api.php
:Route::get('posts', 'PostsController@index');
I ran the command
$ php artisan serve`
and I tested the URL
localhost:8000/api/posts
This error occurs:
BadMethodCallException Method Illuminate\Routing\ResponseFactory::success does not exist. file: vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php line: 100 throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
I can't understand why this happened. Please help me.
-
Roham Rafii almost 6 yearsthanks a lot. I have followed a wrong document. I replaced success() with json() and it works ..
-
ConorJohn about 3 yearsThanks @RohamRafii, the link to the documentation is broken, this is the same issue I had, json() solved it!
-
Joeri almost 2 yearsgithub.com/laravel/framework/blob/8.x/src/Illuminate/Contracts/… link for laravel 8.x