# laravel blade 跟時間
## blade vite
渲染問題
https://github.com/innocenzi/laravel-vite/issues/292
## 自訂blade
延長刀片
`directiveBlade` 允許您使用該方法定義自己的自定義指令。當 Blade 編譯器遇到自定義指令時,它將使用該指令包含的表達式調用提供的回調。
以下示例創建了一個`@datetime($var)`指令,該指令格式化給定的$var,它應該是 的實例DateTime:
```
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::directive('datetime', function ($expression) {
return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
});
}
}
```
如您所見,我們將format方法鏈接到傳遞給指令的任何表達式上。因此,在本例中,該指令生成的最終 PHP 將是:
`<?php echo ($var)->format('m/d/Y H:i'); ?>`
## zip檔案
https://laraveldaily.com/how-to-create-zip-archive-with-files-and-download-it-in-laravel/
## 影片網址 能撥放
https://laraveldaily.com/embed-and-parse-youtube-vimeo-videos-with-laravel-embed-package/
## 年月日排序
https://laraveldaily.com/laravel-group-query-result-by-day-month-year/
## Excel
https://laraveldaily.com/excel-export-from-laravel-blade-table/
## 獲得 出來直接獲得 carbon parse
https://stackoverflow.com/questions/33405939/formatting-a-carbon-date-instance
## ralation 不要 ?? 用法
千萬不要永遠做$model->relationship->field任何檢查的關係對象仍然存在。
它可能因任何原因被刪除,在您的代碼之外,被其他人的排隊作業等刪除。 `Do if-else`,或`{{ $model->relationship->field ?? '' }}`在 Blade 中,或`{{ optional($model->relationship)->field }}`。使用 php8,您甚至可以使用 nullsafe 運算符`{{ $model->relationship?->field) }}`
## 現在時間
`now()->format('Y-m-d H:i'))`
## 簡單的queryString
`route ( 'profile' , [ 'id' => 1 , 'photos' => 'yes' ]); // `
結果:/user/1/profile?photos=yes`
## auth一些用法
```
@if(auth()->user())
// The user is authenticated.
@endif
```
更短
```
@auth
// The user is authenticated.
@endauth
```
相反的 遊客
```
@guest
// The user is not authenticated.
@endguest
```
## 一次檢查多個權限
@canany指令一次檢查多個權限
```
@canany(['update', 'view', 'delete'], $post)
// The current user can update, view, or delete the post
@elsecanany(['create'], \App\Post::class)
// The current user can create a post
@endcanany
```
## 自訂blade語法
`<textarea>@br2nl($post->post_text)</textarea>`
添加到 AppServiceProvider 的boot()方法中
```
public function boot()
{
Blade::directive('br2nl', function ($string) {
return "<?php echo preg_replace('/\<br(\s*)?\/?\>/i', \"\n\", $string); ?>";
});
}
```
## includ的預防
如果你不確定你的 Blade 部分文件是否真的存在,你可以使用這些條件命令:
僅當 Blade 文件存在時才會加載
`@includeIf('partials.header')`
這將僅為具有 role_id 1 的用戶加載標頭
`@includeWhen(auth()->user()->role_id == 1, 'partials.header')`
這將嘗試加載 adminlte.header,如果缺失 - 將加載 default.header
`@includeFirst('adminlte.header', 'default.header')`
## blade的Script沒反應
Stacks
Blade 可以讓你使用 @push 將已命名的 Stack 在其他的視圖或佈局中渲染,這樣能更優雅的在子視圖中指定需要的 JavaScript 程式庫:
```
@push('scripts')
<script src="/example.js"></script>
@endpush
```
記得script要加s
用途
子模板會先includ進去
所以script可能會沒反應 就用這個就好
## blade在前端 最好用單引號包起來

不然會採雷
以為你是變數去找
## {{ or }} 等於三元運算子
https://stackoverflow.com/questions/32030194/laravel-blade-variable-or-default-text-not-working-with-urls
## 單一section不用結尾 像標題這種
`@section('title', $contact->title)`
unless
## 當 false執行 直接else的意思
```
@unless($contact['new_b'])
<div class="div"> good</div>
@endunless
```
## isset跟php用法一樣 檢視存不存在
```
@isset($contact['has_true'])
isset
@endisset
```
## blade slot
slot不只是可以用在 <v-good> 這種元件
還可以用在自己註冊的元件語法

這種
## 關於 foreach 結合 if
```
@if (count($contact))
@foreach ($contact as $key => $con)
<div>{{ $key }} .{{ $con['title'] }}</div>
@endforeach
@else
no isset
@
endif
```
可改成
提一句 foreach內 include可以吃到變數 代表include會先載入
還有foreach可有index
```
@forelse ($contact as $key => $con)
別擔心變數問題 他會先吃到 可能是向php 會先跑一樣
@include('contact.par.post')
@empty
no isset
@endforelse
```
## foreach 內的loop
### loop 可決定迴圈跑起次 注意 要放在foreach內
ex
迴圈停止 當碰到2停止 不會執行2
`@break($key == 2) `
跟上面相反 到1就跑
`@continue($key == 1) `
```
@foreach
@if ($loop->even)
<div>{{ $key }} .{{ $con['title'] }}</div>
@else
<div style="background-color:rgba(26, 24, 24, 0.308)">{{ $key }} .{{ $con['title'] }}</div>
@endif
@endforeah
```
表單最好的話用 include @csrf 跟 按鈕放外面就好
old使用者輸入的舊資料 因為有錯誤 他會redirect 所以要把不重要的殘留
非常重要 這邊的$post 是edit的 但你create沒有傳東西
所以要用optional 中文 可選的
使用方法 optional 把屬性包起來 不論物件是否為空 很好用
但他又會說沒有這個東西所以你要把他在用為null
第一步是傳進來 第二步是抓他屬性 所以要用兩次解決
```
<label for="title">title</label>
<input id="title" type="text" class="form-control" name="title"
這邊重點
value="{{ old('title', optional($post ?? null)->title) }}"></div>
```
## 編碼問題
base 64 的問題用{{!! !!}}
可把
{{}}當innerText
{!! !!}innerHtml
**顯示未跳脫的資料**
在預設情況下,Blade 模板中的 {{ }} 表達式將會自動套用 PHP 的 htmlentities 函式,以避免 XSS 攻擊。如果你不希望你的資料被跳脫,可以使用下列的語法:
```
Hello, {!! $name !!}.
```
## 驗證錯誤訊息
{{-- //特定的錯誤 --}}
```
@error('title')
{{-- //用message --}}
<div class="alert alert-danger">{{ $message }}</div>
@enderror
```
全部錯誤展示
```
@if ($errors->any())
<div class="mb-3">
<ul class="list-group">
{{-- 這邊藥用all去把全部 我猜可能是因為都是物件 所以要包起來array然後跑foreach --}}
@foreach ($errors->all() as $error)
{{-- list-group-item-danger可以跟alert一樣 好用 --}}
<li class="list-group-item list-group-item-danger">{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
```
## 會員權限跟會員登入
**會員權限**
https://laravel.tw/docs/5.2/authorization
為了方便,Laravel 提供了 @can Blade 指令來快速的檢查,當目前認證的使用者擁有給定的權限。例如:
```
<a href="/post/{{ $post->id }}">View Post</a>
@can('update-post', $post)
<a href="/post/{{ $post->id }}/edit">Edit Post</a>
@endcan
你也可以將 @else 指令結合 @can 指令:
@can('update-post', $post)
<!-- 目前的使用者可以更新文章 -->
@else
<!-- 目前的使用者不可以更新文章 -->
@endcan
```

**身分驗證**
https://learnku.com/laravel/t/24129
```
guest
n. 客人,宾客;旅客;特邀嘉宾
@auth 和 @guest 指令可以用来快速确定当前用户是否已通过身份验证,是否为访客:
@auth
// 用户已通过身份验证...
@endauth
@guest
// 用户没有通过身份验证...
@endguest
```
## Blade & JavaScript 框架
由於許多 JavaScript 框架也使用「大括號」來標示將顯示在瀏覽器中的表達式。因此,你可以使用 @ 符號來表示 Blade 渲染引擎應跳過這段不予處理,例如:
```
<h1>Laravel</h1>
Hello, @{{ name }}.
```
在這個例子中, @ 符號將被 Blade 移除;接著 Blade 將不會修改 {{ name }} 表達式,取而代之的是 JavaScript 模板來對其進行渲染
@ 符號也同樣可用於跳過 Blade 指令:
```
{{-- Blade template --}}
@@json()
<!-- HTML output -->
@json()
```
The @verbatim 指令
如果您在模板中需要顯示很多 JavaScript 參數,可以將 HTML 包在 @verbatim 指令中。這樣您就不需要在每一個 Blade 指令前都添加 @ 符號:
```
@verbatim
<div class="container">
Hello, {{ name }}.
</div>
@endverbatim
```
## blade在fetch的雷

## 時間預設 公司的
```
<div class="col-md-6">
<div class="form-group">
<div class="input-group">
<input type="text" id="start_at" name="activity_start"
value="{{ $task->activity_start ?? old('activity_start', now()->format('Y-m-d H:i')) }}"
class="datetimepicker form-control {{ $errors->has('start_at') ? 'is-invalid' : '' }}"
data-role="datetimepicker" data-format="YYYY-MM-DD HH:mm" required>
@if ($errors->has('activity_start'))
<div class="invalid-feedback">
{{ $errors->first('activity_start') }}
</div>
@endif
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="input-group">
<input type="text" id="end_at" name="activeity_end"
value="{{ $task->activeity_end ?? request()->get('activeity_end', old('activeity_end')) }}"
class="datetimepicker form-control {{ $errors->has('end_at') ? 'is-invalid' : '' }}"
data-role="datetimepicker" data-format="YYYY-MM-DD HH:mm" required>
@if ($errors->has('activeity_end'))
<div class="invalid-feedback">
{{ $errors->first('activeity_end') }}
</div>
@endif
</div>
</div>
</div>
```
## 顯示時間 內容看udemy學的
created_at->diffForHumans() 過去多久了轉給人類看得
`加入時間 {{ $post->created_at->diffForHumans() }}`
php現在時間 now ()
diffInMinutes轉成min分鐘 找不到解答
下面是說超過五分鐘顯示new
@if (now()->diffInMinutes($post->created_at) < 5)
<div class="alert alert-info">New!!</div>
@endif
- 時間方法的一些補充 可以字串相加找自己要的

date('Y-m-d') ex 2014-10-02
date('H:m:s') ex 09:06:50pm
time() ex 1412221065
## 渲染 JSON
有時為了初始化一個 JavaScript 變數,您可能會向視圖傳入一個陣列並將其轉化成 JSON 。例如:
```
<script>
var app = <?php echo json_encode($array); ?>;
</script>
```
當然你也可使用 @json Blade 指令來代替手動呼叫 json_encode()。 @json 指令的參數和 PHP 的 json_encode() 一致:
```
<script>
var app = @json($array);
var app = @json($array, JSON_PRETTY_PRINT);
</script>
```
你應該只使用 @json 指令來渲染已存在的參數變成 JSON,Blade 模板是基於正則表達式的,如果嘗試將一個複雜表達式傳遞給 @json 指令可能會導致無法預測的錯誤
## 堆疊 解決子層scripts問題
Blade 允許你將視圖推送到堆疊中,它們可以在其他視圖或布局中進行渲染,這在子視圖中需要指定 JavaScript 函式庫時非常有用
```
@push('scripts')
<script src="/example.js"></script>
@endpush
```
你也可按需進行多次推送,請透過 @stack 指令來完整渲染堆疊的內容
```
<head>
<!-- Head Contents -->
@stack('scripts')
</head>
```
如果你想要預置內容於堆疊的頂部,可以使用 @prepend 指令
```
@push('scripts')
This will be second...
@endpush
// Later...
@prepend('scripts')
This will be first...
@endprepend
```
## 服務注入
@inject 指令可用於從 Laravel 的服務容器中取得服務。傳遞給 @inject 的第一個參數是將要置入的服務變數名,第二個參數可以是你想要解析的類別完整名或接口完整名
```
@inject('metrics', 'App\Services\MetricsService')
<div>
Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>
```
###### tags: `Laravel`