Laravel 筆記

tags: Laravel PHP 學習紀錄 筆記 note

目錄

架構

IOC

DI

權限相關

Gate

  • 在blade 中用 @can@endcan包起來的區塊可以用gate控制權限

Artisan

ARTISAN 命令全攻略

php artisan serve 行為追朔

HTTP

Laravel 技能樹

Polymorphic Relations

CRUD

Delete

Queue

  • Laravel Queues 101: Example with Sending Emails
  • 重點整理
    • php artisan queue:table
      • 產生queue表
    • php artisan migrate
      • 在資料庫產生queue表
    • 在config/queue.php 中把sync改成如下圖
    • send的動作改成queue or later
    • 在.env加入下圖的資訊
      • heroku的話記得要去setting加key、value
    • php artisan queue:work
      • 會持續檢查是否需要執行排程的動作
      • heroku上還不確定怎麼實行
    • 寄信功能 : Gmail有過一陣子就會被擋,需要手動放行可信任裝置的問題

Fail

Collection

public function test() { return $this->paginate(GameReport::get()) ->setPath(url()->current()); } public function paginate($items, $perPage = 15, $page = null, $options = []) { $page = $page ?: (Paginator::resolveCurrentPage() ?: 1); $items = $items instanceof Collection ? $items : Collection::make($items); return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options); }

Eloquent

hasManyThrough

many to many 過程紀錄

狀況

  • 夢幻模擬戰的 使用者-英雄-陣營 發現是多對多的狀況

參考資料

流程簡述

  • 建立要建立的關連的table,在此例中 使用者-英雄-陣營 需要5張表
  • 除了基本的三張表外,還需要紀錄 使用者-英雄 & 英雄-陣營 關係的兩張表,這種中間表在laravel 是使用pivot來稱呼
  • 關連設定圖
  • pivot table 新增、讀取的方法圖

郵件驗證(Email Verification)

Validation

Middleware

Observer

  • 可在Model::create時自動添加東西
  • 要在AppServiceProvider.php 中的 boot() 內做添加

Translation

JWT

  • Json Web Token
  • HackMD
  • 鐵人賽文章
  • 鐵人賽文章
  • 優點
    • 無狀態的傳輸適用於 RESTful API 的設計
    • 不需要 cookie
    • 相較於 Session 所消耗的伺服器效能來得小
    • 由於為無狀態輸出,減少 CSRF 攻擊的可能性
    • 輸出檔案為 JSON,在各類終端皆支援其格式
    • 主機端拿到 token 後不需要再去查詢使用者的訊息,適合用於微服務
  • 缺點
    • Token 被拿走,你的身份就會被盜用,這是 JWT 最大的缺點。

Laravel Session

  • Session 該注意事項
    • Laravel Session 並不是使用 PHP Native Session
    • Laravel 是透過 Middleware 實作 Session 機制

他人筆記

好用套件

Dependency Injection

API該有的內容

152 Laravel Tips About Everything

helpers

設定

好用helpers

8+版本

Collection

Sanctum

Guard

  • 可用於避免在後台登入時,前台也登入的窘境
  • 參考網站

Sail

  • 在 linux 可以用以下指令安裝
    1. curl -s https://laravel.build/CUSTOMPROJECTNAME | bash
    2. 目前正在 wsl 環境下測試能否正常使用
    3. 在 wsl 環境直接使用 1 的指令可以快速安裝 laravel sail
    4. 安裝完後(第一次有點久)使用 cd CUSTOMPROJECTNAME && ./vendor/bin/sail up 指令可快速啟動 laravel 專案

Laradock

php-worker

Get Real With Laravel Echo

Sanctum

API 對接

Auth

相關實用文章

Auth::id()

  • 稍微解釋 Auth::id() 的運作過程

如何正確在 Laravel 撰寫 PHPUnit 單元測試(Unit Test)

品質檢測

Swagger API 文件

[教程] 在不同的 Laravel 应用中提供(服务端)和使用(客户端) OAuth2 认证

圖片處理

準備

需要的東西 來源二

