· 6 years ago · Aug 29, 2019, 09:58 AM
1### Laravel Blade Cheatsheet
2
3#### Introduction
4
5Blade is a simple but powerful templating engine that is used by laravel to display views
6It uses `blade.php` as its file extension. In laravel, blade view files are stored in `resources/views`.
7
8#### Layouts
9
10##### Defining Master Page Layout
11
12```php
13// <!-- views/layouts/app.blade.php -->
14
15<html>
16 <head>
17 <title>App Name | @yield('title')</title>
18 // <!-- Styles -->
19 @yield('styles')
20 </head>
21 <body>
22 @section('sidebar')
23 <aside>Sidebar</aside>
24 @show
25
26 // <!-- Content -->
27 @yield('content')
28
29 // <!-- Scripts -->
30 @yield('scripts')
31 </body>
32</html>
33
34```
35
36##### Extending Master Page
37
38```php
39// <!-- view/pages/home.blade.php -->
40@extends('layouts.app')
41
42@section('styles')
43
44<style>
45/* Some Styles Here */
46</style>
47
48@endsection
49
50@section('sidebar')
51 @parent // <!-- Extends parent instead of overwriting it -->
52
53 <div>More Sidebar</div>
54@endsection
55
56@section('scripts')
57
58<script>
59// some javascript code here
60</script>
61
62@endsection
63```
64
65#### Returning View Pages With Data
66
67```php
68
69 Route::get('/home', function($data){
70 return view('pages.home', ['data' => $data]);
71 });
72
73```
74
75#### Components And Slots
76
77```php
78
79// <!-- views/components/alert.blade.php -->
80<div class="notification is-danger">
81 {{ slot }}
82</div>
83
84// <!-- view/pages/login.blade.php -->
85@component('components.alert')
86 <strong>Whoops!</strong> Something Went Wrong // <!-- Takes slot place -->
87@endcomponent
88
89// <!-- Displays first view from array of views -->
90@componentFirst(['custom.alert', 'components.alert'])
91 <strong>Whoops!</strong> Something Went Wrong // <!-- Takes slot place -->
92@endcomponent
93
94// <!-- Custom Name To Slot -->
95<div class="notification is-danger">
96 <h4 class="title">{{ $title }}</h4>
97 {{ $slot }}
98</div>
99
100@component('components.alert')
101 @slot('title')
102 403! Unauthorized
103 @endslot
104 <p>You are not authorized to view this page</p>
105@endcomponent
106
107// <!-- Adding data to component -->
108@component('components.alert', ['foo' => 'bar'])
109 <p>Lorem ipsum</p>
110@endcomponent
111
112```
113
114#### Unescaped Data
115
116All tags passed displayed with `{{ $data }}` is escaped with `htmlspecialchars` to prevent XSS attacks.
117
118```php
119 // <!-- Display Unescaped Data -->
120 {!! $data !!}
121
122```
123
124#### With Javascript
125
126##### Displaying JSON
127
128```php
129
130 // <!-- Using normal php -->
131 <script>
132 const app = <?php echo json_encode($array); ?>;
133 </script>
134
135 // <!-- Using blade -->
136 <script>
137 const app = @json($array, JSON_PRETTY_PRINT);
138 </script>
139
140```
141
142##### Using Frameworks
143
144Since most js framework use `{{ $data }}` this convention to display data in DOM, blade provides a way to handle this.
145
146```php
147
148// <!-- Rendering on one line -->
149
150@{{ data }}
151
152// <!-- Rendering on multiple lines -->
153@verbatim
154// <!-- HTML And Framework data rendering -->
155<div>
156 <h3>Merhaba, {{ name }}</h3>
157</div>
158
159@endverbatim
160
161```
162
163##### Control Structures
164
165```php
166
167// <!-- If... Else ... -->
168@if($name == 'Margai Wangara')
169 <p>You are an awesome programmer</p>
170@else
171 <p>Margai would love to learn more programming stuff from you</p>
172@endif
173
174// <!-- Unless -->
175Logic: unless user is authenticated, show log in button
176@unless(Auth::check())
177 <button>Log In</button>
178@endunless
179
180// <!-- isset -->
181Logic: Data is available and not null
182@isset($data)
183 // <!-- Do something -->
184@endisset
185
186// <!-- empty -->
187@empty($data)
188 // <!-- Do Something -->
189@endempty
190
191// <!-- conditional sections -->
192@hasSection('navigation')
193
194 @yield('navigation')
195
196@endif
197
198// <!-- switch statement -->
199@switch($action)
200
201 @case('eat')
202 {{ $think->isBugInCode }}
203 @break
204
205 @case('sleep')
206 {{ $dream->solvedBugButMoreBugsPopUp }}
207 @break
208
209 @default
210 @break
211
212@endswitch
213
214```
215
216###### Authentication
217
218```php
219
220// <!-- without guard -->
221@auth
222 // <!-- This user is authenticated, show some awesome code result -->
223@endauth
224
225// <!-- is guest and without guard -->
226@guest
227 // <!-- This user is a guest, show some courtesy -->
228@endguest
229
230// <!-- with guard -->
231@auth('admin')
232 // <!-- Some Dashboard Magic | is authenticated as admin -->
233@endauth
234
235// <!-- is guest with guard -->
236@guest('admin')
237 // <!-- is guest on admin side, not logged in as admin -->
238@endguest
239
240
241```
242
243##### Loops
244
245```php
246
247// <!-- for loop -->
248@for($i = 0; $i < 10; $i++)
249 {{ $paper[$i] }}
250@endfor
251
252// <!-- for each -->
253@foreach($databank as $data)
254 {{ $data->id }}
255@endforeach
256
257// <!-- for else -->
258@forelse($databank as $data)
259 {{ $data->id }}
260@empty
261 <p>No data to display</p>
262@endforelse
263
264// <!-- while -->
265@while(true)
266 <p>Loop Forever</p>
267@endwhile
268
269
270```
271
272###### Loop Iterations
273
274```php
275@foreach($databank as $data)
276
277 @if($data->id == 1)
278 @continue
279 @endif
280
281 @if($data->id == 5)
282 @break
283 @endif
284
285@endforeach
286
287// <!-- alternative -->
288@foreach($databank as $data)
289
290 @continue($data->id == 1)
291
292 @break($data->id == 5)
293
294@endforeach
295
296```
297
298###### Loop Variable
299
300```php
301@foreach($databank as $data)
302 // <!-- if first -->
303 @if($loop->first)
304 // <!-- Do Some Logic -->
305 @endif
306
307 // <!-- if last in last loop-->
308 @if($loop->last)
309 // <!-- Do some more logic -->
310 @endif
311
312@endforeach
313
314// <!-- Nested Loops -->
315@foreach($databank as $data)
316
317 @foreach($data->related as $related)
318 // <!-- if first in outer/parent loop-->
319 @if($loop->parent->first)
320 // <!-- Do Some Logic -->
321 @endif
322
323 // <!-- if last in outer/parent loop-->
324 @if($loop->parent->last)
325 // <!-- Do some more logic -->
326 @endif
327
328 @endforeach
329
330@endforeach
331
332```
333
334**Loop Variable Table**
335
336| Loop Variable | Description |
337| ------------- | ------------- |
338| `$loop->index` | Index (starts at 0, same to $index in foreach($data as $index=>$d)) |
339| `$loop->iteration` | Iteration (starts at 1) |
340| `$loop->remaining` | Remaining iterations/items in loop |
341| `$loop->count` | Number of items |
342| `$loop->first` | First item in loop |
343| `$loop->last` | Last item in loop |
344| `$loop->even` | If iteration is even (meaning iteration 2, 4, 6, 8 ...) |
345| `$loop->odd` | If iteration is odd (meaning iteration 1, 3, 5, 7 ...) |
346| `$loop->depth` | Nesting level of current loop |
347| `$loop->parent` | Parent loop variable |
348
349##### Extras
350
351```php
352
353// <!-- Comments -->
354{{-- This is a blade comment --}}
355
356// <!-- php code inside blade -->
357@php
358
359 <?php echo 'Blade is awesome'; ?>
360
361@endphp
362
363```
364
365##### Forms
366
367###### CSRF And Methods Override
368
369Setting `csrf` token and override methods like `PUT` inside forms
370
371```php
372 // <!-- CSRF !important -->
373 @csrf
374
375 // <!-- Method override -->
376 @method('PUT')
377
378```
379
380###### Validation
381
382```php
383
384 // <!-- Error Handling in forms -->
385 <div class="field">
386 <div class="control">
387 <input type="text" name="username" class="input @error('name') is-danger @enderror">
388 </div>
389 @error('username')
390 <p class="help is-danger">Username is required</p>
391 @enderror
392 </div>
393
394```
395
396##### Stacks
397
398Works like a stack, push items that have to be displayed in a LIFO way
399
400```php
401
402// <!-- push script -->
403@push('scripts')
404 <script src="{{ asset('js/main.js') }}"></script>
405@endpush
406
407// <!-- render scripts -->
408<body>
409
410 // <!-- bottom end -->
411 @stack('scripts')
412</body>
413
414// <!-- prepend script to beginning of stack -->
415@prepend('scripts')
416 // <!--This script will be first-->
417@endprepend
418
419```
420
421##### Subviews (includes)
422
423Can be used to render partials such as navbars and asides
424
425```php
426
427 // <!-- normal -->
428 @include('view.name', ['foo' => 'bar'])
429
430 // <!-- include if - if exists -->
431 @includeIf('view.name')
432
433 // <!-- include when - certain condition met? include -->
434 @includeWhen($condition, 'view.name', ['foo' => 'bar'])
435
436 // <!-- include first -->
437 @includeFirst(['custom.view', 'view.name'], ['foo' => 'bar'])
438
439 // <!-- ----------------------
440 combine views and includes
441 ---------------------- -->
442 @each('view.name', $jobs, 'job') // <!-- access data from 'job', $job->name ...-->
443
444 @each('view.name', $jobs, 'job', 'view.empty') // <!-- empty array in '$jobs', display some view -->
445
446```
447
448##### Service Injection (adding services)
449
450```php
451 // <!-- inject metrics service -->
452 @inject('metrics', 'App\Services\MetricsService')
453
454 // <!-- use -->
455 {{ $metrics->monthlyIncome() }}
456
457```
458
459##### Extending Blade
460
461```php
462 // <!-- inside 'App\Providers\AppServiceProvider' -->
463
464 // <!-- creating custom directive -->
465 public function boot()
466 {
467 // create custom directive
468 Blade::directive('datetime', function($expression){
469 return "<?php echo ($expression)->format('m/d/Y H:i');?>";
470 });
471
472 }
473
474 // <!-- use -->
475 @datetime($user->created_at)
476
477 // <!-- creating custom ifs -->
478 public function boot()
479 {
480 Blade::if('env', function($environment){
481
482 return app()->environment($environment);
483
484 });
485 }
486
487 // <!-- use -->
488 @env('local')
489
490 {{ __("Find me at 127.0.0.1") }}
491
492 @elseenv('testing')
493
494 {{ __("I need a focus group") }}
495
496 @else
497
498 {{ __("Fingers crossed") }}
499
500 @endenv
501
502
503```
504
505:alien:**Happy Coding!**:alien: