PHP Laravel REST APIs Tutorial with MySQL

Today, We want to share with you PHP Laravel REST APIs Tutorial with MySQL.In this post we will show you Creating an API Key for Laravel REST APIs, hear for Best Practices PHP Laravel REST API from Scratch we will give you demo and example for implement.In this post, we will learn about Create REST API in Laravel with authentication with an example.

PHP Laravel REST APIs Tutorial with MySQL

There are the Following The simple About PHP Laravel REST APIs Tutorial with MySQL Full Information With Example and source code.

As I will cover this Post with live Working example to develop How To Create A Simple REST API in Laravel, so the Learn to build a REST API with Laravel API resources for this example is following below.

Creating the User Access Key

php artisan make:migration create_member_access_key

Table_name = webapimember

add a new field named access_key

Schema::table('webapimember', function (Blueprint $table) {

            $table->longtext('access_key', 15)->nullable();    
});

Database Migrations

php artisan migrate

created table in database (webapimember) store Key – A345SJDK5

php artisan make:middleware APIkey

Created middleware(APIkey) in middleware folder

middleware/APIkey.php

apache_request_headers();
      $api_key = $headers['Authorization'];
        if ($api_key == '') {
          return redirect('/');
        } else { 

             // dd($headers);
            $users = DB::table('webapimember')->where('access_key', $api_key)->count();
            if ($users != 1) { 
              //return response("Invalid access key");
              return $this->sendError('Invalid access key.');
            } else { 
              return $next($request);
            }
        } 
    }
    public function apache_request_headers() {
        $headers = array();
        foreach($_SERVER as $key => $value) {
            if(substr($key, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
            }
        }
        return $headers;
    }
    public function sendError($error, $errorMessages = [], $code = 404)
    {
        $response = [
            'success' => false,
            'message' => $error,
        ];


        if(!empty($errorMessages)){
            $response['data'] = $errorMessages;
        }


        return response()->json($response, $code);
    }
}

Http/Kernel.php

protected $routeMiddleware = [
        //add your APIkey middleware
        'APIkey' => \App\Http\Middleware\APIkey::class,
    ];

Now we can change our route file one last time:

//API 

Route::get('membersubject', 'API\MemberController@getsubject')->middleware('APIkey');
Route::get('getdepartment', 'API\MemberController@getdepartment')->middleware('APIkey');
Route::get('/sub_category/get/{id}', 'API\MemberController@getsubdepartment')->middleware('APIkey');

php curl call

$apiKey = 'CD35Xsdjsd58slios123';
$api_url = 'https://www.pakainfo.com/';
$get_subject = RestfulAPI('get', $api_url.'membersubject', $data=null, $apiKey);
$subject_data = json_decode($get_subject,true);


$getdepartment = RestfulAPI('get', $api_url.'getdepartment', $data=null, $apiKey);
$category_data = json_decode($getdepartment,true);
print_r($category_data['message']);


function RestfulAPI($method, $url, $data, $apiKey){

    $curl = curl_init();

    switch ($method){
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // OPTIONS:
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: '.$apiKey,
        'Content-Type: application/json',
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

    // EXECUTE:
    $result = curl_exec($curl);
    //print_r($result);
    if(!$result){die("Connection Failure");}
    curl_close($curl);
    return $result;
}
//Free Download Example - Pakainfo.com
Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP Laravel REST APIs Tutorial with MySQL.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment