Laravel 6 tutorial – Build Your First CRUD App with Example

Laravel 6 tutorial – Build Your First CRUD App with Example

CRUD is the basic requirement of the any project. In this tutorial we will learn CRUD operation with server-side form validation. You will learn easy to insert update delete operation with laravel Applications from scratch.

Originally published at https://w3path.com

We will create CRUD (create/read/update/delete) for product management. We will validate crud application forms with server-side validation. In this product crud management, we will use the resource controller and route.

Contents

  • Install Laravel Fresh Project
  • Generate Model and Migration
  • Create Resource Route & Controller
  • Create the blade view
  • Start Development Server
  • Conclusion
Install Laravel Fresh Project

We need to install Laravel 6 fresh application using below command, Open your command prompt and run the below command :

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

After successfully install Laravel 6 Application, Go to your project root directory and find the .env file and setup database credential, If you don’t find the .env file then rename the .env.example file to .env

Configuration in .env

In this step, we will set database credential in .env file. Let’s open .env file.

 
DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here
Generate Model and Migration

Now we will create table named Products and its migration file. use the below command:

php artisan make:model Product-m

This command will create a model named Products and also create one migration file for Product table. After successfully run the command go to database/migrations file and put the below here :

 
<?php 

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

class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('product_code');
$table->text('description');
$table->timestamps();
});
}

/** 
 * Reverse the migrations. 
 * 
 * @return void 
 */ 
public function down() 
{ 
    Schema::dropIfExists('products'); 
} 

}

Next, migrate the table using the below command.

php artisan migrate

If you found any query builder error in command prompt go to => app\Providers\AppServiceProvider.php and put the below code here :

 use Illuminate\Support\Facades\Schema;
 
public function boot()
{
    Schema::defaultStringLength(191);
}

And then run this below command :

 php artisan migrate:fresh

Now, add the fillable property inside Book.php file.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'title',
'product_code',
'description',
];
}
Create Resource Route & Controller

Create the ProductController using the below command.

php artisan make:controller ProductController  --resource

This command will create a contoller name ProductController and also inside by default seven methods like index, store, create, update, destroy, show, edit.

Next, We need to add the resource route. Go to routes/web.php put the below routes here :

<?php

Route::get('/', function () {
return view('welcome');
});

Route::resource('products', 'ProductController');

Next open controller, Go to app/HTTP/Controller/ProductController and put the below code here :

<?php
   
namespace App\Http\Controllers;
   
