Sử dụng lệnh curl, api thêm người dùng bằng api (ok)

$ curl -X POST http://blog.com/api/register -H "Accept: application/json" -H "Content-Type: application/json" -d '{"name": "LionelPhan10", "email": "lionel10@gmail.com", "password": "toptal"}'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   307  100   230  100    77    513    171 --:--:-- --:--:-- --:--:--   686{"data":{"name":"LionelPhan10","email":"lionel10@gmail.com","updated_at":"2020-07-25T18:52:03.000000Z","created_at":"2020-07-25T18:52:03.000000Z","id":21,"api_token":"K9cigx0EQwJAmgnjL9Rwx2ULFs0CSkf6Lief0fcTQ3gq2d0HU23b9tbJ89Nd"}}

C:\xampp\htdocs\blog\routes\api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Use App\Article;
/*
|--------------------------------------------------------------------------
| 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::get('articles', 'ArticleController@index');
Route::get('articles/{id}', 'ArticleController@show');
Route::post('articles', 'ArticleController@store');
Route::put('articles/{id}', 'ArticleController@update');
Route::delete('articles/{id}', 'ArticleController@delete');
Route::post('register', 'Auth\RegisterController@register');
Route::post('login', 'Auth\LoginController@login');

C:\xampp\htdocs\blog\app\Http\Controllers\Auth\RegisterController.php

<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Validator;
use Hash;
use Illuminate\Support\Facades\Auth;
class RegisterController extends Controller {
  public function register(Request $request) {
    // Here the request is validated. The validator method is located
    // inside the RegisterController, and makes sure the name, email
    // password and password_confirmation fields are required.
    $this->validator($request->all())->validate();
    // A Registered event is created and will trigger any relevant
    // observers, such as sending a confirmation email or any
    // code that needs to be run as soon as the user is created.
    event(new Registered($user = $this->create($request->all())));
    // After the user is created, he's logged in.
    $this->guard()->login($user);
    // And finally this is the hook that we want. If there is no
    // registered() method or it returns null, redirect him to
    // some other URL. In our case, we just need to implement
    // that method to return the correct response.
    return $this->registered($request, $user) ? $this->registered($request, $user) : redirect($this->redirectPath());
  }
  protected function create(array $data) {
    $user = User::create([
      'name'     => $data['name'],
      'email'    => $data['email'],
      'password' => Hash::make($data['password']),
    ]);
    return $user;
  }
  protected function guard() {
	  return Auth::guard();
	}
  protected function registered(Request $request, $user) {
    $user->generateToken();
    return response()->json(['data' => $user->toArray()], 201);
  }
  protected function validator(array $data) {
    return Validator::make($data, [
      'name'     => 'required|string|max:255',
      'email'    => 'required|string|email|max:255|unique:users',
      'password' => 'required|string|min:6',
    ]);
  }
}

C:\xampp\htdocs\blog\app\Http\Controllers\Auth\LoginController.php

<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class LoginController extends Controller {
  public function login(Request $request) {
    $this->validateLogin($request);
    if ($this->attemptLogin($request)) {
      $user = $this->guard()->user();
      $user->generateToken();
      return response()->json([
        'data' => $user->toArray(),
      ]);
    }
    return $this->sendFailedLoginResponse($request);
  }
}

C:\xampp\htdocs\blog\app\User.php

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable {
  use 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',
  ];

  /**
   * The attributes that should be cast to native types.
   *
   * @var array
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  public function generateToken() {
    $this->api_token = str_random(60);
    $this->save();
    return $this->api_token;
  }
}

Last updated