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
Share:
10,567

Related videos on Youtube

Roham Rafii
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, 2022

Comments

  • Roham Rafii
    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
    Roham Rafii almost 6 years
    thanks a lot. I have followed a wrong document. I replaced success() with json() and it works ..
  • ConorJohn
    ConorJohn about 3 years
    Thanks @RohamRafii, the link to the documentation is broken, this is the same issue I had, json() solved it!
  • Joeri
    Joeri almost 2 years