# 偷偷告訴你 ###### tags: `補充` 老師筆記集散地 https://hackmd.io/@Monastery # Laravel 從入門到放棄 @小生生 ###### tags: `Laravel` `初學者` ## 安裝環境 [xampp](https://www.apachefriends.org/xampp-files/7.4.8/xampp-windows-x64-7.4.8-0-VC15-installer.exe) [composer](https://getcomposer.org/Composer-Setup.exe) [node](https://nodejs.org/en/) [HeidiSQL](https://www.heidisql.com/installers/HeidiSQL_11.0.0.5919_Setup.exe) [VScode](https://code.visualstudio.com/docs/?dv=win) ### VScode 套件 #### Power Mode!!!!!! * PHP Extension Pack * Laravel Extension Pack * PHP Namespace Resolver * Material Icon Theme * Prettier - Code formatter ### 安裝 laravel 使用vscode開啟欲放置專案之資料夾,開啟terminal輸入指令安裝laravel ```php= composer global require laravel/installer ``` ![](https://i.imgur.com/FFOh1Ip.png) ### 建立專案 安裝完成 laravel 後,輸入指令建立專案 project_name 為專案名稱可更換 ```php= composer create-project --prefer-dist laravel/laravel project_name "7.*" ``` ![](https://i.imgur.com/kMMZoCk.png) #### 需確認 php 版本符合 laravel 版本,可至官網查詢環境設定,否則會出現如下錯誤 ![](https://i.imgur.com/BWg9m5O.png) ### 進入資料夾 將 VScode 資料夾指定至剛建立的專案,如圖 ![](https://i.imgur.com/0txDu9F.png) ### 安裝composer及npm相關套件 在 terminal 輸入指令 ``` composer install npm install ``` ## 與資料庫建立連線 ### 1. 開啟XAMPP 啟動 My SQL ![](https://i.imgur.com/lMbZ6HG.png) ### 2. 開啟HeidSQL 建立連線資料環境 ![](https://i.imgur.com/S4IkNqH.png) 建立新資料庫 ![](https://i.imgur.com/4YO8xQq.png) ### 3. 更改.env設定 將 DB_DATABASE 改成剛剛新建立的資料庫名稱 ``` DB_DATABASE="資料庫名稱" ``` ![](https://i.imgur.com/WUCjUZP.png) ### 4. 啟動serve 輸入 ``` php artisan serve ``` ## 設定Controller [參見](https://laravel.com/docs/6.x/controllers#introduction) 在 web.php 檔案內設定路徑時,為了保持程式碼乾淨, 會將資料庫連線指令、商業邏輯寫在另外的 Controllers 內 ### 1. 新增controller ``` php artisan make:controller {Controller名稱} --invokable ``` 新增一個 FrontController 及一個 BackController >Controller 放置路徑為 app/Http/Controllers ### 2. 設定controller ``` public function index() { return view('index'); } ``` ### 3. 設定view路徑 ``` Route::get('/', 'FrontController@index'); Route::get('about', 'FrontController@about'); ``` ## 建立會員系統 [參見](https://laravel.com/docs/6.x/authentication) ### 1. 安裝routing 安裝 auth ``` composer require laravel/ui "^2.0" php artisan ui vue --auth npm install npm run dev npm run watch ``` ### 2. 建立資料表 ``` php artisan migrate ``` ### 3. 修改routes 將 routes/web.php 檔案內的`Auth::routes();` 註解 這段程式碼將許多 function 包起來(如login、register), 為了後續能自由調用這些 function,將其改成完整程式碼 ``` // Authentication Routes... Route::get('login', 'Auth\LoginController@showLoginForm')->name('login'); Route::post('login', 'Auth\LoginController@login'); Route::post('logout', 'Auth\LoginController@logout')->name('logout'); // Registration Routes... Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register'); Route::post('register', 'Auth\RegisterController@register'); // Password Reset Routes... Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm'); Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail'); Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm'); Route::post('password/reset', 'Auth\ResetPasswordController@reset'); ``` 之後在資料庫中即可看到剛剛新增的會員資料表 ![](https://i.imgur.com/SIguRZw.png) ## 操作資料表 [參見](https://laravel.com/docs/7.x/migrations) 通常不會直接操作資料庫軟體來新增資料表, 而是透過 laravel 內建的 `migrations` 進行操作, `migrations`是一種資料庫的版本控制,讓團隊能輕鬆的修改跟共享資料庫結構 ### 新增資料表 ``` php artisan make:migration create_{資料表名稱}_table ``` 每當新增完成資料表,需要輸入指令啟動它 ``` php artisan migrate ``` > 要注意每次新增`migration`後 `migrate` 只能跑一次 > 並且會在資料庫內新增跑過該筆資料的紀錄 > 無法再去 > ![](https://i.imgur.com/zVwTcNi.png) ### 新增資料欄位 要新增料欄位時,不會直接從資料庫內新增, 而是針對某張資料表新增 migration: ``` php artisan make:migration add_votes_to_users_table --table=users ``` 接著新增新的資料欄位 ``` public function up() { Schema::table('users', function (Blueprint $table) { $table->string('title', 200); }); } ``` ### 修改資料欄位 要修改資料欄位,首先要安裝: ``` composer require doctrine/dbal ``` 接著一樣針對某張資料表新增 migration, 修改指定資料表內的資料欄位: ``` public function up() { Schema::table('news', function (Blueprint $table) { $table->string('title', 50)->nullable()->change(); }); } ``` ### 刪除資料表 要刪除資料表,可以使用`drop`或`dropIfExists` 同樣的要先針對某張資料表新增 migration, ``` php artisan make:migration drop_blog_table ``` 接著輸入`drop`或`dropIfExists`刪指定資料表 ``` Schema::drop('users'); Schema::dropIfExists('users'); ``` ### 清空資料庫 清空資料庫內 migration 紀錄,但存在資料夾內的不會受影響 ``` php artisan migrate:reset ``` 清除所有的 migration 並重新執行有修改過的欄位 ``` php artisan migrate:refresh ``` ## 取得資料庫資料 在 controller 內與資料庫建立連線 引入 `use Illuminate\Support\Facades\DB;` ### 取得單筆資料 宣告變數取得該資料表 接著透過 compact 回傳 ``` public function news() { $news = DB::table('news')->get(); return view('news', compact('news')); } ``` ### 取得多筆資料 使用 for loop 在畫面印出每筆資料 ``` @foreach ($news as $mynews) <p>This is user {{ $mynews->id }}</p> @endforeach ``` ## 使用Blade Templates 在製作網站時每一頁的 navbar 以及 footer 都會是一樣的, 因此透過 blade templates 將會重複使用到的做成可重複利用的模板, 通常存放在`resources/views/layout`資料夾內 ### 定義layout頁面布局 ``` <!-- 檔案儲存路徑 resources/views/layouts/front_layout.blade.php --> <html> <head> <title>頁面名稱 - @yield('title')</title> </head> <body> <div class="container"> @yield('content') </div> </body> </html> ``` ### 使用定義好的 layout 頁面 在上半部我們定義了 front_layout 檔案, 緊接著要使用這支檔案,方法如下: ``` <!-- 儲存於 resources/views/index.blade.php --> <!-- 首先 extends 檔案 --> @extends('front_layout') @section('title', '頁面標題') @section('content') <p>這是我的主要內容。</p> @endsection ``` ## 使用 Route 傳遞參數 這邊我們要實作動態產生產品內頁, 透過帶入產品 ID [參見](https://laravel.com/docs/6.x/routing#route-parameters) ### 設定 Route 路徑 使用 Required Parameters 帶入產品 ID ``` Route::get('/product/{id}', 'FrontController@product_detail'); ``` ### 設定 Controller 在 function 內帶入 `$id` 透過 `where` 找到資料表符合 id 的資料 ``` public function product_detail($id) { // 這裡注意原本 ->get() 會取得所有資料,要將它改成 ->first() 才會抓出一筆資料 $rabbit = DB::table('products')->where('id', $id)->first(); //或是使用 find 的方式也能抓到一筆資料 $rabbit = DB::table('products')->find($id); return view('front.products_datail', compact('rabbit')); } ``` ### 新增 blade.php 因為會帶到新的 products_datail 頁面, 所以在view內產生一支新的 products_datail.blade.php 檔案 由於使用first會將資料轉換成一筆object,所以在引用資料時要指向欄位(id) ``` <div class="container"> <div class="row"> {{ $rabbit->id }} </div> </div> ``` ## 設定 Model [參見](https://laravel.com/docs/6.x/eloquent) ### 新增 Model 首先新增一個 model ``` php artisan make:model model_name ``` > model 放置路徑為 app ### 指定連線資料庫 在類別中定義可以連線的資料 ``` class News extends Model { protected $table = 'news'; } ``` ### 設定可修改的資料 將要修改的欄位儲存在 fillable 內 ``` class News extends Model { protected $table = 'news'; protected $fillable = [ 'title', 'img', 'content', ]; } ``` ### 設定關聯 在 model 寫一個 function 使用時會用到這個 function 名稱 belongsTo 可更換各種關聯方式如: * hasOne 一對一 * hasMany 一對多(父對子) * belongsTo 一對多(子對父) * belongsToMany 多對多 ``` public function camp() { return $this->belongsTo(Camp::class); } ``` ## krlove generator 快速產生 model 所需內容 # SCSS編譯方式 ## 存放路徑 在 laravel 中若要指定路徑的檔案,皆要放在`/public`底下 ## 編譯 SCSS 如果要編譯,則要修改根目錄中的 `webpack.mix.js` 按照原本的範例程式碼進行修改: `.sass('public/css/index.scss', 'public/css');` `.sass('scss的路徑', '編譯後css的路徑');` 接著輸入 `npm run dev` 或是 `npm run watch` 就會編譯 `webpack.mix.js` 中的程式碼 ``` npm run dev *只會跑一次 npm run watch *會一直執行 ``` # 時間格式寫法 ## Carbon > 參閱:https://www.kancloud.cn/kancloud/laravel-5-learning-notes/50163 ### 時間格式(created_at)取 yyyy-mm-dd ``` <?php $dt = \Carbon\Carbon::parse($item->created_at); $data = $dt->toDateString(); ?> ``` https://www.vnewin.com/day13-laravel-restful-api-validation-and-localization/ # 帳號權限寫法 ## 設定帳號權限 首先要在 users 表單內新增一個欄位"role" 預設值給 user 使用內建的 middleware ``` php artisan make:middleware ``` # 圖片壓縮 ## 安裝插件 使用這套插件:[intervention](http://image.intervention.io/) ``` composer require intervention/image ```