Laravel Redirect To Another URL / Web Page - HTTP Laravel Redirects

Laravel 5.7 REST API Tutorial Example Steps

Today, We want to share with you Laravel 5.7 REST API Tutorial Example.In this post we will show you Creating APIs in Laravel 5.7 using API resources, hear for Create restful APIs using Laravel 5.7 with resourceful routes example we will give you demo and example for implement.In this post, we will learn about Create REST API in Laravel 5.7 with authentication using Passport with an example.

Laravel 5.7 REST API Tutorial Example

There are the Following The simple About Laravel 5.7 REST API Tutorial Example Full Information With Example and source code.

As I will cover this Post with live Working example to develop PHP Laravel 5.7 – Rest API with Passport Tutorial, so the Laravel 5.7 – Create REST API with authentication using Passport Tutorial is following below.

  jquery Increment Animating Numbers Counting Up Example

There is All the API Routes URL using Laravel 5.7

  • Student Login: API:GET, URL:http://student-management/oauth/token
  • Student Signup: API:GET, URL:http://student-management/api/signup
  • Student List: API:GET, URL:http://student-management/api/students
  • Student Create: API:POST, URL:http://student-management/api/students
  • Student Show: API:GET, URL:http://student-management/api/students/{id}
  • Student Update: API:PUT, URL:http://student-management/api/students/{id}
  • Student Delete: API:DELETE, URL:http://student-management/api/students/{id}

Step 1: Install Laravel 5.7 Project

Step by step from Full Example scratch in fresh Laravel 5.7 application

composer create-project --prefer-dist laravel/laravel atmiya25

Step 2: Setup Passport

// Setup passport via the Composer
composer require laravel/passport

//default migration
php artisan migrate

//Setup passport using command in Laravel 5.7
php artisan passport:install

Step 3: Laravel 5.7 Passport Settings

app/Member.php

<?php
  
namespace App;
  
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\Member as Authenticatable;
  
class Member extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, Notifiable;
  
    protected $fillable = [
        'name', 'email', 'password',
    ];
  
    protected $hidden = [
        'password', 'remember_token',
    ];
}

app/Providers/AuthServiceProvider.php

<?php

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;


class AuthServiceProvider extends ServiceProvider
{

    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    public function boot()
    {
        $this->signupPolicies();
        Passport::routes();
    }
}

config/auth.php

<?php
//
return [
    .....
	............
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'members',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'members',
        ],
    ],
    .....
	...............
]

Step 4: Laravel 5.7 Add Student Table and Model

php artisan make:migration create_students_table

database/migrations

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStudentsTable extends Migration
{
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('students');
    }
}

create Laravel 5.7 migration

php artisan migrate

app/Student.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
    protected $fillable = [
        'name', 'detail'
    ];
}

Step 5: Laravel 5.7 API Routes

routes/api.php

<?php
 
Route::post('signup', 'API\[email protected]');
  
Route::middleware('auth:api')->group( function () {
	Route::resource('students', 'API\StudentController');
});

Step 6: Make a Laravel 5.7 Controller Files

app/Http/Controllers/API/CustomController.php

<?php
namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;


class CustomController extends Controller
{
    public function apiResponseSuccess($result, $message)
    {
    	$response = [
            'success' => true,
            'data'    => $result,
            'message' => $message,
        ];


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

    public function apiResponseError($error, $msgError = [], $code = 404)
    {
    	$response = [
            'success' => false,
            'message' => $error,
        ];


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


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

app/Http/Controllers/API/StudentController.php

<?php

namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\CustomController as CustomController;
use App\Student;
use Validator;


class StudentController extends CustomController
{
    public function index()
    {
        $students = Student::all();
        return $this->apiResponseSuccess($students->toArray(), 'Students retrieved successfully.');
    }

    public function store(Request $request)
    {
        $input = $request->all();


        $validator = Validator::make($input, [
            'name' => 'required',
            'detail' => 'required'
        ]);

        if($validator->fails()){
            return $this->apiResponseError('Validation Error.', $validator->errors());       
        }
        $student = Student::create($input);
        return $this->apiResponseSuccess($student->toArray(), 'Student created successfully.');
    }

    public function show($id)
    {
        $student = Student::find($id);
        if (is_null($student)) {
            return $this->apiResponseError('Student not found.');
        }
        return $this->apiResponseSuccess($student->toArray(), 'Student retrieved successfully.');
    }
    public function update(Request $request, Student $student)
    {
        $input = $request->all();
        $validator = Validator::make($input, [
            'name' => 'required',
            'detail' => 'required'
        ]);

        if($validator->fails()){
            return $this->apiResponseError('Validation Error.', $validator->errors());       
        }

        $student->name = $input['name'];
        $student->detail = $input['detail'];
        $student->save();
        return $this->apiResponseSuccess($student->toArray(), 'Student updated successfully.');
    }

    public function destroy(Student $student)
    {
        $student->delete();
        return $this->apiResponseSuccess($student->toArray(), 'Student deleted successfully.');
    }
}

app/Http/Controllers/API/SignupController.php

<?php
namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\API\CustomController as CustomController;
use App\Member;
use Illuminate\Support\Facades\Auth;
use Validator;

class SignupController extends CustomController
{
    public function signup(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);


        if($validator->fails()){
            return $this->apiResponseError('Validation Error.', $validator->errors());       
        }

        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $member = Member::create($input);
        $success['token'] =  $member->createToken('MyApp')->accessToken;
        $success['name'] =  $member->name;


        return $this->apiResponseSuccess($success, 'Member signup successfully.');
    }
}

run Laravel 5.7 restful api Project

php artisan serve

Include Laravel 5.7 Must in Headers part

'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken,
]

Angular 6 CRUD Operations Application Tutorials

Read :

  Autocomplete Textbox with Multiple Values using jQuery PHP and MySQL

Summary

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

I hope you get an idea about Laravel 5.7 REST API Tutorial Example.
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 Reply

avatar
  Subscribe  
Notify of