2021年1月31日 星期日

套件fruitcake/laravel-cors設定API允許跨網域請求

 *套件fruitcake/laravel-cors設定API允許跨網域請求:

1.安裝套件fruitcake/laravel-cors
(laravel 8 預設就有安裝,不須再安裝)
composer require fruitcake/laravel-cors

2.產生config檔:
(產生的檔案在 config/cors.php)
(laravel 8 預設就有,不須再產生)
php artisan vendor:publish --tag="cors"

3.使用fruitcake/laravel-cors

*設定 app/Http/Kernel.php
(laravel 8 預設就有設定,不須再設定)

protected $middleware = [
  \Fruitcake\Cors\HandleCors::class,
  ...
];

*設定 config/cors.php

// paths 加入 'oauth/*',才能"跨網域"請求 passport 的 access_token
'paths' => ['api/*', 'oauth/*', 'sanctum/csrf-cookie'],

---------------------------------
參考資料:

fruitcake/laravel-cors
https://github.com/fruitcake/laravel-cors

 

測試 "不同網域" 請求api的方法

 *測試 "不同網域" 請求api的方法:

1.進入
https://api.jquery.com/

2.打開瀏覽器的console(主控台)輸入:
(ajax的url為api網址)

$.ajax({
  url: 'http://localhost/animal/public/api/news'
}).done(function(data) {
  console.log(data);
});

=============================================

$.ajax({
  type: 'POST',
  url: 'http://localhost/animal/public/oauth/token',
  data: {grant_type: 'password', client_id: '2', client_secret: 'bKT4uk7TGKrih4FGTlt01fdbpPc6f1B2Ry4j', username: 'arc99@gmail.com', password: 'aaa1234', scopes: ''},
  success: function(msg) {
    alert('Data Saved: ' + msg);
  }
});

=============================================

jQuery Ajax
https://www.fooish.com/jquery/ajax.html

 


2021年1月25日 星期一

laravel 多檔案上傳

laravel 多檔案上傳

============================================================
*資料庫:
news
news_file

*laravel 檔案:
model
migration
controller
route

*postman:
title
content
photo (單一檔案)
file[] (多個檔案)(使用陣列)

============================================================
*資料庫:

news:

id            int auto key
title        vc
content        text
photo        vc

migration:

$table->id();
$table->string('title');
$table->text('content');
$table->string('photo');
$table->timestamps();

--------------------------------
news_file:

id            int auto key
news_id        int
file_name    vc                檔案名稱
org_name    vc                檔案原始名稱

migration:

$table->id();
$table->unsignedBigInteger('news_id');
$table->string('file_name');
$table->string('org_name');
$table->timestamps();

============================================================
*laravel 檔案:

model
migration
controller

route

--------------------------------
php artisan make:model news -rmc

--------------------------------
route:

use App\Http\Controllers\NewsController;

Route::apiResource('news', NewsController::class);

php artisan route:list

============================================================
*新增

| POST | api/news | news.store | App\Http\Controllers\NewsController@store | api |

POST

http://localhost/animal/public/api/news

============================================================
app\Models\news.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class news extends Model
{
    use HasFactory;

    //可以被批量寫入的屬性
    protected $fillable = [
        'title',
        'content',
        'photo',
    ];
}

============================================================
app\Models\news_file.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class news_file extends Model
{
    use HasFactory;

    //可以被批量寫入的屬性
    protected $fillable = [
        'news_id',
        'file_name',
        'org_name',
    ];
}

============================================================
*多檔上傳:

1.把檔案儲存到uploads資料夾

2.把檔案資料儲存到: 資料表 news_file
news_id
file_name
org_name

3.回傳資料

============================================================
app\Http\Controllers\NewsController.php

<?php

namespace App\Http\Controllers;

use App\Models\news;
use App\Models\news_file;
use Illuminate\Http\Request;

