# Laravel葵花寶典
:::warning
## php指令
php artisan serve
-ctrl + c
php artisan migrate
php artisan make:migration create_users_table --create="users"
php artisan make:controller ProfileController
php artisan make:model {資料表名稱} --migration -m
:::
---
# Controllers
預設會建立在 app/Http/Controllers 目錄底下
php artisan make:controller ProfileController
建立在 app/Http/Controllers/Admin 目錄
php artisan make:controller Admin/ProfileController
## Migration
### 建立 Migration
$ php artisan make:migration create_users_table --create="users"
Migration 建立之後的檔案會放在 database/migrations/2015_04_11_134630_create_users_table.php
Migration 檔案最前面的日期會依照你建立 Migration 的時間自動產生,所以每個人看到的檔名皆會不同在後面加了 --create 的參數可以告訴 Migration,我們要做建立 user 資料表的動作,檔案內容會像這樣:
```php=
<?php
// database/migrations/2015_04_11_134630_create_users_table.php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/ㄒ
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->timestamp();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
```
## Migration指令
:::success
//列出目前所有 Migration 狀態
php artisan migrate:status
//執行 Migration
php artisan migrate
//恢復上一版本的 Migration
php artisan migrate:rollback
//清除所有版本的 Migration
php artisan migrate:reset
//清除所有版本的 Migration 並重新執行
php artisan migrate:refresh
//建立資料表
php artisan make:migration create_users_table --create="userBase"
//異動資料表欄位資料
php artisan make:migration add_email_to_users_table --table="userBase"
:::
## 資料排序 orderBy
orderBy 針對給定的欄位,將查詢結果排序。
第一個參數為你要用來排序的欄位,第二個參數則控制排序的方向
<font color="#249E13"> ->asc = 正排序</font>
<font color="#249E13"> ->desc =反排序</font>
## array_push
在陣列裡面放資料進去
==必須先把這個變數宣告成陣列==
$array=[];
array_push( 欲增加的陣列, 值)=>array_push(array,value1,value2...)
範例:
```
$a=array("Dog","Cat");
array_push($a,"Horse","Bird");
print_r($a);
輸出結果:Array (Dog ,Cat ,Horse ,Bird)
```
==MyVScode:==
```
public function product() {
$lists = DB::table('todayproducts') ->get();
$discount_price = [];
foreach ($lists as $key =>$value){
array_push($discount_price, round($value->price*$value->discount));
};
return view('front.product.index' ,compact('lists', 'discount_price'));
}
```
==口語化:==
>$lists as $key =>$value =$list as 索引值=>抓到的值
>array_push($discount_price, round($value->price*$value->discount));
>=array_push(折扣後的價格陣列, round=小數點進位(取到的值->金額乘上取到的值->折扣後的價格))
>compact('discount_price')); =將折扣後的價格傳到前端
## 2021/06/15-會員系統 [參考教學]([(https://ithelp.ithome.com.tw/articles/10221406]))
>1. npm install
>2. composer install
>3. composer require laravel/ui "^2.0"
>4. php artisan ui vue --auth
>5. npm install
>6. npm run dev
>7. 改.env檔的資料庫名稱
>8. 利用資料庫軟體 新增與.env檔設定同名的資料庫
>9. php artisan migrate
> 10. php artisan serve
==.env要先更改,在啟動php artisan serve,才會實現資料庫的更改==
連線資料庫之後輸入指令
```
composer require laravel/ui "^2.0"
php artisan ui vue --auth
npm install
npm run dev
```
會出現log in 和 register

執行`php artisan migrate`連結資料庫
匯入指令生成的migration

1. 在資料庫(migration)加入一個新的角色權限= role
2. 加完後重新刷新資料庫(php artisan migrate:refresh)更新項目
3. 到User的model(app/User.php)新增兩個常數
ROLE_ADMIN
ROLE_USER
,並加入剛剛新增的項目
==定義權限使用; php規則宣告常數需大寫==
```php=
const ROLE_ADMIN = 'admin';
const ROLE_USER = 'user';
protected $fillable = [ 'name', 'email', 'password', 'role'
];
```
5. 在RegisterController新增註冊時的預設身分為一般身份(Http/Auth/RegisterController.php)
```php=
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role' => User::ROLE_USER,
]);
```
6. (Providers/AuthServiceProvider.php)
判斷角色權限,將$user的直抓進來和role比對
結果會是Ture/False
public function boot()
```php=
{
$this->registerPolicies();
// 新增 1
Gate::define('admin', function ($user)
{
return $user->role === User::ROLE_ADMIN; // 管理者
});
// 新增 2
Gate::define('user', function ($user)
{
return $user->role === User::ROLE_USER; // 一般身分別
});
}
```
## `Auth::routes();` == 等同於以下這些程式碼,是可以直接使用的
[Auth::routes();解釋參考文章](https://learnku.com/laravel/t/9469/excuse-me-auth-routes-where-do-you-find-the-routes-that-are-extended-in-which-document-is-it-in)
```php=
// 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')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
```
---
### foreach()

---
## 更改登入權限
auth = 登入狀態
can:admin = 角色權限
```php=
Route::middleware('auth','can:admin')
```
必須同時是登入狀態和有角色權限的才可以進入
## 2021/06/16
## 產品關連
<font color="#ddr5a">透過某筆資料身上的id去找到你要的id。</font>
### VScode實作:
==<font color="#FF5E5E">product Type->一對一</font>==
==<font color="#FF5E5E">product->一對多
</font>==
在product Type和product migration裡面新增資料欄位
#### product Type
```php=
public function up()
{
Schema::create('product_types', function (Blueprint $table)
{
$table->id();
$table->string('type_name')->comment('種類名稱');
$table->timestamps();
});
}
```
#### product
```php=
public function up()
{
Schema::create('products', function (Blueprint $table)
{
$table->id();
$table->string('products_name')->comment('產品名稱');
$table->interger('products_price')->comment('產品價格');
$table->text('products_discript')->comment('產品描述');
$table->timestamps();
});
}
```
:::info
product Type->==<font color="#FF5E5E"> 一對一-> hasOne</font>==
this->hasMany('存取的地方', '我的欄位名稱', '對方的欄位名稱');
```php=
public function type()
{
return $this->hasOne('App\ProductType', 'id', 'product_type_id');
//寫法二
return $this->hasOne(ProductType::get());
}
```
:::
:::info
product->==<font color="#FF5E5E"> 一對多-> hasMany
</font>==
this->hasOne('存取的地方', '對方的欄位名稱', '我的欄位名稱');
```php=
public function Product()
{
return $this->hasMany('App\Product', 'product_type_id', 'id');
}
```
:::
---
* public資料夾是對外公開的->File storge
## request
* 在表單送出的時候網路傳送端會有很多資料,F12->Network查看
request會幫你接住
$request->all()表示你只要顯示資料庫的資料
### 存取表單內容
```php=
public function store(Request $request)
{
$new_record = new ProductType();
$new_record->product_type = $request->product_type;
return redirect('admin/product/type')->with('message', '新增種類成功!');
}
```
```php=
public function store(Request $request)
{
ProductType::create([
'product_type' => $request->product_type,
]);
return redirect('admin/product/type')->with('message', '新增種類成功!');
}
```
```php=
public function store(Request $request)
{
ProductType::create($request->all());
return redirect('admin/product/type')->with('message', '新增種類成功!');
}
```
>以上三種寫法都可以得到一樣的結果
>>解釋為:Request $request接收輸入的資料到ProductType的資料庫裡面create新增$request->all()接收到的所有資料;
傳送redirect給<font color="#FF5E5E">Route路徑('admin/product/type')</font>,然後帶一個新增成功的訊息。
---
當關聯的產品種類空白時,會因為沒有值所以無法存取,就會報錯
```php=
@foreach ($lists as $item)
<tr>
<td>{{ $item->type->product_type }}</td>
<td>{{ $item->name }}</td>
<td>{{ $item->image }}</td>
<td>{{ $item->color }}</td>
<td>{{ $item->size }}</td>
<td>{{ $item->price }}</td>
<td>{{ $item->discript }}</td>
<tr>
@endforeach
```
在product_type後加上??'' = product_type??''
表示可以接受空白
---
## CDN引入
### DataTables CDN
[DataTables](https://datatables.net/examples/basic_init/zero_configuration.html)
>
### Front Awsome CDN引入
google搜尋Front Awsome CDN

---
## <font color="#FF5E5E">Error::</font>
#### php指令
創建controller、magration等有問題的時候,可以查看web.的Route有沒有寫錯、沒寫完,先//掉在輸入指令即可建立成功。
:::success
官方命名方式提供
---
| 命名方式 | 寫法 |
| --------- | ------------ |
| 大駝峰 | ProductList |
| 小駝峰 | productList |
| 底線 | product_list |
| 命名規則 | | | | | |
| - | -------- | ------------ | ------------- | -------------- | ------------ |
| | Model: | Migration: | Controller: | Views:(不強制) | Function |
| 1. | 大駝峰 | 底線連接單字(小寫) | ___Controller(大駝峰) | 小寫 | 小駝峰 |
| 2. | 與表格名稱一致 | 資料表名稱複數 | 單數 | 底線連接 |
| 3. | 單數 |
| 範例: | History | histories | HistoryController | history |
:::