2

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.

3 Answers 3

3

There is no success method on the ResponseFactory. You can find the available methods here.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot. I have followed a wrong document. I replaced success() with json() and it works ..
Thanks @RohamRafii, the link to the documentation is broken, this is the same issue I had, json() solved it!
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

Comments

0

For me i got this error because , i not add "use HttpResponse;" on my controller class; So just add "use HttpResponse;" on your controller class after your class declaration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.