class NewsController extends Controller
{
    //新增
    public function store(Request $request)
    {   
        //-----------------------------------------
        //資料驗證
        $request->validate([
            'photo' => 'required|mimes:jpg,png,gif,jpeg|max:2048', //圖檔
            'file[]' => 'mimes:csv,txt,xlx,xls,pdf|max:2048', //檔案
        ]);
        
        if($request->file()) {
            //photo檔案資料
            $file = $request->file('photo');
            $datax = 'File Name: ' . $file->getClientOriginalName(); // SplitShire-0164-1024x683.jpg
            $datax = 'File Extension: ' . $file->getClientOriginalExtension(); // jpg
            $datax = 'File Real Path: '.$file->getRealPath(); // C:\wamp64\tmp\php17E8.tmp
            $datax = 'File Size: '.$file->getSize(); // 201256 (單位為 byte) (201256 / 1024 = 196 kbyte)
            $datax = 'File Mime Type: '.$file->getMimeType(); // image/jpeg
            // return $datax;
            
            //儲存圖檔到 uploads 資料夾
            $destinationPath = 'uploads';
            $fileName = time() . '_' . $file->getClientOriginalName();
            $file->move($destinationPath, $fileName);

            //新增資料到資料庫
            // $data = News::create($request->all());
            $data = News::create([
                'title' => $request->title,
                'content' => $request->content,
                'photo' => $fileName,
            ]);

            $data = $data->refresh(); //再查詢一次資料庫

            //多檔案上傳-----------------------------------------
            if($request->hasFile('file'))
            {
                $files = $request->file('file');

                foreach ($files as $file){
                    //儲存圖檔到 uploads 資料夾
                    $destinationPath = 'uploads';
                    $originalName = $file->getClientOriginalName();
                    $fileName = time() . '_' . $originalName;
                    $file->move($destinationPath, $fileName);

                    //把檔案資料儲存到: 資料表 news_file
                    $filex = news_file::create([
                        'news_id' => $data->id,
                        'file_name' => $fileName,
                        'org_name' => $originalName,
                    ]);
                }

                $filex = news_file::where('news_id', $data->id)
                        ->orderBy('id')
                        ->get();
            }


            return response()->json([
                'status' => 'success',
                'message' => '新增成功',
                'data' => $data,
                'file' => $filex,
            ]);
        }
    }
}

============================================================
*回傳資料:

{
    "status": "success",
    "message": "新增成功",
    "data": {
        "id": 14,
        "title": "title001",
        "content": "content001",
        "photo": "1611499727_SplitShire-0164-1024x683.jpg",
        "created_at": "2021-01-24T14:48:48.000000Z",
        "updated_at": "2021-01-24T14:48:48.000000Z"
    },
    "file": [
        {
            "id": 12,
            "news_id": 14,
            "file_name": "1611499729_網站規劃.pdf",
            "org_name": "網站規劃.pdf",
            "created_at": "2021-01-24T14:48:49.000000Z",
            "updated_at": "2021-01-24T14:48:49.000000Z"
        },
        {
            "id": 13,
            "news_id": 14,
            "file_name": "1611499729_test001.txt",
            "org_name": "test001.txt",
            "created_at": "2021-01-24T14:48:49.000000Z",
            "updated_at": "2021-01-24T14:48:49.000000Z"
        }
    ]
}

============================================================


2021年1月22日 星期五

laravel

URL Generation
https://laravel.com/docs/8.x/urls

url()->previous();

laravel获取当前的url以及当前的基础域名方法汇总
https://blog.csdn.net/zhezhebie/article/details/81701256

--------------------------------------
Arrays in JSON Objects
https://www.w3schools.com/js/js_json_arrays.asp

{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}

x = myObj.cars[0];

--------------------------------------
laravel 多檔案上傳

https://learnku.com/articles/50553

https://www.lagagain.com/post/30%E5%A4%A9%E6%88%90%E7%88%B2laravel%E8%90%8C%E6%96%B0%E7%AC%AC28%E5%A4%A9-%E4%B8%8A%E5%82%B3%E6%AA%94%E6%A1%88/

https://t.codebug.vip/questions-1988374.htm

https://gist.github.com/winwu/b5dd3076311962227fd2

http://hk.uwenku.com/question/p-aoucnslq-bka.html

http://hk.uwenku.com/question/p-ahpdfrov-hv.html

https://iter01.com/540694.html

2021年1月14日 星期四

API分頁

API分頁:

GET
/api/topics?limit=10&page=3

TopicController.php

public function index(Request $request)
{
    //設定預設值 $request->limit
    $limit = $request->limit ?? 10; //未設定預設值為10
    
    //使用Model orderBy方法加入SQL語法排序條件,依照id由大到小排序
    $topics = Topic::orderBy('id', 'desc')
        ->paginate($limit) //使用分頁方法,最多回傳$limit筆資料
        ->appends($request->query());
        
    return response($topics, Response::HTTP_OK);
}