use App\Product;
use Illuminate\Http\Request;
use Redirect;
use PDF;
   
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     /
    public function index()
    {
        $data['products'] = Product::orderBy('id','desc')->paginate(10);
   
        return view('product.list',$data);
    }
    
    /**
     
Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     /
    public function create()
    {
        return view('product.create');
    }
   
    /**
     
Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     /
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'product_code' => 'required',
            'description' => 'required',
        ]);
   
        Product::create($request->all());
    
        return Redirect::to('products')
       ->with('success','Greate! Product created successfully.');
    }
    
    /**
     
Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     /
    public function show(Request $request)
    {
         
    }
    
    /**
     
Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     /
    public function edit($id)
    {  
        $where = array('id' => $id);
        $data['product_info'] = Product::where($where)->first();
 
        return view('product.edit', $data);
    }
   
    /**
     
Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     /
    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required',
            'product_code' => 'required',
            'description' => 'required',
        ]);
         
        $update = ['title' => $request->title, 'description' => $request->description];
        Product::where('id',$id)->update($update);
   
        return Redirect::to('products')
       ->with('success','Great! Product updated successfully');
    }
   
    /**
     
Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Product::where('id',$id)->delete();
   
        return Redirect::to('products')->with('success','Product deleted successfully');
    }
     
}
Create the blade view

Next, We need to create some blade view files, Go to app/resources/views/ and create one folder name product. Inside the product folder create the following blade files.

  1. Layout.blade.php
  2. List.blade.php
  3. Create.blade.php
  4. Edit.blade.php
Layout.blade.php


<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel CRUD Tutorial With Example - Tutsmake.com</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <style>
    body{
    background-color: #25274d;
    }
    .container{
    background: #ff9b00;
    padding: 4%;
    border-top-left-radius: 0.5rem;
    border-bottom-left-radius: 0.5rem;
    }
    </style>
  </head>
  <body>
    <div class="container">
      <br><br><br>
      @yield('content')
    </div>
  </body>
</html>
List.blade.php  
@extends('product.layout')
   
@section('content')
  <a href="{{ route('products.create') }}" class="btn btn-success mb-2">Add</a>
  <br>
   <div class="row">
        <div class="col-12">
          
          <table class="table table-bordered" id="laravel_crud">
           <thead>
              <tr>
                 <th>Id</th>
                 <th>Title</th>
                 <th>Product Code</th>
                 <th>Description</th>
                 <th>Created at</th>
                 <td colspan="2">Action</td>
              </tr>
           </thead>
           <tbody>
              @foreach($products as $product)
              <tr>
                 <td>{{ $product->id }}</td>
                 <td>{{ $product->title }}</td>
                 <td>{{ $product->product_code }}</td>
                 <td>{{ $product->description }}</td>
                 <td>{{ date('Y-m-d', strtotime($product->created_at)) }}</td>
                 <td><a href="{{ route('products.edit',$product->id)}}" class="btn btn-primary">Edit</a></td>
                 <td>
                 <form action="{{ route('products.destroy', $product->id)}}" method="post">
                  {{ csrf_field() }}
                  @method('DELETE')
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
                </td>
              </tr>
              @endforeach
           </tbody>
          </table>
          {!! $products->links() !!}
       </div>
   </div>
 @endsection  
Create.blade.php
@extends('product.layout')
 
@section('content')
<h2 style="margin-top: 12px;" class="text-center">Add Product</a></h2>
<br>
 
<form action="{{ route('products.store') }}" method="POST" name="add_product">
{{ csrf_field() }}
 
<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <strong>Title</strong>
            <input type="text" name="title" class="form-control" placeholder="Enter Title">
            <span class="text-danger">{{ $errors->first('title') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <strong>Product Code</strong>
            <input type="text" name="product_code" class="form-control" placeholder="Enter Product Code">
            <span class="text-danger">{{ $errors->first('product_code') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <strong>Description</strong>
            <textarea class="form-control" col="4" name="description" placeholder="Enter Description"></textarea>
            <span class="text-danger">{{ $errors->first('description') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</div>
 
</form>
@endsection
Edit.blade.php
@extends('product.layout')
 
@section('content')
<h2 style="margin-top: 12px;" class="text-center">Edit Product</a></h2>
<br>
 
<form action="{{ route('products.update', $product_info->id) }}" method="POST" name="update_product">
{{ csrf_field() }}
@method('PATCH')
 
<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <strong>Title</strong>
            <input type="text" name="title" class="form-control" placeholder="Enter Title" value="{{ $product_info->title }}">
            <span class="text-danger">{{ $errors->first('title') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <strong>Product Code</strong>
            <input type="text" name="product_code" class="form-control" placeholder="Enter Product Code" value="{{ $product_info->product_code }}">
            <span class="text-danger">{{ $errors->first('product_code') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <strong>Description</strong>
            <textarea class="form-control" col="4" name="description" placeholder="Enter Description" >{{ $product_info->description }}</textarea>
            <span class="text-danger">{{ $errors->first('description') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</div>
 
</form>
@endsection
Start Development Server

In this step, we will use the PHP artisan serve command. It will start your server locally

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now we are ready to run our example open the below URL in the browser.

http://localhost:8000/products

Conclusion

In this article, We have successfully created Laravel 6 CRUD Application (Create, Read, Update, Delete) with example. Our examples run quickly.

Live Demo

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

Laravel 5.8 Tutorial for Beginners

Upgrading Laravel To 6.0 From 5.8

Laravel 6 Release New Features and Upgrade

What’s New in Laravel 6.0

Laravel 6 CRUD Application Tutorial

Laravel 6 Image Upload Tutorial


Laravel 6 REST API and Passport Tutorial (with an eCommerce Project)

Laravel 6 REST API and Passport Tutorial (with an eCommerce Project)

In this tutorial, we’ll explore the ways you can build—and test—a robust API using Laravel. We’ll be using Laravel 6, and all of the code is available for reference on GitHub. Now we are going to develop a ecommerce rest api where we have a product table and a review table. Using those two table we will make our ecommerce rest api.

Rest Api Development

In this tutorial, we’ll explore the ways you can build—and test—a robust API using Laravel. We’ll be using Laravel 6, and all of the code is available for reference on GitHub. Now we are going to develop a ecommerce rest api where we have a product table and a review table. Using those two table we will make our ecommerce rest api.

RESTful APIs

First, we need to understand what exactly is considered a RESTful API. REST stands for REpresentational State Transfer and is an architectural style for network communication between applications, which relies on a stateless protocol (usually HTTP) for interaction.

HTTP Verbs Represent Actions

In RESTful APIs, we use the HTTP verbs as actions, and the endpoints are the resources acted upon. We’ll be using the HTTP verbs for their semantic meaning:

  • **GET: **retrieve resources
  • POST: create resources
  • PUT: update resources
  • **DELETE: **delete resources

Update Action: PUT vs. POST

RESTful APIs are a matter of much debate and there are plenty of opinions out there on whether is best to update with POST, PATCH, or PUT, or if the create action is best left to the PUT verb. In this article we’ll be using PUT for the update action, as according to the HTTP RFC, PUT means to create/update a resource at a specific location. Another requirement for the PUT verb is idempotence, which in this case basically means you can send that request 1, 2 or 1000 times and the result will be the same: one updated resource in the database

Here, i will tech you how to create rest api with authentication using passport in laravel 6 application. i will show you step by step build restful api authentication using eloquent api resources in laravel 6. you can easily learn rest api for crud module with authentication in laravel 6.

Rest API is must be use when you are working with mobile application. when your application is prefer for web app and mobile app than you must have to create api for your mobile development.

However, Laravel provide easy way to create api. if you have authentication in your mobile app than you can easily do it using passport. Laravel 6 Passport provide way to create auth token for validating users.

So you also want to create rest api for your mobile application than you can follow this tutorial for how to create rest api step by step with laravel 6. If you are new than don't worry about that i written tutorial step by step.

Step 1: Install Laravel 6

I am going to explain step by step from scratch so, we need to get fresh Laravel 6 application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Step 2: Setup Passport

In this step we need to install passport via the Composer package manager, so one your terminal and fire bellow command:

composer require laravel/passport

After successfully install package, we require to get default migration for create new passport tables in our database. so let's run bellow command.

php artisan migrate

Next, we need to install passport using command, Using passport:install command, it will create token keys for security. So let's run bellow command:

php artisan passport:install

Step 3: Passport Configuration

In this step, we have to configuration on three place model, service provider and auth config file. So you have to just following change on that file.

In model we added HasApiTokens class of Passport,
In AuthServiceProvider we added "Passport::routes()",
In auth.php, we added api auth configuration.

app/User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

app/Providers/AuthServiceProvider.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->registerPolicies();
    }
}

config/auth.php

return [
    .....
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
    .....
]

Step 4: Create API Routes

Route::post('register', 'API\[email protected]');
Route::post('login', 'API\[email protected]');

Route::apiResource('/products','ProductController');

Route::group(['prefix' => 'products'],function(){

  Route::apiResource('/{product}/reviews','ReviewController');

});

Step 5: Create Model Migration and Controller and Factory

in next step, now we have create new controller as BaseController,and RegisterController, i created new folder "API" in Controllers folder because we will make alone APIs controller, So let's create controller: We need two table for this Rest Api and also we will create two factory for creating our dummy data. So run bellow command to make those things.

php artisan make:model Product -fmr
php artisan make:model Review -fmr

app/Http/Controllers/API/BaseController.php

namespace App\Http\Controllers\API;

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

class BaseController extends Controller
{

    public function sendResponse($result, $message)
    {
    	$response = [
            'success' => true,
            'data'    => $result,
            'message' => $message,
        ];

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

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

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

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

app/Http/Controllers/API/RegisterController.php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;

class RegisterController extends BaseController
{

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

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

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

        return $this->sendResponse($success, 'User register successfully.');
    }

    public function login(Request $request)
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            $success['name'] =  $user->name;

            return $this->sendResponse($success, 'User login successfully.');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }
}

Step 6: Setup database table

Now open your migration table and paste the below code.

database/migrations/products.php

Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('detail');
            $table->double('price');
            $table->string('stock');
            $table->double('discount');
            $table->integer('user_id')->unsigned();
            $table->timestamps();
});

database/migrations/reviews.php

Schema::create('reviews', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('product_id');
            $table->string('customer');
            $table->text('review');
            $table->double('star');
            $table->timestamps();
});

Step 7: Make relationship between product and review

Now we have to make relationship between Product model and Review model. for making it paste those code to your product and review model.

app/Product.php

namespace App;

use App\Review;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{   
	protected $fillable = [
        'name', 'detail', 'stock','price','discount'
    ];
    public function reviews()
    {
    	return $this->hasMany(Review::class);
    }
}

app/Review.php

namespace App;

use App\Product;
use Illuminate\Database\Eloquent\Model;

class Review extends Model
{   
	protected $fillable = [
        'customer', 'star', 'review'
    ];
    public function product()
    {
    	return $this->belongsTo(Product::class);
    }
}

Step 8: Setup factory

Now our relationship and and our database table is ready. so now we can run our migrate command to save that table in our database**. **So after configuring your database run **php artisan migrate **and open

database/factory/ProductFactory.php

use Faker\Generator as Faker;

$factory->define(Product::class, function (Faker $faker) {
    return [
        "name" => $faker->word,
        "detail" => $faker->paragraph,
        "price" => $faker->numberBetween(100,1000),
        "stock" => $faker->randomDigit,
        "discount" => $faker->numberBetween(2,30),
        "user_id" => function(){
        	return \App\User::all()->random();
        }
    ];
});

database/factory/ReviewFactory.php

use Faker\Generator as Faker;

$factory->define(Review::class, function (Faker $faker) {

    return [
    	"product_id" => function(){
    		return App\Product::all()->random();
    	},
        "customer" => $faker->name,
        "review" => $faker->paragraph,
        "star" => $faker->numberBetween(0,5)
    ];

});

Now our factory setup is done. So time to insert some dummy data. So open your command and paste this following line of command one after another.

php artisan tinker

factory(\App\Product::class,50)->create()

factory(\App\Review::class,50)->create()

exit

After running this command we have 50 product and 50 reviews for our products.

Step 9: Setup Product Controller

Now time to fetch our api data from database. So open

app\Http\Controllers\ProductController.php

namespace App\Http\Controllers;
use App\Http\Requests\ProductRequest;
use App\Http\Resources\ProductCollection;
use App\Http\Resources\ProductResource;
use App\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class ProductController extends Controller
{   

    public function __construct()
    {
        $this->middleware('auth:api')->except('index','show');
    }

    public function index()
    {

        return ProductCollection::collection(Product::paginate(5));
    }

    public function store(ProductRequest $request)
    {
       $product = new Product;
       $product->name = $request->name;
       $product->detail = $request->description;
       $product->price = $request->price;
       $product->stock = $request->stock;
       $product->discount = $request->discount;

       $product->save();

       return response([

         'data' => new ProductResource($product)

       ],Response::HTTP_CREATED);

    }

    public function show(Product $product)
    {
        return new ProductResource($product);
    }

    public function update(Request $request, Product $product)
    {   
        $this->userAuthorize($product);

        $request['detail'] = $request->description;

        unset($request['description']);

        $product->update($request->all());

       return response([

         'data' => new ProductResource($product)

       ],Response::HTTP_CREATED);

    }

    public function destroy(Product $product)
    {
        $product->delete();

        return response(null,Response::HTTP_NO_CONTENT);
    }

     public function userAuthorize($product)
    {
        if(Auth::user()->id != $product->user_id){
            //throw your exception text here;

        }
    }
}

Step 10: Create Resource Collection

For creating product resource and review resource just enter the following commands.

php artisan make:resource ProductCollection

php artisan make:resource ProductResouce 

php artisan make:resource ReviewResource

After running this command you will get three file to app/Http/Resources slug. Look , why we create this resource or collection ? Without creating this we can return our api data, But if you use Collection or Resource then you can modify your return data. How ? Look

app/Http/Resources/ProductCollection.php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class ProductCollection extends Resource {

    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'totalPrice' => round((1-($this->discount/100)) * $this->price,2),
            'discount' => $this->discount,
            'rating' => $this->reviews->count() > 0 ? round($this->reviews->sum('star')/$this->reviews->count(),2) : 'No rating yet',
            'href' => [
               'link' => route('products.show',$this->id)
            ]
        ];
    }
}

Now see we put name, totalPrice, **discount **etc in our return data field name. Here you can use any name whatever you want. But if you don't use it then you can't change your outcome data. Also we can add extra field name to show more information for a particular data. Hope you understand why we need resource or collection.

app/Http/Resources/ProductResource.php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class ProductResource extends Resource
{

    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'description' => $this->detail,
            'price' => $this->price,
            'stock' => $this->stock == 0 ? 'Out of stock' : $this->stock,
            'discount' => $this->discount,
            'totalPrice' => round((1-($this->discount/100)) * $this->price,2),
            'rating' => $this->reviews->count() > 0 ? round($this->reviews->sum('star')/$this->reviews->count(),2) : 'No rating yet',
            'href' => [
               'reviews' => route('reviews.index',$this->id)
            ]
        ];
    }
}

app/Http/Resources/ReviewResource.php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ReviewResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'customer' => $this->customer,
            'body' => $this->review,
            'star' => $this->star,
       ];
    }
}

Step 11: Create Custom Request

Laravel gives us default Request for handle form data. But we can use custom request for a specific model. Paste this following code to make request.

php artisan make:request Product

php artisan make:request Review

Now visit app/Http/Requests you will get two newly created file

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductRequest extends FormRequest
{

    public function authorize()
    {
        return true; //Only authorize user can do this operation if false then unauthorize user can do
    }

    public function rules()
    {
        return [
            'name' => 'required|max:255|unique:products',
            'description' => 'required',
            'price' => 'required|max:10',
            'stock' => 'required|max:6',
            'discount' => 'required|max:2'
        ];
    }
}

**authorize() **method return two things, true or false. If true then it will work for only authenticated user and if false it will works for unauthorize user. **rules() **method validated html form data.

app/Http/Requests/ReviewRequest.php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ReviewRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            "customer" => "required",
            "star" => "required|integer|between:0,5",
            "review" => "required"
        ];
    }
}

**Step 12: Setup review **controller

app/Http/Controllers/ReviewController.php

namespace App\Http\Controllers;

use App\Http\Resources\ReviewResource;
use App\Product;
use App\Review;
use Illuminate\Http\Request;

class ReviewController extends Controller
{
    public function index(Product $product)
    {
       return ReviewResource::collection($product->reviews);

    }

    public function store(ReviewRequest $request , Product $product)
    {
       $review = new Review($request->all());

       $product->reviews()->save($review);

       return response([
         'data' => new ReviewResource($review)
       ],Response::HTTP_CREATED);
    }

    public function update(Request $request, Product $procduct, Review $review)
    {
        $review->update($request->all());
    }

    public function destroy(Product $product, Review $review)
    {
        $review->delete();
        return response(null,Response::HTTP_NO_CONTENT);
    }
}

Now everything is done for our rest api development project. So now you are ready to run our Rest Api data in your postman. Now we are ready to to run full restful api and also passport api in laravel. so let's run our example so run bellow command for quick run:

php artisan serve

make sure in details api we will use following headers as listed bellow:

'headers' => [

    'Accept' => 'application/json',

    'Authorization' => 'Bearer '.$accessToken,

]

Here is Routes URL with Verb:

Register API: Verb:GET, URL:http://localhost:8000/api/register
Login API: Verb:GET, URL:http://localhost:8000/api/login
Product API: URL:http://127.0.0.1:8000/api/products
Product Single API: URL:http://127.0.0.1:8000/api/products/4
Product Review API: URL:http://127.0.0.1:8000/api/products/4/reviews

Now visit those url in your postman and you will see your api data. Hope you've enjoy this tutorial. If you have any doubt or confusion then ask me you confution in the comment box. i will try to fix your confusion. Hope it can help you.

How to Build PHP REST API Framework from Scratch

How to Build PHP REST API Framework from Scratch

This PHP Framework tutorial explains how to build PHP REST API Framework from scratch. Create own PHP Rest framework to handle GET, POST, PUT and DELETE Requests.

In this video tutorial we have created own PHP Rest framework to handle GET, POST, PUT and DELETE Requests.

We will develop complete rest framework from scratch.

We have covered PDO Connection with Mysql Database.

We have also covered small part of Object Oriented Programming

We have used Postman to interact with the API

We have covered handling GET, POST, PUT and DELETE Request

Source Code: https://github.com/nandymandy1/PHP-REST-FRAMEWORK-FROM-SCRATCH

How to create REST API with authentication using Passport in Laravel 6

How to create REST API with authentication using Passport in Laravel 6

In this tutorial, you'll learn how to create rest api with authentication using passport in laravel 6 application. I will show you step by step build Restful API Authentication using eloquent API resources in Laravel 6.

REST API is must be use when you are working with mobile application. when your application is prefer for web app and mobile app than you must have to create api for your mobile development.

However, Laravel provide easy way to create api. if you have authentication in your mobile app than you can easily do it using passport. Laravel 6 Passport provide way to create auth token for validating users.

So you also want to create rest api for your mobile application than you can follow this tutorial for how to create rest api step by step with Laravel 6. If you are new than don't worry about that i written tutorial step by step.

Step 1: Install Laravel 6

I am going to explain step by step from scratch so, we need to get fresh Laravel 6 application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Step 2: Use Passport

In this step we need to install passport via the Composer package manager, so one your terminal and fire bellow command:

composer require laravel/passport

After successfully install package, we require to get default migration for create new passport tables in our database. so let's run bellow command.

php artisan migrate

Next, we need to install passport using command, Using passport:install command, it will create token keys for security. So let's run bellow command:

php artisan passport:install

Read Also: Laravel 6 CRUD Application Tutorial

Step 3: Passport Configuration

In this step, we have to configuration on three place model, service provider and auth config file. So you have to just following change on that file.

In model we added HasApiTokens class of Passport,

In AuthServiceProvider we added "Passport::routes()",

In auth.php, we added api auth configuration.

app/User.php

<?php

  

namespace App;

  

use Illuminate\Notifications\Notifiable;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Laravel\Passport\HasApiTokens;

use Illuminate\Foundation\Auth\User as Authenticatable;

  

class User extends Authenticatable implements MustVerifyEmail

{

    use HasApiTokens, Notifiable;

  

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'name', 'email', 'password',

    ];

  

    /**

     * The attributes that should be hidden for arrays.

     *

     * @var array

     */

    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

