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

Read Also:  How to Export MySQL Database data to Excel in PHP MySQLi

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

<?php

namespace App\Http\Middleware;

use Closure;
use DB;
class APIkey
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin: *');
      $headers = $this->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:

Read Also:  Laravel 5/6/7 CRUD Operations Example Step By Step

//API 

Route::get('membersubject', 'API\[email protected]')->middleware('APIkey');
Route::get('getdepartment', 'API\[email protected]')->middleware('APIkey');
Route::get('/sub_category/get/{id}', 'API\[email protected]')->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;
}
//<a href="https://www.pakainfo.com/" target="_blank" alt="pakainfo" title="pakainfo">Free Download Example - Pakainfo.com</a>

Angular 6 CRUD Operations Application Tutorials

Read :

Read Also:  Http Post and Get Web Api Calls using Vuejs

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.