0%

Laravel 筆記

源自網路上教學

Route

選擇性接收參數
1
2
3
Route::get('/test/{name?}', function ($ifblank = 'test') {
return $ifblank;
});
限制參數格式
1
2
3
4
5
6
7
8
Route::pattern('id', '[0-9]+');
Route::get('/te/{id}', function ($id) {
return $id;
});
// OR
Route::get('/te/{id}', function ($id) {
return $id;
})->where('id', '[0-9]+');
Named Route
1
2
3
4
Route::get('post/{id}', ['as' => 'posts.show', function(){
}]);
and we cau use route() helper fnuc
<a href="{{ route('posts.show', $id) }}"></a>
Prefixing Route
1
2
3
4
5
Route::group(['prefix' => 'admin'], function(){
Route::get('users', function(){
// 實際上的 URL 會是 "/admin/users"
});
});

View

1
2
3
{{-- 不會被解析的註解 --}}
{{ "<div>123</div>" }} 解析前會先跳脫 => 123
{!! "<div>123</div>" !!} 不會跳脫,可印HTML => <div>123</div>
1
2
<a href="{{ route('home.index') }}">回首頁</a>
<img src="{{ asset('img/logo.png') }}">

Migration

為確保版本控制的內容是無誤的,在將Migration 送進版本控制之前,要先測試一下 rollback 的動作是不是正確無誤,以防止真的需要回溯時無法正確的回復到先前的狀態千萬別偷懶不寫 down 動作,或是沒有測試 rollback
php artisan migrate:rollback
一旦將 migration 檔放入版本控制並 push 出去後,就不可以再修改 migration 檔裡的內容,以免造成其他人的不同步或錯誤。若因有誤而需要修改資料庫的狀況時,應該再建立新的 migration 來變更資料庫

  • 在輸入 migration 名稱時打錯字怎麼辦?

    1. php artisan migrate:rollback
    2. 重新命名 Class 名稱及檔案名稱
    3. composer dump-autoloadphp artisan migrate
    4. 把產生出來的檔案手動刪除掉、資料庫內資料表砍掉,再重新產生一次
      PS:why composer dumpautoload? 因為 database 資料夾使用 classmap 來載入。只有在打了 composer dumpautoload 之後 composer 才會更新 autoload_classmap(vendor\composer\autoload_classmap.php) 的内容。
  • 不小心把 migrations 資料表弄壞、或是弄亂無法復原時怎麼辦?

    1. php artisan migrate:reset
    2. 把所有資料表全部手動刪除
    3. php artisan migrate

Debug

1
2
3
$QAQ=123;
var_dump($QAQ);
dd($QAQ); // 推薦用

Controller

Laravel 5.2
$ php artisan make:controller TestsController不會自幫我們產生 RESTful 的方法了
$ php artisan make:controller TestsController --resource這樣才會

RESTful
1
2
3
4
5
6
7
8
動詞 路徑 行為 路由名稱
GET /photo index photo.index
GET /photo/create create photo.create
POST /photo store photo.store
GET /photo/{photo} show photo.show
GET /photo/{photo}/edit edit photo.edit
PUT/PATCH /photo/{photo} update photo.update
DELETE /photo/{photo} destroy photo.destroy
慣例優於設定
1
2
3
4
5
6
Route::resource('photo', 'PhotoController', ['only' => [
'index', 'show'
]]);
Route::resource('photo', 'PhotoController', ['except' => [
'create', 'store', 'update', 'destroy'
]]);
存完跳回去存的
1
2
3
4
public function store(Request $request){
...
return redirect()‐>route('posts.show', $post‐>id);
}

好用的Carbon API
$message->created_at->toDateTimeString();

分頁簡單
$messages = Message::orderBy('created_at','desc')->paginate(11);

Model錯誤處理

return 404
1
2
3
4
5
6
7
public function show($id)
{
$post = \App\Post::find($id);
if(is_null($post)){
abort(404);
}
}

$post=\App\Post::findOrFail($id);

Session
1
2
3
4
5
6
7
8
9
10
11
12
public function show($id)
{
$post = \App\Post::find($id);
if(is_null($post)){
return redirect()‐>route('posts.index')->with('message','找不到該⽂文章');
}
}
@if(session('message'))
...
{{ session('message') }}
@endif