Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create complete Laravel rest api and and confusing with Laravel REST controller

Tags:

rest

php

laravel

I am very new to Laravel, and now I am on my first Laravel project. Now I need to provide REST api for mobile. I followed REST resource controller documentation on Laravel website. But when I call my REST api, it is not returning any value.

How to complete rest api in Laravel? I am using Laravel 5.

My REST API server code follows.

"route"

Route::resource('/users','user_accessController');

"controller"

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Response;
use Illuminate\Http\Request;

use App\User;

class user_accessController extends Controller {

    public function index()
    {
        return Response::json(array('name'=>'wai yan'));
    }
}

Client code:

"using curl"

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, 'http://laravel.bbc:8080/users');
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_exec($ch);

    $res = curl_close($ch);

What is wrong with my code? It is not returning any value.

like image 215
Wai Yan Hein Avatar asked Nov 19 '25 14:11

Wai Yan Hein


1 Answers

Firstly you need to understand Laravel's naming convention.

StudlyCase for your controllers.

Use artisan command to generate resource controller

php artisan make:controller UserAccessController

Your route:

Route::resource('/users','UserAccessController');

"controller" - file name: UserAccessController.php

namespace App\Http\Controllers;

use Response;
//use App\Http\Controllers\Controller; no need for this both files are in same namespace

use App\User;

class UserAccessController extends Controller {

    /**
    * Display a listing of the resource.
    *
    * @return Response
    */
    public function index()
    {
        return response()->json(['name' => 'wai yan']);
    }


}

Am using Laravel 5 with same code above and this is the output when I used curl command:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://laravel.dev/users

enter image description here

like image 108
Emeka Mbah Avatar answered Nov 21 '25 02:11

Emeka Mbah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!