CREATE TABLE `photos` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`photo_origin_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`photo_new_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`photo_temp_path` varchar(255) NOT NULL,
`photo_extension` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`photo_status` enum('active','inactive') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`photo_date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
สร้าง Class Model Photo (Photo.php)
php artisan make:Model Photo
แก้ไขไฟล์ app\Models\Photo.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
use HasFactory;
protected $table = 'photos';
protected $fillable = [
'id', 'photo_origin_name', 'photo_new_name',
'photo_extension', 'photo_status', 'photo_date', 'photo_temp_path'
];
public $timestamps = false;
}
สร้าง Class Controller UploadFileController (UploadFileController.php)
<?php
namespace App\Http\Controllers;
use App\Models\Photo;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class UploadFileController extends Controller
{
public function simpleUplaod(Request $request)
{
try {
if ($request->file('photo')->isValid()) {
$path = $request->photo->path();
$extension = $request->photo->extension();
$clientOriginalName = $request->photo->getClientOriginalName();
$newFileName = time() . $clientOriginalName;
$uploadedFile = $request->file('photo');
// Save File to local drive
Storage::putFileAs('photos', $uploadedFile, $newFileName);
//Save File to Photo table
$photo = new Photo();
$photo->photo_temp_path = $path;
$photo->photo_origin_name = $clientOriginalName;
$photo->photo_new_name = $newFileName;
$photo->photo_extension = $extension;
$photo->photo_status = 'ACTIVE';
$photo->photo_date = Carbon::now();
$photo->save();
return [
'path' => $path,
'extension' => $extension,
'clientOriginalName' => $clientOriginalName,
'newFileName' => $newFileName
];
}
} catch (\Throwable $th) {
return $th->getMessage();
}
}
}
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $addHttpCookie = true;
protected $except = [
'upload'
];
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePhotosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->id();
$table->string('photo_name');
$table->integer('photo_size');
$table->string('photo_url');
$table->enum('photo_status', ['active', 'inactive']);
$table->dateTime('photo_date', 0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('photos');
}
}
ในการกำหนด datatype ของ column ตารางมีรูปแบบที่หลากหลาย มี function รองรับอยู่แล้ว สำหรับการกำหนดสร้าง สามารถดูเพิ่มเติมได้จากตารางนี้
Available Column Types
The schema builder contains a variety of column types that you may specify when building your tables:
ก่อนที่จะทดสอบติดตั้ง npm i -g json เพื่อ pritty json response เพื่อความสวยงาม
$ curl localhost:8000/api/photos | json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 28 0 28 0 0 65 0 --:--:-- --:--:-- --:--:-- 65
{
"name": "index",
"photos": []
}
/* fetch photos all */
$ curl localhost:8000/api/photos/create | json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 31 0 31 0 0 73 0 --:--:-- --:--:-- --:--:-- 73
{
"name": "create",
"status": true
}
/* create photo */
$ curl -X POST -H "Content-Type: application/json" -d "{\"photo_name\":\"laravel\",\"photo_size\":1024,\"photo_url\":\"https://laravel.com/img/logotype.min.svg\",\"photo_status\":\"active\",\"photo_date\":\"2020-10-06 10:24:01\"}" http://127.0.0.1:8000/api/photos | json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 357 0 201 100 156 1116 866 --:--:-- --:--:-- --:--:-- 1994
{
"name": "store",
"payload": {
"photo_name": "laravel",
"photo_size": 1024,
"photo_url": "https://laravel.com/img/logotype.min.svg",
"photo_status": "active",
"photo_date": "2020-10-06 10:24:01"
},
"status": true
}
/* create photo with payload */
$ curl localhost:8000/api/photos/1 | json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 286 0 286 0 0 722 0 --:--:-- --:--:-- --:--:-- 722
{
"name": "show",
"id": "1",
"photo": {
"id": 1,
"photo_name": "laravel",
"photo_size": 1024,
"photo_url": "https://laravel.com/img/logotype.min.svg",
"photo_status": "active",
"photo_date": "2020-10-06 10:32:24",
"created_at": "2020-10-06T10:32:24.000000Z",
"updated_at": "2020-10-06T10:32:24.000000Z"
}
}
/* fetch photo by id */
$ curl localhost:8000/api/photos/1/edit | json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 286 0 286 0 0 709 0 --:--:-- --:--:-- --:--:-- 709
{
"name": "edit",
"id": "1",
"photo": {
"id": 1,
"photo_name": "laravel",
"photo_size": 1024,
"photo_url": "https://laravel.com/img/logotype.min.svg",
"photo_status": "active",
"photo_date": "2020-10-06 10:32:24",
"created_at": "2020-10-06T10:32:24.000000Z",
"updated_at": "2020-10-06T10:32:24.000000Z"
}
}
/* fetch photo by id for edit */
$ curl -X PATCH -H "Content-Type: application/json" -d "{\"id\":1,\"photo_name\":\"laravel patch\",\"photo_size\":2048,\"photo_url\":\"https://laravel.com/img/logotype.min.svg\",\"photo_status\":\"active\",\"photo_date\":\"2020-10-06 10:24:01\"}" http://127.0.0.1:8000/api/photos/1 | json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 393 0 224 100 169 1108 836 --:--:-- --:--:-- --:--:-- 1945
{
"name": "update",
"status": true,
"payload": {
"id": 1,
"photo_name": "laravel patch",
"photo_size": 2048,
"photo_url": "https://laravel.com/img/logotype.min.svg",
"photo_status": "active",
"photo_date": "2020-10-06 10:24:01"
},
"id": "1"
}
/* patch photo with payload */
$ curl localhost:8000/api/photos/1 | json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 292 0 292 0 0 707 0 --:--:-- --:--:-- --:--:-- 705
{
"name": "show",
"id": "1",
"photo": {
"id": 1,
"photo_name": "laravel patch",
"photo_size": 2048,
"photo_url": "https://laravel.com/img/logotype.min.svg",
"photo_status": "active",
"photo_date": "2020-10-06 10:36:22",
"created_at": "2020-10-06T10:32:24.000000Z",
"updated_at": "2020-10-06T10:36:22.000000Z"
}
}
curl -X DELETE http://127.0.0.1:8000/api/photos/1 | json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 41 0 41 0 0 221 0 --:--:-- --:--:-- --:--:-- 221
{
"name": "destroy",
"status": true,
"id": "1"
}
/* delete photo by id */
laravel สร้าง generate /app/Http/Controllers/PhotoController.php ภายในไฟล์จะมีการสร้าง function RESTful template มาให้
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PhotoController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
มาทำความรู้จักการทำงานแต่ละ function มามีการทำงานอย่างไร ตามการอธิบายจากตารางนี้
implement PhotoController ตาม function การทำงานเพื่อใช้ตรวจสอบการ call จาก REST client
ผมจะเพิ่ม function response()->json(); เพื่อทำการ return http response คืนค่ากลับไปในรูปแบบ application/json format
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PhotoController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return response()->json(['name' => 'index']);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return response()->json(['name' => 'create']);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
return response()->json(['name' => 'store', 'payload' => $request->all()]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
return response()->json(['name' => 'show', 'id' => $id]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
return response()->json(['name' => 'edit', 'id' => $id]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
return response()->json(['name' => 'update', 'payload' => $request->all(), 'id' => $id]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
return response()->json(['name' => 'destroy', 'id' => $id]);
}
}
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
/**
* Create a new component instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.alert');
}
}