{

    /**

     * The policy mappings for the application.

     *

     * @var array

     */

    protected $policies = [

        'App\Model' => 'App\Policies\ModelPolicy',

    ];


    /**

     * Register any authentication / authorization services.

     *

     * @return void

     */

    public function boot()

    {

        $this->registerPolicies();

    }

}

config/auth.php

<?php


return [

    .....

    'guards' => [

        'web' => [

            'driver' => 'session',

            'provider' => 'users',

        ],

        'api' => [

            'driver' => 'passport',

            'provider' => 'users',

        ],

    ],

    .....

]
Step 4: Add Product Table and Model

Next, we require to create migration for posts table using Laravel 6 php artisan command, so first fire bellow command:

php artisan make:migration create_products_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create products table.

<?php


use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class CreateProductsTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('products', function (Blueprint $table) {

            $table->bigIncrements('id');

            $table->string('name');

            $table->text('detail');

            $table->timestamps();

        });

    }


    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('products');

    }

}

After create migration we need to run above migration by following command:

php artisan migrate

After create "products" table you should create Product model for products, so first create file in this path app/Product.php and put bellow content in item.php file:

app/Product.php

<?php

  

namespace App;

   

use Illuminate\Database\Eloquent\Model;

   

class Product extends Model

{

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'name', 'detail'

    ];

}
Step 5: Create API Routes

