Laravel 雜 (將內容丟到相關的文章) - fantasy0107/notes GitHub Wiki
語系設定變數
//resources/lang/zh-tw/auth.php
return [
...
'string1' => 'Welcome :user, Please meet :other',
]
//使用helper - trans('語系檔key', [帶入的變數(需與語系檔變數名稱一樣) => 值])
trans('string1', [ 'user' => 'Ainsley', 'other' => 'Hayden' ]);
Laravel Helpers to Make Your Life Easier - 筆記
data_get()
取得陣列或物件的資料, 用 .(dot) 或 *(wildcard)
data_get($array|$object, $key, default_value_if_not_found);
$array = ['albums' => ['rock' => ['count' => 75]]];
$count = data_get($array, 'albums.rock.count'); // 75
$avgCost = data_get($array, 'albums.rock.avg_cost', 0); // 0
$object->albums->rock->count = 75;
$count = data_get($object, 'albums.rock.count'); // 75
$avgCost = data_get($object, 'albums.rock.avg_cost', 0); // 0
$array = ['albums' => ['rock' => ['count' => 75], 'punk' => ['count' => 12]]];
$counts = data_get($array, 'albums.*.count'); // [75, 12]
optional
允許你存取properties或呼叫methods在一個物件上
當物件是null時會出現錯誤, 但這個helper function會丟出null而非錯誤
// User 1 exists, with account
$user1 = User::find(1);
$accountId = $user1->account->id; // 123
// User 2 exists, without account
$user2 = User::find(2);
$accountId = $user2->account->id; // PHP Error: Trying to get property of non-object
// Fix without optional()
$accountId = $user2->account ? $user2->account->id : null; // null
$accountId = $user2->account->id ?? null; // null
// Fix with optional()
$accountId = optional($user2->account)->id; // null
用Laravel開發API簡易流程
產生 controller
php artisan make:controller UserController --resource
Controller
先寫一個method用dd印出訊息
public function getUser(Request $request)
{
dd('api');
}
controller method的動詞用laravel的Resource範例 https://laravel.com/docs/5.5/controllers#resource-controllers
Route
用http method來顯示你要做的事情
get -> 取得資源(index/show)
post -> 新增資源(store)
put -> 更新資源全部內容(update)
patch -> 更新資源部分內容(update)
deletet ->刪除資源(destroy)
Route::get('/users/1', 'UserController@getUser');
多個字就用-表示
Route::get('user-tags', 'ApiController@getTags');
每個URI代表資源的名稱或者Table的名稱也就是說只能是名詞複數
//範例
- GET /api/files/ 得到所有檔案
- GET /api/files/1/ 得到檔案 ID 為 1 的檔案
- POST /api/files/ 新增一個檔案
- PUT /api/files/1/ 更新 ID 為 1 的檔案
- PATCH /api/files/1/ 更新 ID 為 1 的部分檔案內容
- DELETE /api/files/1/ 刪除 ID 為 1 的檔案
第一個版本的API
接下來就是將相關的邏輯補完
public function getUser(Request $request)
{
...
}
遵守PSR2
status code
- 200 OK 用於請求成功 。GET 檔案成功,PUT, PATCH 更新成功
- 201 Created 用於請求 POST 成功建立資料。
- 204 No Content 用於請求 DELETE 成功。
- 400 Bad Request 用於請求 API 參數不正確的情況,例如傳入的 JSON 格式錯誤。
- 401 Unauthorized 用於表示請求的 API 缺少身份驗證資訊。
- 403 Forbidden 用於表示該資源不允許特定用戶訪問。
- 404 Not Found 用於表示請求一個不存在的資源。
Searching, sorting, filtering and pagination
Sorting
GET /companies?sort=rank_asc
Filtering
GET /companies?category=banking&location=india
Searching
GET /companies?search=Digital Mckinsey
Pagination
GET /companies?page=23
Versioning
http://api.yourservice.com/v1/companies/34/employees
Test
Postman - 邊開發邊測試
PHPUnit - 方便以後知道那些API壞掉
覆蓋率可以知道哪些地方沒有執行到
Swagger - 提供給前端工程師知道有哪些API
在正式網站上試試看
重構 - Clean Code相關概念
可以參考一下別人整理的Clean code筆記
排版
變數
比較
方法
SOLID
Dont repeat yourself
參考
本地端部屬Laravel
安裝laravel的套件
composer global require "laravel/installer"
建立新的laravel
laravel new LaravelProjectName
apache\conf\extra\httpd-vhosts
<VirtualHost *:80>
ServerAdmin A
DocumentRoot "C:\xampp\htdocs\ProjectName\public"
ServerName ProjectName.site.app
</VirtualHost>
C:\WINDOWS\system32\drivers\etc\hosts
...
127.0.0.1 ProjectName.site.app
...
advanced Eloquent search query filters
Endpoint
Route::post('/search', 'SearchController@filter');
Payload
payload意思即為承載量,在開發中則是指出在一堆資料中我們所關心的部分!
{
"name": "Billy",
"company": "Google",
"city": "London",
"event": "key-note-presentation-new-york-05-2016",
"responded": true,
"response": "I will be attending",
"managers": [
"Tom Jones",
"Joe Bloggs"
]
}
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Search\UserSearch;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SearchController extends Controller
{
public function filter(Request $request)
{
return UserSearch::apply($request);
}
}
第一版 - 單一條件搜尋
只能根據一個條件去做搜尋 缺點是不知道要從哪個條件開始比較好
public function filter(Request $request, User $user)
{
// Search for a user based on their name.
if ($request->has('name')) {
return $user->where('name', $request->input('name'))->get();
}
.......
return User::all();
}
第二版本 - 多重條件搜尋
public function filter(Request $request, User $user)
{
$user = $user->newQuery();
// Search for a user based on their name.
if ($request->has('name')) {
$user->where('name', $request->input('name'));
}
// Search for a user based on their company.
if ($request->has('company')) {
$user->where('company', $request->input('company'));
}
// Search for a user based on their city.
if ($request->has('city')) {
$user->where('city', $request->input('city'));
}
// Continue for all of the filters.
// Get the results and return them.
return $user->get();
}
第三版本 - 多重條件 + 關聯搜尋
$user = $user->newQuery();
// Search for a user based on their name.
if ($request->has('name')) {
$user->where('name', $request->input('name'));
}
// Search for a user based on their company.
if ($request->has('company')) {
$user->where('company', $request->input('company'));
}
// Search for a user based on their city.
if ($request->has('city')) {
$user->where('city', $request->input('city'));
}
// Only return users who are assigned
// to the given sales manager(s).
if ($request->has('managers')) {
$user->whereHas('managers', function ($query) use ($request) {
$query->whereIn('managers.name', $request->input('managers'));
});
}
// Has an 'event' parameter been provided?
if ($request->has('event')) {
// Only return users who have
// been invited to the event.
$user->whereHas('rsvp.event', function ($query) use ($request) {
$query->where('event.slug', $request->input('event'));
});
// Only return users who have responded
// to the invitation (with any type of
// response).
if ($request->has('responded')) {
$user->whereHas('rsvp', function ($query) use ($request) {
$query->whereNotNull('responded_at');
});
}
// Only return users who have responded
// to the invitation with a specific
// response.
if ($request->has('response')) {
$user->whereHas('rsvp', function ($query) use ($request) {
$query->where('response', 'I will be attending');
});
}
}
// Get the results and return them.
return $user->get();
參考
Writing advanced Eloquent search query filters
在Ubuntu上佈署Laravel
PHP
sudo apt-get install php
更新repositories
apt-get update
安裝ngix
sudo apt-get install nginx
移除apache
sudo apt-get remove apache2*
覆蓋apache 預測頁面
mv /var/www/html/index.nginx-debian.html /var/www/html/index.html
安裝mysql server
apt-get install mysql-server
安裝git
sudo apt-get install git
安裝composer
curl -sS https://getcomposer.org/installer | php
將 Composer 執行檔移到系統預設的環境變數路徑
sudo mv composer.phar /usr/bin/composer
新增 /var/www/.ssh 的目錄
mkdir /var/www/.ssh
把 /var/www/.ssh 的目錄權限改為 www-data:www-data
chown www-data:www-data /var/www/.ssh
切換使用者至 www-data
sudo su
su -s /bin/bash www-data
先檢查有沒有在使用的 SSH key
ls -al ~/.ssh
安裝laravel
sudo composer create-project laravel/laravel your-project --prefer-dist