forked from summerblue/laravel5-cheatsheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
executable file
·2112 lines (1969 loc) · 81.6 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="@summer">
<title>Laravel 5.1 LTS Cheat Sheet</title>
<meta name="description" content="A quick reference guide (cheat sheet) for Laravel 5.1 LTS, listing artisan, composer, routes and other useful bits of information.We intend to build this Cheat Sheet more assessable and user friendly, you can view it with modern desktop :computer: browser and mobile device :iphone: .">
<meta name="keywords" content="Laravel 5.1 Artisan,Laravel 5.1 Auth,Laravel 5.1 Blade,Laravel 5.1 Cache,Laravel 5.1 Composer,Laravel 5.1 Config,Laravel 5.1 Container,Laravel 5.1 Cookie,Laravel 5.1 DB,Laravel 5.1 Environment,Laravel 5.1 Event,Laravel 5.1 File,Laravel 5.1 Form,Laravel 5.1 HTML,Laravel 5.1 Helper,Laravel 5.1 Input,Laravel 5.1 Lang,Laravel 5.1 Log,Laravel 5.1 Mail,Laravel 5.1 Model,Laravel 5.1 Pagination,Laravel 5.1 Queue,Laravel 5.1 Redirect,Laravel 5.1 Request,Laravel 5.1 Response,Laravel 5.1 Route,Laravel 5.1 SSH,Laravel 5.1 Schema,Laravel 5.1 Security,Laravel 5.1 Session,Laravel 5.1 String,Laravel 5.1 URL,Laravel 5.1 UnitTest,Laravel 5.1 Validation,Laravel 5.1 View">
<link rel="stylesheet" href="assets/css/normalize.css" />
<link rel="stylesheet" href="assets/css/foundation.min.css" />
<link rel="stylesheet" href="assets/css/font-awesome.min.css" />
<link rel="stylesheet" href="assets/css/page.css" />
</head>
<body>
<div class="off-canvas-wrapper wrapper-container">
<div class="off-canvas-wrapper-inner" data-off-canvas-wrapper>
<div class="off-canvas position-left sidebar-canvas" id="offCanvasLeft" data-off-canvas data-position="left">
<button class="close-button" aria-label="Close menu" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
<ul class="mobile-ofc vertical menu">
<li>
<button class="warning hollow button check-all-button">Check All</button>
</li>
<li>
<ul class="submenu menu vertical mobile-cmd-cell" data-submenu>
</ul>
</li>
</ul>
</div>
<div class="off-canvas-content" data-off-canvas-content>
<div class="title-bar hide-for-medium">
<div class="title-bar-left">
<button class="menu-icon" type="button" data-open="offCanvasLeft"></button>
</div>
</div>
</div>
<a href="#top" id="top-button" title="Top"><i class="icon-arrow-up"></i></a>
<a href="#" class="comments-toggle" title="Toggle Code Comments"><i class="icon-eye-close"></i></a>
<div class="row full-width">
<div class="large-2 columns code-column sidebar">
<h5 class="sidebar-title">Laravel 5.1 LTS Cheat Sheet</h5>
<hr class="horizonal-line">
<div class="show-for-medium">
<button class="warning hollow button check-all-button">Check All</button>
<div class="clearfix"></div>
<ul class="sidebar-menu">
</ul>
<div class="clearfix"></div>
<hr class="horizonal-line">
</div>
<ul class="sidebar-bottom">
<li>
<a href="https://phphub.org" target="_blank">Laravel Forum</a>
</li>
<li>
<a href="https://laravel.com/docs/5.1" target="_blank">Laravel 5.1 Docs</a>
</li>
<li>
<a href="https://laravel-china.org/topics/3383" target="_blank" rel="nofollow" title="" style="display: block;margin-bottom: 23px;">
<img src="https://dn-phphub.qbox.me/uploads/images/201612/10/1/k7wwMpJduq.jpg" style="width: 150px;border: 1px solid #d8d3d3;box-shadow: 0 0 30px #d4d4d4;-moz-box-shadow: 0 0 30px #ccc;-webkit-box-shadow: 0 0 30px #d4d4d4;margin-bottom: 10px;margin-top: 21px;border-radius: 4px;">
</a>
</li>
<li>
<a href="http://estgroupe.com" target="_blank">by The EST Group</a>
</li>
<li class="social-icon">
<a href="http://github.com/summerblue" target="_blank" data-tooltip aria-haspopup="true" class="top" data-disable-hover="false" tabindex="2" title="This project maintained by Summer with Love">
<div class="avatar"></div>
</a>
<a href="https://github.com/summerblue/laravel5-cheatsheet" target="_blank" data-tooltip aria-haspopup="true" class="top" data-disable-hover="false" tabindex="2" title="Star me on GitHub">
<i class="icon-github"></i>
</a>
<a href="https://twitter.com/Summer_Charlie" target="_blank" data-tooltip aria-haspopup="true" class="top" data-disable-hover="false" tabindex="2" title="Follow My Twitter">
<i class="icon-twitter"></i>
</a>
<a href="http://weibo.com/1837553744" target="_blank" data-tooltip aria-haspopup="true" class="top" data-disable-hover="false" tabindex="2" title="Follow My Weibo">
<i class="icon-weibo"></i>
</a>
</li>
<li class="languages-flag">
<a href="https://cs.laravel-china.org/">
<i class="cn flag"></i>
</a>
<span class="vertical-line">|</span>
<a href="https://summerblue.github.io/laravel5-cheatsheet/">
<i class="gb flag"></i>
</a>
</li>
</ul>
</div>
<div class="large-10 columns code-column code-container">
<div class="grid">
<section class="cmd-description grid-item">
<h4><a name="artisan" href="#artisan">Artisan</a> <a href="http://laravel.com/docs/artisan" title="Artisan CLI @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// Added in 5.1.11:http://laravel.com/docs/5.1/authorization#creating-policies
php artisan make:policy PostPolicy
// Displays help for a given command
php artisan --help OR -h
// Do not output any message
php artisan --quiet OR -q
// Display this application version
php artisan --version OR -V
// Do not ask any interactive question
php artisan --no-interaction OR -n
// Force ANSI output
php artisan --ansi
// Disable ANSI output
php artisan --no-ansi
// The environment the command should run under
php artisan --env
// -v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
php artisan --verbose
// Remove the compiled class file
php artisan clear-compiled
// Display the current framework environment
php artisan env
// Displays help for a command
php artisan help
// Lists commands
php artisan list
// Interact with your application
php artisan tinker
// Put the application into maintenance mode
php artisan down
// Bring the application out of maintenance mode
php artisan up
// Optimize the framework for better performance
// --force Force the compiled class file to be written.
// --psr Do not optimize Composer dump-autoload.
php artisan optimize [--force] [--psr]
// Serve the application on the PHP development server
php artisan serve
// Change the default port
php artisan serve --port 8080
// Get it to work outside localhost
php artisan serve --host 0.0.0.0
// Set the application namespace
php artisan app:name namespace
// Flush expired password reset tokens
php artisan auth:clear-resets
// Flush the application cache
php artisan cache:clear
// Create a migration for the cache database table
php artisan cache:table
// Create a cache file for faster configuration loading
php artisan config:cache
// Remove the configuration cache file
php artisan config:clear
// In program
$exitCode = Artisan::call('config:cache');
// Seed the database with records
// --class The class name of the root seeder (default: "DatabaseSeeder")
// --database The database connection to seed
// --force Force the operation to run when in production.
php artisan db:seed [--class[="..."]] [--database[="..."]] [--force]
// Generate the missing events and handlers based on registration
php artisan event:generate
// Create a new command handler class
// --command The command class the handler handles.
php artisan handler:command [--command="..."] name
// Create a new event handler class
// --event The event class the handler handles.
// --queued Indicates the event handler should be queued.
php artisan handler:event [--event="..."] [--queued] name
// Set the application key
php artisan key:generate
// By default, this creates a self-handling command that isn't pushed to the queue.
// Pass this the --handler flag to generate a handler, and the --queued flag to make it queued.
php artisan make:command [--handler] [--queued] name
// Create a new Artisan command
// --command The terminal command that should be assigned. (default: "command:name")
make:console [--command[="..."]] name
// Create a new resourceful controller
// --plain Generate an empty controller class.
php artisan make:controller [--plain] name
php artisan make:controller App\\Admin\\Http\\Controllers\\DashboardController
// Create a new event class
php artisan make:event name
// Create a new middleware class
php artisan make:middleware name
// Create a new migration file
// --create The table to be created.
// --table The table to migrate.
php artisan make:migration [--create[="..."]] [--table[="..."]] name
// Create a new Eloquent model class
php artisan make:model name
// Create a new service provider class
php artisan make:provider name
// Create a new form request class
php artisan make:request name
// Database migrations
// --database The database connection to use.
// --force Force the operation to run when in production.
// --path The path of migrations files to be executed.
// --pretend Dump the SQL queries that would be run.
// --seed Indicates if the seed task should be re-run.
php artisan migrate [--database[="..."]] [--force] [--path[="..."]] [--pretend] [--seed]
// Create the migration repository
php artisan migrate:install [--database[="..."]]
// Create a new migration file
// --seeder The class name of the root seeder.
php artisan migrate:refresh [--database[="..."]] [--force] [--seed] [--seeder[="..."]]
// Rollback all database migrations
// --pretend Dump the SQL queries that would be run.
php artisan migrate:reset [--database[="..."]] [--force] [--pretend]
// Rollback the last database migration
php artisan migrate:rollback [--database[="..."]] [--force] [--pretend]
// Show a list of migrations up/down
php artisan migrate:status
// Create a migration for the queue jobs database table
php artisan queue:table
// Listen to a given queue
// --queue The queue to listen on
// --delay Amount of time to delay failed jobs (default: 0)
// --memory The memory limit in megabytes (default: 128)
// --timeout Seconds a job may run before timing out (default: 60)
// --sleep Seconds to wait before checking queue for jobs (default: 3)
// --tries Number of times to attempt a job before logging it failed (default: 0)
php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
// List all of the failed queue jobs
php artisan queue:failed
// Create a migration for the failed queue jobs database table
php artisan queue:failed-table
// Flush all of the failed queue jobs
php artisan queue:flush
// Delete a failed queue job
php artisan queue:forget
// Restart queue worker daemons after their current job
php artisan queue:restart
// Retry a failed queue job(id: The ID of the failed job)
php artisan queue:retry id
// Subscribe a URL to an Iron.io push queue
// queue: The name of Iron.io queue.
// url: The URL to be subscribed.
// --type The push type for the queue.
php artisan queue:subscribe [--type[="..."]] queue url
// Process the next job on a queue
// --queue The queue to listen on
// --daemon Run the worker in daemon mode
// --delay Amount of time to delay failed jobs (default: 0)
// --force Force the worker to run even in maintenance mode
// --memory The memory limit in megabytes (default: 128)
// --sleep Number of seconds to sleep when no job is available (default: 3)
// --tries Number of times to attempt a job before logging it failed (default: 0)
php artisan queue:work [--queue[="..."]] [--daemon] [--delay[="..."]] [--force] [--memory[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
// Create a route cache file for faster route registration
php artisan route:cache
// Remove the route cache file
php artisan route:clear
// List all registered routes
php artisan route:list
// Run the scheduled commands
php artisan schedule:run
// Create a migration for the session database table
php artisan session:table
// Publish any publishable assets from vendor packages
// --force Overwrite any existing files.
// --provider The service provider that has assets you want to publish.
// --tag The tag that has assets you want to publish.
php artisan vendor:publish [--force] [--provider[="..."]] [--tag[="..."]]
php artisan tail [--path[="..."]] [--lines[="..."]] [connection]
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="composer" href="#composer">Composer</a> <a href="http://getcomposer.org/doc/03-cli.md" title="Composer CLI Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
composer create-project laravel/laravel folder_name
composer install
composer update
composer dump-autoload [--optimize]
composer self-update
composer require [options] [--] [vendor/packages]...
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Configuration" href="#Configuration">Config</a> <a href="http://laravel.com/docs/configuration" title="Configuration Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
Config::get('app.timezone');
//get with Default value
Config::get('app.timezone', 'UTC');
//set Configuration
Config::set('database.default', 'sqlite');
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="routing" href="#routing">Route</a> <a href="http://laravel.com/docs/routing" title="Routing @ Laravel Docs"><i class="icon-file-text"></i></a> <a href="http://laravel.com/docs/helpers#routing" title="Routing Helpers @ Laravel Docs"><i class="icon-file-text"></i></a> </h4>
<pre class="prettyprint lang-php">
Route::get('foo', function(){});
Route::get('foo', 'ControllerName@function');
Route::controller('foo', 'FooController');
</pre>
<h6>RESTful Controllers <a href="http://laravel.com/docs/controllers#restful-resource-controllers" title="RESTful Controllers @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
Route::resource('posts','PostsController');
//Specify a subset of actions to handle on the route
Route::resource('photo', 'PhotoController',['only' => ['index', 'show']]);
Route::resource('photo', 'PhotoController',['except' => ['update', 'destroy']]);
</pre>
<h6>Triggering Errors <a href="http://laravel.com/docs/routing#throwing-404-errors" title="throwing-404-errors @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
App::abort(404);
$handler->missing(...) in ErrorServiceProvider::boot();
throw new NotFoundHttpException;
</pre>
<h6>Route Parameters <a href="http://laravel.com/docs/routing#route-parameters" title="RESTful Controllers @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
Route::get('foo/{bar}', function($bar){});
Route::get('foo/{bar?}', function($bar = 'bar'){});
</pre>
<h6>HTTP Verbs</h6>
<pre class="prettyprint lang-php">
Route::any('foo', function(){});
Route::post('foo', function(){});
Route::put('foo', function(){});
Route::patch('foo', function(){});
Route::delete('foo', function(){});
// RESTful actions
Route::resource('foo', 'FooController');
// Registering A Route For Multiple Verbs
Route::match(['get', 'post'], '/', function(){});
</pre>
<h6>Secure Routes(TBD)</h6>
<pre class="prettyprint lang-php">
Route::get('foo', array('https', function(){}));
</pre>
<h6>Route Constraints</h6>
<pre class="prettyprint lang-php">
Route::get('foo/{bar}', function($bar){})
->where('bar', '[0-9]+');
Route::get('foo/{bar}/{baz}', function($bar, $baz){})
->where(array('bar' => '[0-9]+', 'baz' => '[A-Za-z]'))
</pre>
<pre class="prettyprint lang-php">
// Set a pattern to be used across routes
Route::pattern('bar', '[0-9]+')
</pre>
<h6>HTTP Middleware <a href="http://laravel.com/docs/middleware" title="HTTP Middleware @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
// Assigning Middleware To Routes
Route::get('admin/profile', ['middleware' => 'auth', function(){}]);
Route::get('admin/profile', function(){})->middleware('auth');
</pre>
<h6>Named Routes</h6>
<pre class="prettyprint lang-php">
Route::currentRouteName();
Route::get('foo/bar', array('as' => 'foobar', function(){}));
Route::get('user/profile', [
'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
Route::get('user/profile', 'UserController@showProfile')->name('profile');
$url = route('profile');
$redirect = redirect()->route('profile');
</pre>
<h6>Route Prefixing</h6>
<pre class="prettyprint lang-php">
Route::group(['prefix' => 'admin'], function()
{
Route::get('users', function(){
return 'Matches The "/admin/users" URL';
});
});
</pre>
<h6>Route Namespacing</h6>
<pre class="prettyprint lang-php">
// This route group will carry the namespace 'Foo\Bar'
Route::group(array('namespace' => 'Foo\Bar'), function(){})
</pre>
<h6>Sub-Domain Routing</h6>
<pre class="prettyprint lang-php">
// {sub} will be passed to the closure
Route::group(array('domain' => '{sub}.example.com'), function(){});
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="app" href="#app">Environment</a> <a href="http://laravel.com/docs/configuration#environment-configuration" title="Environment Configuration @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
$environment = app()->environment();
$environment = App::environment();
$environment = $app->environment();
// The environment is local
if ($app->environment('local')){}
// The environment is either local OR staging...
if ($app->environment('local', 'staging')){}
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="log" href="#log">Log</a> <a href="http://laravel.com/docs/errors#logging" title="Log @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// The logger provides the seven logging levels defined in RFC 5424:
// debug, info, notice, warning, error, critical, and alert.
Log::info('info');
Log::info('info',array('context'=>'additional info'));
Log::error('error');
Log::warning('warning');
// get monolog instance
Log::getMonolog();
// add listener
Log::listen(function($level, $message, $context) {});
</pre>
<h6>Query Logging <a href="http://laravel.com/docs/database#query-logging" title="Log @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
// enable the log
DB::connection()->enableQueryLog();
// get an array of the executed queries
DB::getQueryLog();
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="urls" href="#urls">URL</a> <a href="http://laravel.com/api/5.1/Illuminate/Routing/UrlGenerator.html" title="UrlGenerator @ Laravel Docs"><i class="icon-file-text"></i></a> <a href="http://laravel.com/docs/helpers#urls" title="URL helper @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
URL::full();
URL::current();
URL::previous();
URL::to('foo/bar', $parameters, $secure);
URL::action('NewsController@item', ['id'=>123]);
// need be in appropriate namespace
URL::action('Auth\AuthController@logout');
URL::action('FooController@method', $parameters, $absolute);
URL::route('foo', $parameters, $absolute);
URL::secure('foo/bar', $parameters);
URL::asset('css/foo.css', $secure);
URL::secureAsset('css/foo.css');
URL::isValidUrl('http://example.com');
URL::getRequest();
URL::setRequest($request);
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="events" href="#events">Event</a> <a href="http://laravel.com/docs/events" title="Events @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
Event::fire('foo.bar', array($bar));
// Register an event listener with the dispatcher.
// void listen(string|array $events, mixed $listener, int $priority)
Event::listen('App\Events\UserSignup', function($bar){});
Event::listen('foo.*', function($bar){});
Event::listen('foo.bar', 'FooHandler', 10);
Event::listen('foo.bar', 'BarHandler', 5);
// Stopping The Propagation Of An Event
// You may do so by returning false from your handler.
Event::listen('foor.bar', function($event){ return false; });
Event::subscribe('UserEventHandler');
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="db" href="#db">DB</a> <a href="http://laravel.com/docs/5.1/database" title="Basic Database Usage @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<h6>Basic Database Usage</h6>
<pre class="prettyprint lang-php">
DB::connection('connection_name');
// Running A Select Query
$results = DB::select('select * from users where id = ?', [1]);
$results = DB::select('select * from users where id = :id', ['id' => 1]);
// Running A General Statement
DB::statement('drop table users');
// Listening For Query Events
DB::listen(function($sql, $bindings, $time){ code_here; });
// Database Transactions
DB::transaction(function()
{
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
DB::beginTransaction();
DB::rollBack();
DB::commit();
</pre>
<h6>Query Builder <a href="http://laravel.com/docs/5.1/queries" title="Query Builder @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
// Retrieving All Rows From A Table
DB::table('name')->get();
// Chunking Results From A Table
DB::table('users')->chunk(100, function($users)
{
foreach ($users as $user)
{
//
}
});
// Retrieving A Single Row From A Table
$user = DB::table('users')->where('name', 'John')->first();
DB::table('name')->first();
// Retrieving A Single Column From A Row
$name = DB::table('users')->where('name', 'John')->pluck('name');
DB::table('name')->pluck('column');
// Retrieving A List Of Column Values
$roles = DB::table('roles')->lists('title');
$roles = DB::table('roles')->lists('title', 'name');
// Specifying A Select Clause
$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();
// Adding A Select Clause To An Existing Query
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
// Using Where Operators
$users = DB::table('users')->where('votes', '>', 100)->get();
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
$users = DB::table('users')
->whereBetween('votes', [1, 100])->get();
$users = DB::table('users')
->whereNotBetween('votes', [1, 100])->get();
$users = DB::table('users')
->whereIn('id', [1, 2, 3])->get();
$users = DB::table('users')
->whereNotIn('id', [1, 2, 3])->get();
$users = DB::table('users')
->whereNull('updated_at')->get();
DB::table('name')->whereNotNull('column')->get();
// Dynamic Where Clauses
$admin = DB::table('users')->whereId(1)->first();
$john = DB::table('users')
->whereIdAndEmail(2, 'john@doe.com')
->first();
$jane = DB::table('users')
->whereNameOrAge('Jane', 22)
->first();
// Order By, Group By, And Having
$users = DB::table('users')
->orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
DB::table('name')->orderBy('column')->get();
DB::table('name')->orderBy('column','desc')->get();
DB::table('name')->having('count', '>', 100)->get();
// Offset & Limit
$users = DB::table('users')->skip(10)->take(5)->get();
</pre>
<h6>Joins <a href="http://laravel.com/docs/5.1/queries#joins" title="Joins @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
// Basic Join Statement
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get();
// Left Join Statement
DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
// select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
</pre>
<h6>Aggregates <a href="http://laravel.com/docs/5.1/queries#aggregates" title="Aggregates @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');
</pre>
<h6>Raw Expressions <a href="http://laravel.com/docs/5.1/queries#raw-expressions" title="Raw Expressions @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
// return rows
DB::select('select * from users where id = ?', array('value'));
// return nr affected rows
DB::insert('insert into foo set bar=2');
DB::update('update foo set bar=2');
DB::delete('delete from bar');
// returns void
DB::statement('update foo set bar=2');
// raw expression inside a statement
DB::table('name')->select(DB::raw('count(*) as count, column2'))->get();
</pre>
<h6>Inserts / Updates / Deletes / Unions / Pessimistic Locking</h6>
<pre class="prettyprint lang-php">
// Inserts
DB::table('users')->insert(
['email' => 'john@example.com', 'votes' => 0]
);
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);
DB::table('users')->insert([
['email' => 'taylor@example.com', 'votes' => 0],
['email' => 'dayle@example.com', 'votes' => 0]
]);
// Updates
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);
DB::table('users')->increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes');
DB::table('users')->decrement('votes', 5);
DB::table('users')->increment('votes', 1, ['name' => 'John']);
// Deletes
DB::table('users')->where('votes', '<', 100)->delete();
DB::table('users')->delete();
DB::table('users')->truncate();
// Unions
// The unionAll() method is also available, and has the same method signature as union.
$first = DB::table('users')->whereNull('first_name');
$users = DB::table('users')->whereNull('last_name')->union($first)->get();
// Pessimistic Locking
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="eloquent" href="#eloquent">Model</a> <a href="http://laravel.com/docs/eloquent" title="Eloquent @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<h6>Basic Usage <a href="http://laravel.com/docs/5.1/eloquent#basic-usage" title="Basic Usage @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
// Defining An Eloquent Model
class User extends Model {}
// generate Eloquent models
php artisan make:model User
// specify a custom table name
class User extends Model {
protected $table = 'my_users';
}
</pre>
<h6>More</h6>
<pre class="prettyprint lang-php">Model::create(array('key' => 'value'));
// Find first matching record by attributes or create
Model::firstOrCreate(array('key' => 'value'));
// Find first record by attributes or instantiate
Model::firstOrNew(array('key' => 'value'));
// Create or update a record matching attibutes, and fill with values
Model::updateOrCreate(array('search_key' => 'search_value'), array('key' => 'value'));
// Fill a model with an array of attributes, beware of mass assignment!
Model::fill($attributes);
Model::destroy(1);
Model::all();
Model::find(1);
// Find using dual primary key
Model::find(array('first', 'last'));
// Throw an exception if the lookup fails
Model::findOrFail(1);
// Find using dual primary key and throw exception if the lookup fails
Model::findOrFail(array('first', 'last'));
Model::where('foo', '=', 'bar')->get();
Model::where('foo', '=', 'bar')->first();
Model::where('foo', '=', 'bar')->exists();
// dynamic
Model::whereFoo('bar')->first();
// Throw an exception if the lookup fails
Model::where('foo', '=', 'bar')->firstOrFail();
Model::where('foo', '=', 'bar')->count();
Model::where('foo', '=', 'bar')->delete();
//Output raw query
Model::where('foo', '=', 'bar')->toSql();
Model::whereRaw('foo = bar and cars = 2', array(20))->get();
Model::on('connection-name')->find(1);
Model::with('relation')->get();
Model::all()->take(10);
Model::all()->skip(10);
// Default Eloquent sort is ascendant
Model::all()->orderBy('column');
Model::all()->orderBy('column','desc');
</pre>
<h6>Soft Delete <a href="http://laravel.com/docs/5.1/eloquent#soft-deleting" title="Soft Deleting @ Laravel Docs"><i class="icon-file-text"></i></a></h6>
<pre class="prettyprint lang-php">
Model::withTrashed()->where('cars', 2)->get();
// Include the soft deleted models in the results
Model::withTrashed()->where('cars', 2)->restore();
Model::where('cars', 2)->forceDelete();
// Force the result set to only included soft deletes
Model::onlyTrashed()->where('cars', 2)->get();
</pre>
<h6>Relationships</h6>
<pre class="prettyprint lang-php">
// One To One - User::phone()
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
// One To One - Phone::user(), The Inverse Of The Relation
return $this->belongsTo('App\User', 'foreign_key', 'other_key');
// One To Many - Post::comments()
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
// One To Many - Comment::post()
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
// Many To Many - User::roles();
return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
// Many To Many - Role::users();
return $this->belongsToMany('App\User');
// Many To Many - Retrieving Intermediate Table Columns
$role->pivot->created_at;
// Many To Many - Pivot table with extra attributes
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
// Many To Many - Automatically maintained created_at and updated_at timestamps
return $this->belongsToMany('App\Role')->withTimestamps();
// Has Many Through - Country::posts(), A Country model have
// many Post models through an intermediate User model (User::country_id)
return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');
// Polymorphic Relations - Photo::imageable()
return $this->morphTo();
// Polymorphic Relations - Staff::photos()
return $this->morphMany('App\Photo', 'imageable');
// Polymorphic Relations - Product::photos()
return $this->morphMany('App\Photo', 'imageable');
// Polymorphic Relations - Register the morphMap in your AppServiceProvider
Relation::morphMap([
'Post' => App\Post::class,
'Comment' => App\Comment::class,
]);
// Many To Many Polymorphic Relations - Tables: posts,videos,tags,taggables
// Post::tags()
return $this->morphToMany('App\Tag', 'taggable');
// Video::tags()
return $this->morphToMany('App\Tag', 'taggable');
// Tag::posts()
return $this->morphedByMany('App\Post', 'taggable');
// Tag::videos()
return $this->morphedByMany('App\Video', 'taggable');
// Querying Relations
$user->posts()->where('active', 1)->get();
// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();
// Retrieve all posts that have three or more comments...
$posts = Post::has('comments', '>=', 3)->get();
// Retrieve all posts that have at least one comment with votes...
$posts = Post::has('comments.votes')->get();
// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();
// Eager Loading
$books = App\Book::with('author')->get();
$books = App\Book::with('author', 'publisher')->get();
$books = App\Book::with('author.contacts')->get();
// Lazy Eager Loading
$books->load('author', 'publisher');
// Inserting Related Models
$comment = new App\Comment(['message' => 'A new comment.']);
$post->comments()->save($comment);
// save multiple related models
$post->comments()->saveMany([
new App\Comment(['message' => 'A new comment.']),
new App\Comment(['message' => 'Another comment.']),
]);
$post->comments()->create(['message' => 'A new comment.']);
// Updating a belongsTo relationship
$user->account()->associate($account);
$user->save();
$user->account()->dissociate();
$user->save();
// Inserting Related Models - Many To Many Relationships
$user->roles()->attach($roleId);
$user->roles()->attach($roleId, ['expires' => $expires]);
// Detach a single role from the user...
$user->roles()->detach($roleId);
// Detach all roles from the user...
$user->roles()->detach();
$user->roles()->detach([1, 2, 3]);
$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);
// Any IDs that are not in the given array will be removed from the intermediate table.
$user->roles()->sync([1, 2, 3]);
// You may also pass additional intermediate table values with the IDs:
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
</pre>
<h6>Events</h6>
<pre class="prettyprint lang-php">Model::creating(function($model){});
Model::created(function($model){});
Model::updating(function($model){});
Model::updated(function($model){});
Model::saving(function($model){});
Model::saved(function($model){});
Model::deleting(function($model){});
Model::deleted(function($model){});
Model::observe(new FooObserver);
</pre>
<h6>Eloquent Configuration</h6>
<pre class="prettyprint lang-php">
// Disables mass assignment exceptions from being thrown from model inserts and updates
Eloquent::unguard();
// Renables any ability to throw mass assignment exceptions
Eloquent::reguard();
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="pagination" href="#pagination">Pagination</a> <a href="http://laravel.com/docs/pagination" title="Pagination @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// Auto-Magic Pagination
Model::paginate(15);
Model::where('cars', 2)->paginate(15);
// "Next" and "Previous" only
Model::where('cars', 2)->simplePaginate(15);
// Manual Paginator
Paginator::make($items, $totalItems, $perPage);
// Print page navigators in view
$variable->links();
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="localization" href="#localization">Lang</a> <a href="http://laravel.com/docs/localization" title="Localization @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
App::setLocale('en');
Lang::get('messages.welcome');
Lang::get('messages.welcome', array('foo' => 'Bar'));
Lang::has('messages.welcome');
Lang::choice('messages.apples', 10);
// Lang::get alias
trans('messages.welcome');
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="files" href="#files">File</a> <a href="http://laravel.com/api/5.1/Illuminate/Filesystem/Filesystem.html" title="Filesystem @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
File::exists('path');
File::get('path');
File::getRemote('path');
// Get a file's contents by requiring it
File::getRequire('path');
// Require the given file once
File::requireOnce('path');
// Write the contents of a file
File::put('path', 'contents');
// Append to a file
File::append('path', 'data');
// Delete the file at a given path
File::delete('path');
// Move a file to a new location
File::move('path', 'target');
// Copy a file to a new location
File::copy('path', 'target');
// Extract the file extension from a file path
File::extension('path');
// Get the file type of a given file
File::type('path');
// Get the file size of a given file
File::size('path');
// Get the file's last modification time
File::lastModified('path');
// Determine if the given path is a directory
File::isDirectory('directory');
// Determine if the given path is writable
File::isWritable('path');
// Determine if the given path is a file
File::isFile('file');
// Find path names matching a given pattern.
File::glob($patterns, $flag);
// Get an array of all files in a directory.
File::files('directory');
// Get all of the files from the given directory (recursive).
File::allFiles('directory');
// Get all of the directories within a given directory.
File::directories('directory');
// Create a directory
File::makeDirectory('path', $mode = 0777, $recursive = false);
// Copy a directory from one location to another
File::copyDirectory('directory', 'destination', $options = null);
// Recursively delete a directory
File::deleteDirectory('directory', $preserve = false);
// Empty the specified directory of all files and folders
File::cleanDirectory('directory');
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="unittest" href="#unittest">UnitTest</a> <a href="http://laravel.com/docs/testing" title="Unit testing @ Laravel Docs"><i class="icon-file-text"></i></a></h4>
<h6>Install and run</h6>
<pre class="prettyprint lang-php">
// add to composer and update:
"phpunit/phpunit": "4.0.*"
// run tests (from project root)
./vendor/bin/phpunit
</pre>
<h6>Asserts</h6>
<pre class="prettyprint lang-php">
$this->assertTrue(true);
$this->assertEquals('foo', $bar);
$this->assertCount(1,$times);
$this->assertResponseOk();
$this->assertResponseStatus(403);
$this->assertRedirectedTo('foo');
$this->assertRedirectedToRoute('route.name');
$this->assertRedirectedToAction('Controller@method');
$this->assertViewHas('name');
$this->assertViewHas('age', $value);
$this->assertSessionHasErrors();
// Asserting the session has errors for a given key...
$this->assertSessionHasErrors('name');
// Asserting the session has errors for several keys...
$this->assertSessionHasErrors(array('name', 'age'));
$this->assertHasOldInput();
</pre>
<h6>Calling routes</h6>
<pre class="prettyprint lang-php">
$response = $this->call($method, $uri, $parameters, $files, $server, $content);
$response = $this->callSecure('GET', 'foo/bar');
$this->session(['foo' => 'bar']);
$this->flushSession();
$this->seed();
$this->seed($connection);
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="SSH" href="#SSH">SSH</a> <a href="http://laravel.com/docs/ssh" title="SSH @ Laravel Docs"><i class="icon-file-text"></i></a>
</h4>
<h6>Executing Commands</h6>
<pre class="prettyprint lang-php">
SSH::run(array $commands);
SSH::into($remote)->run(array $commands); // specify remote, otherwise assumes default
SSH::run(array $commands, function($line)
{
echo $line.PHP_EOL;
});
</pre>
<h6>Tasks</h6>
<pre class="prettyprint lang-php">
// define
SSH::define($taskName, array $commands);
// execute
SSH::task($taskName, function($line)
{
echo $line.PHP_EOL;
});
</pre>
<h6>SFTP Uploads</h6>
<pre class="prettyprint lang-php">SSH::put($localFile, $remotePath);
SSH::putString($string, $remotePath);
</pre>
</section>
<section class="cmd-description grid-item">