In this step, we will create api routes. Laravel provide api.php file for write web services route. So, let's add new route on that file.

routes/api.php

<?php

  

/*

|--------------------------------------------------------------------------

| API Routes

|--------------------------------------------------------------------------

|

| Here is where you can register API routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| is assigned the "api" middleware group. Enjoy building your API!

|

*/

  

Route::post('register', 'API\[email protected]');

Route::post('login', 'API\[email protected]');

   

Route::middleware('auth:api')->group( function () {

    Route::resource('products', 'API\ProductController');

});
Step 6: Create Controller Files

in next step, now we have create new controller as BaseController, ProductController and RegisterController, i created new folder "API" in Controllers folder because we will make alone APIs controller, So let's create both controller:

app/Http/Controllers/API/BaseController.php

<?php


namespace App\Http\Controllers\API;


use Illuminate\Http\Request;

use App\Http\Controllers\Controller as Controller;


class BaseController extends Controller

{

    /**

     * success response method.

     *

     * @return \Illuminate\Http\Response

     */

    public function sendResponse($result, $message)

    {

    	$response = [

            'success' => true,

            'data'    => $result,

            'message' => $message,

        ];


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

    }


    /**

     * return error response.

     *

     * @return \Illuminate\Http\Response

     */

    public function sendError($error, $errorMessages = [], $code = 404)

