12
votes

I am following the Laracast's API tutorial and trying to create an ApiController that all the other controllers extend. ApiController is responsible for response handling.

class ApiController extends Controller
{
    protected $statusCode;

    public function getStatusCode()
    {
        return $this->statusCode;
    }

    public function setStatusCode($statusCode)
    {
        $this->statusCode = $statusCode;
    }

    public function respondNotFound($message = 'Not Found!')
    {
        return Reponse::json([

            'error' => [
                'message' => $message,
                'status_code' => $this->getStatusCode()
            ]

        ]);
    }
}

And i also have a ReportController that extends ApiController.

class ReportController extends ApiController
{
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $report = Report::find($id);

        if (! $report ) {
            $this->respondNotFound(Report does not exist.');
        }

        return Response::json([
            'data'=> $this->ReportTransformer->transform($report)
        ], 200);
    }
}

When i try to call respondNotFound method from ReportController i get

Class 'App\Http\Controllers\Response' not found error

eventhough i add use Illuminate\Support\Facades\Response;to parent or child class i get the error. How can i fix this ?

Any help would be appreciated.

1
Try use Response; instead. Or the response() helper - return response()->json(...);. - ceejayoz
Seems the namespace you are using to import the class Response is not correct. use the correct one. - Mojtaba
Use statements are per file, you still have to include them in child classes even if they are included in the parent. Either add the facade use statement in the child class or use \Response - jfadich

1 Answers

40
votes

Since it's a facade, add this:

use Response;

Or use full namespace:

return \Response::json(...);

Or just use helper:

return response()->json(...);