實作內容

  • 要求 php 要有 gd extension
  • 目前完成接收前端傳進來的圖片 resize
  • (待修改)圖片儲存的方式是 gd 的方式,不便於檔案移動、刪除
<?php

namespace App\Http\Controllers\Apis;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Image;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class UploadImageController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'image' => 'required|image',
        ]);

        // 將圖片轉換成 base64
        $base64 = file_get_contents(data_get($validated, 'image')->path());
        // 將 base64 轉換成 GD class
        $image = imagecreatefromstring($base64);
        // 取得原始寬高
        $originWidth = imagesx($image);
        $originHeight = imagesy($image);
        // 在此控制 resize 的圖片要多寬
        $width = 300;
        // 控制高度為原始比例
        $height = round($width * $originHeight / $originWidth);
        // 使用 imagecreatetruecolor() 函數生成一個新的圖片。另一種寫法 $resizedImage = imagescale($image, $width)
        $resizedImage = imagecreatetruecolor($width, $height);
        // 使用 imagecopyresampled() 函數將原始圖片縮放到指定大小
        imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $width, $height, $originWidth, $originHeight);
        // 生成新的圖片名稱
        $name = uniqid() . '.png';
        // 生成圖片的完整路徑
        $fullPath = storage_path('app/public/' . $name);
        // 使用 imagepng() 函數將縮放後的圖片存儲到本地存儲空間中
        imagepng($resizedImage, $fullPath);
        // 生成給前端使用的 url
        $imaPath = asset('storage/' . $name);

        return response()->json(['image' => $imaPath]);
    }
}

爬蟲 未完成

<?php

use App\Http\Controllers\NoteController;
use App\Models\Image;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Symfony\Component\DomCrawler\Crawler;
use Carbon\Carbon;

Route::get('/test', function () {
    // 設定 PTT 的網址和板名
    $url = 'https://www.ptt.cc/bbs/C_Chat/M.1536493373.A.1D6.html';
    $board = 'C_Chat';

    // 從 PTT 獲取文章內容
    $response = Http::withOptions(['verify' => false])
        ->get($url);
    $html = $response->body();

    // 解析 HTML,並取得文章標題、作者、時間和內文
    $crawler = new Crawler($html);
    return $crawler->text();
    $title = $crawler->filter('.article-meta .article-meta-tag')->eq(2)->text();
    $author = $crawler->filter('.article-meta .article-meta-value')->eq(0)->text();
    $time_str = $crawler->filter('.article-meta .article-meta-value')->eq(3)->text();
    $time = Carbon::parse(Str::after($time_str, ' '));
    $content = $crawler->filter('#main-content')->text();
    $content = Str::before($content, '--');

    $result = [
        'board' => $board,
        'title' => $title,
        'author' => $author,
        'time' => $time,
        'content' => $content
    ];

    return $result;
    // // 儲存文章到資料庫
    // $post = new Post;
    // $post->board = $board;
    // $post->title = $title;
    // $post->author = $author;
    // $post->published_at = $time;
    // $post->content = $content;
    // $post->save();
});

Socialite

Laravel Socialite 簡單的代價

websocket

大佛十多年前的 ws 鐵人文章

chat 參考

CORS

講解的挺詳細的文章

Laravel ORM 分表查询

  • 分表的參考資料

Laradock Elasticsearch

在Laravel项目中使用Elasticsearch

好用的片段程式碼

在 laravel 中取得 DB 的名稱 & 註解

  • 對於前人開的表落落長的狀況,使用整理好的方式呈現需要的資訊
$temp = [];

$tableName = 'p30_entertainment_wallet_stored';

$columnComments = DB::select("SELECT COLUMN_NAME, COLUMN_COMMENT
                      FROM information_schema.COLUMNS
                      WHERE TABLE_NAME = ?", [$tableName]);

foreach ($columnComments as $column) {
    $columnName = $column->COLUMN_NAME;
    $columnComment = $column->COLUMN_COMMENT;

    $temp[] = [
        $columnName,
        $columnComment
    ];
}

return $temp;