    {

    	$response = [

            'success' => false,

            'message' => $error,

        ];


        if(!empty($errorMessages)){

            $response['data'] = $errorMessages;

        }


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

    }

}

app/Http/Controllers/API/RegisterController.php

<?php

   

namespace App\Http\Controllers\API;

   

use Illuminate\Http\Request;

use App\Http\Controllers\API\BaseController as BaseController;

use App\User;

use Illuminate\Support\Facades\Auth;

use Validator;

   

class RegisterController extends BaseController

{

    /**

     * Register api

     *

     * @return \Illuminate\Http\Response

     */

    public function register(Request $request)

    {

        $validator = Validator::make($request->all(), [

            'name' => 'required',

            'email' => 'required|email',

            'password' => 'required',

            'c_password' => 'required|same:password',

        ]);

   

        if($validator->fails()){

            return $this->sendError('Validation Error.', $validator->errors());       

        }

   

        $input = $request->all();

        $input['password'] = bcrypt($input['password']);

        $user = User::create($input);

        $success['token'] =  $user->createToken('MyApp')->accessToken;

        $success['name'] =  $user->name;

   

        return $this->sendResponse($success, 'User register successfully.');

    }

   

    /**

     * Login api

     *

     * @return \Illuminate\Http\Response

     */

    public function login(Request $request)

    {

        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 

            $user = Auth::user(); 

            $success['token'] =  $user->createToken('MyApp')-> accessToken; 

            $success['name'] =  $user->name;

   

            return $this->sendResponse($success, 'User login successfully.');

        } 

        else{ 

            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);

        } 

    }

}

app/Http/Controllers/API/ProductController.php

<?php

   

namespace App\Http\Controllers\API;

   

use Illuminate\Http\Request;

use App\Http\Controllers\API\BaseController as BaseController;

use App\Product;

use Validator;

use App\Http\Resources\Product as ProductResource;

   

class ProductController extends BaseController

{

    /**

     * Display a listing of the resource.

     *

     * @return \Illuminate\Http\Response

     */

    public function index()

    {

        $products = Product::all();

    

        return $this->sendResponse(ProductResource::collection($products), 'Products retrieved successfully.');

    }

    /**

     * Store a newly created resource in storage.

     *

     * @param  \Illuminate\Http\Request  $request

     * @return \Illuminate\Http\Response

     */

    public function store(Request $request)

    {

        $input = $request->all();

   

        $validator = Validator::make($input, [

            'name' => 'required',

            'detail' => 'required'

        ]);

   

        if($validator->fails()){

            return $this->sendError('Validation Error.', $validator->errors());       

        }

   

        $product = Product::create($input);

   

        return $this->sendResponse(new ProductResource($product), 'Product created successfully.');

    } 

   

    /**

     * Display the specified resource.

     *

     * @param  int  $id

     * @return \Illuminate\Http\Response

     */

    public function show($id)

    {

        $product = Product::find($id);

  

        if (is_null($product)) {

            return $this->sendError('Product not found.');

        }

   

        return $this->sendResponse(new ProductResource($product), 'Product retrieved successfully.');

    }

    

    /**

     * Update the specified resource in storage.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  int  $id

     * @return \Illuminate\Http\Response

     */

    public function update(Request $request, Product $product)

    {

        $input = $request->all();

   

        $validator = Validator::make($input, [

            'name' => 'required',

            'detail' => 'required'

        ]);

   

        if($validator->fails()){

            return $this->sendError('Validation Error.', $validator->errors());       

        }

   

        $product->name = $input['name'];

        $product->detail = $input['detail'];

        $product->save();

   

        return $this->sendResponse(new ProductResource($product), 'Product updated successfully.');

    }

   

    /**

     * Remove the specified resource from storage.

     *

     * @param  int  $id

     * @return \Illuminate\Http\Response

     */

    public function destroy(Product $product)

    {

        $product->delete();

   

        return $this->sendResponse([], 'Product deleted successfully.');

    }

}
Step 7: Create Eloquent API Resources

This is a very important step of creating rest api in laravel 6. you can use eloquent api resources with api. it will helps you to make same response layout of your model object. we used in ProductController file. now we have to create it using following command:

php artisan make:resource Product

Now there created new file with new folder on following path:

app/Http/Resources/Product.php

<?php

  

namespace App\Http\Resources;

   

use Illuminate\Http\Resources\Json\JsonResource;

   

class Product extends JsonResource

{

    /**

     * Transform the resource into an array.

     *

     * @param  \Illuminate\Http\Request  $request

     * @return array

     */

    public function toArray($request)

    {

        return [

            'id' => $this->id,

            'name' => $this->name,

            'detail' => $this->detail,

            'created_at' => $this->created_at->format('d/m/Y'),

            'updated_at' => $this->updated_at->format('d/m/Y'),

        ];

    }

}

Now we are ready to to run full restful api and also passport api in laravel. so let's run our example so run bellow command for quick run:

php artisan serve

make sure in details api we will use following headers as listed bellow:

'headers' => [

    'Accept' => 'application/json',

    'Authorization' => 'Bearer '.$accessToken,

]

Here is Routes URL with Verb:

Now simply you can run above listed url like as bellow screen shot:

  1. Register API: Verb:GET, URL:http://localhost:8000/api/register

  1. Login API: Verb:GET, URL:http://localhost:8000/api/login

  1. Product List API: Verb:GET, URL:http://localhost:8000/api/products

  1. Product Create API: Verb:POST, URL:http://localhost:8000/api/products

  1. Product Show API: Verb:GET, URL:http://localhost:8000/api/products/{id}

  1. Product Update API: Verb:PUT, URL:http://localhost:8000/api/products/{id}

  1. Product Delete API: Verb:DELETE, URL:http://localhost:8000/api/products/{id}

You can download code from git: Download Code from Github

I hope it can help you...