Laravel cheatsheet

Page 1

L ara velCh eatShee t Artis an phpartisan--helpOR-h phpartisan--quie tOR-q phpartisan--vers ionOR-V phpartisan--no-i nteractionO Rn phpartisan--ansi phpartisan--no-a nsi phpartisan--env //-v|vv|vvvIncre asetheverb osi tyo fmess ages :1f orn orma lo ut put,2f ormor ev erbo seoutputan d3fordebug phpartisan--verb ose

phpartisanchange s phpartisanclearcompiled phpartisandown phpartisandump-a utoload phpartisanenv phpartisanhelp phpartisanlist phpartisanmigrat e phpartisanoptimi ze phpartisanroutes phpartisanserve phpartisantinker phpartisanup phpartisanworkbe nch

phpartisanasset: publish[--b enc h[=" ve ndor /pac kag e" ]][ --pa th[ =" ..."]][ packag e ] phpartisanauth:r eminders phpartisancache: clear phpartisancomman d:makename[-comm an d[=" ..." ]][-p at h[=" ... "] ][--na m espace [ =" ..." ]] phpartisanconfig :publish phpartisancontro ller:make[-be nch= "v endo r/pa cka ge "] phpartisandb:see d[--class[= ".. ."]][ --da taba se[ =" .. ." ]] phpartisankey:ge nerate phpartisanmigrat e[--bench=" ven dor/ pa ckag e"][-da ta ba se[= ".. ." ]][--p a th[=". . ." ]][ -p ackage [ =" . .."]][ --pret e n d][-s e ed] phpartisanmigrat e:install[-da taba se [=". .."] ] phpartisanmigrat e:makename[-benc h= "ven dor/ pac ka ge "][-cre at e][--p a ckage[ = ". .."] ][ --path [ =" . .."]][ --tabl e [ ="..." ] ] phpartisanmigrat e:refresh[-da taba se [=". .."] ][ -se ed ] phpartisanmigrat e:reset[--d ata base [= "... "]][-pr et en d] phpartisanmigrat e:rollback[ --d atab as e[=" ..." ]][-p re tend ] phpartisanqueue: listen[--qu eue [=". .. "]][--d ela y[ =" .. ."]][-m emory[= " ..."]][-tim eo u t[=".. . "] ][conn e ction] phpartisanqueue: subscribe[-ty pe[= ". .."] ]qu eueu rl phpartisanqueue: work[--queu e[= "... "] ][-del ay[ =" .. ." ]][ --m em ory[=". . ."]][ -s leep ][ connec t io n ] phpartisansessio n:table phpartisanview:p ublish[--pa th[ =".. ." ]]p acka ge

Compo se r composercreate-pr ojectlarave l/l arav elfol der_ nam e composerinstall composerupdate composerdump-auto load[--opti miz e] composerself-upda te


Routi ng Route::get('foo',function(){} ); Route::get('foo','ControllerN ame @fun ct ion' ); Route::controller( 'foo','FooC ont roll er ');

Trigg er ingE rr or s App::abort(404); App::missing(funct ion($excepti on) {}); thrownewNotFound HttpExceptio n;

RouteP arame te rs Route::get('foo/{b ar}',functi on( $bar ){ }); Route::get('foo/{b ar?}',funct ion ($ba r='b ar') {}) ;

HTTPVe rbs Route::any('foo',function(){} ); Route::post('foo',function(){ }); Route::put('foo',function(){} ); Route::patch('foo' ,function() {}) ; Route::delete('foo ',function( ){} ); //RESTfulactions Route::resource('f oo','FooCon tro ller ') ;

Secur eRoute s Route::get('foo',array('https ',func ti on() {})) ;

RouteC onstr ai nt s Route::get('foo/{b ar}',functi on( $bar ){ }) ->where('bar',' [ 0-9] +') ; Route::get('foo/{b ar}/{baz}',fun ctio n( $bar ,$b az) {} ) ->where(array('b a r'= >' [0 -9]+ ',' ba z '=>' [A-Z a-z ]') )

Filte rs //Declareanauthfilter Route::filter('aut h',function (){ }); //Registeraclas sasafilte r Route::filter('foo ','FooFilte r') ; //Routesinthisgrouparegu ard edb ythe'aut h'fi lt er Route::get('foo',array('befor e'=>' au th',fun cti on () {} )); Route::group(array ('before'=>'a uth' ),fun ctio n() {} ); //Patternfilter Route::when('foo/* ','foo'); //HTTPverbpatte rn Route::when('foo/* ','foo',ar ray ('po st '));

NamedR outes Route::currentRout eName(); Route::get('foo/ba r',array('a s'=>' fo obar ',f unc ti on () {})) ;


RouteP refix in g //Thisroutegrou pwillcarryth epr ef ix' foo' Route::group(array ('prefix'=>'f oo') ,func tion (){ })

Sub-D om ainR ou ti ng //{sub}willbep assedtothecl osur e Route::group(array ('domain'=>'{ sub} .e xamp le.c om' ),f un ctio n() {} );

URLs URL::full(); URL::current(); URL::previous(); URL::to('foo/bar',$parameters ,$ secu re ); URL::action('FooCo ntroller@met hod ',$ pa rame ters ,$ ab so lu te); URL::route('foo',$parameters,$a bsol ut e); URL::secure('foo/b ar',$parame ter s); URL::asset('css/fo o.css',$sec ure ); URL::secureAsset(' css/foo.css' ); URL::isValidUrl('h ttp://exampl e.c om') ; URL::getRequest(); URL::setRequest($r equest); URL::getGenerator( ); URL::setGenerator( $generator);

Event s Event::fire('foo.b ar',array($ bar )); Event::listen('foo .bar',funct ion ($ba r) {}); Event::listen('foo .*',functio n($ bar) {} ); Event::listen('foo .bar','FooH and ler' ,10); Event::listen('foo .bar','BarH and ler' ,5); Event::listen('foo r.bar',func tio n($e ve nt){ret urnf al se ;}) ; Event::queue('foo' ,array($bar )); Event::flusher('fo o',function ($b ar){ }) ; Event::flush('foo' ); Event::subscribe(n ewFooEventH and ler) ;

DB $results=DB::sel ect('select*f romus erswher ei d=?' ,ar ray (' value') ) ; DB::insert('insertintousers(id ,na me )va lues(? ,?) ',arr ay( 1,'Dayle ' )); DB::update('updateuserssetv ote s=10 0wh erenam e=?' ,ar ray (' John')) ; DB::delete('deletefromusers' ); DB::statement('dro ptableuser s') ; DB::listen(functio n($sql,$bin din gs,$t ime) {co de_ he re ()}); DB::transaction(fu nction(){co de_ here ()});


Eloqu en t Model::create(arra y('key'=>' val ue') ); Model::destroy(1); Model::all(); Model::find(1); //Triggeranexce ption Model::findOrFail( 1); Model::where('foo' ,'=','bar' )-> get( ); Model::where('foo' ,'=','bar' )-> firs t( ); //Exception Model::where('foo' ,'=','bar' )-> firs tO rFai l(); Model::where('foo' ,'=','bar' )-> coun t( ); Model::where('foo' ,'=','bar' )-> dele te (); Model::whereRaw('f oo=barandca rs=2 ',a rray (20 )) -> ge t(); Model::on('connect ion-name')-> fin d(1) ; Model::with('relat ion')->get() ; Model::all()->take (10); Model::all()->skip (10);

SoftDe lete Model::withTrashed ()->where('c ars ',2 )>get (); Model::withTrashed ()->where('c ars ',2 )>res tore (); Model::where('cars ',2)->force Del ete( ); Model::onlyTrashed ()->where('c ars ',2 )>get ();

Event s Model::creating(fu nction($mode l){ }); Model::created(fun ction($model ){} ); Model::updating(fu nction($mode l){ }); Model::updated(fun ction($model ){} ); Model::saving(func tion($model) {}) ; Model::saved(funct ion($model){ }); Model::deleting(fu nction($mode l){ }); Model::deleted(fun ction($model ){} ); Model::observe(newFooObserver );

Mail Mail::send('email. view',$data ,f unct io n($m essa ge) {} ); Mail::send(array(' html.view','te xt.v ie w'),$da ta,$ ca ll back ); Mail::queue('email .view',$dat a,func ti on($ mess age ){ }) ; Mail::queueOn('que ue-name','e mai l.vi ew ',$ data ,$ ca ll ba ck); Mail::later(5,'em ail.view',$ dat a,f un ctio n($m ess ag e) {} ); //Writeallemailtologsins tea dofs endi ng Mail::pretend();

Queue s Queue::push('SendM ail',array( 'me ssag e'=>$mes sag e) ); Queue::push('SendE mail@send',arr ay(' me ssag e'= >$ me ss ag e)); Queue::push(functi on($job)use$i d{} ); phpartisanqueue: listen phpartisanqueue: listenconne cti on phpartisanqueue: listen--tim eou t=60 phpartisanqueue: work


Local iz ation App::setLocale('en '); Lang::get('message s.welcome'); Lang::get('message s.welcome',arr ay(' fo o'= >'B ar' )) ; Lang::has('message s.welcome'); Lang::choice('mess ages.apples' ,1 0);

Files File::exists('path '); File::get('path'); File::getRemote('p ath'); File::getRequire(' path'); File::requireOnce( 'path'); File::put('path','contents'); File::append('path ','data'); File::delete('path '); File::move('path','target'); File::copy('path','target'); File::extension('p ath'); File::type('path') ; File::size('path') ; File::lastModified ('path'); File::isDirectory( 'directory') ; File::isWritable(' path'); File::isFile('file '); //Findpathnamesmatchingagiv enp at tern . File::glob($patter ns,$flag); //Getanarrayofallfilesi nadir ec tory . File::files('direc tory'); //Getallofthefilesfromt hegive ndire ctor y( re cu rs ive) . File::allFiles('di rectory'); //Getallofthedirectorieswit hinagive ndi rec to ry . File::directories( 'directory') ; File::makeDirector y('path',$m ode=0 77 7,$ recu rsi ve=f alse ); File::copyDirector y('directory ','des ti nati on',$o pt io ns=n ull ); File::deleteDirect ory('directo ry' ,$p re serv e=fal se ); File::cleanDirecto ry('director y') ;

Input Input::get('key'); //Defaultifthekeyismissi ng Input::get('key','default'); Input::has('key'); Input::all(); //Onlyretrieve' foo'and'ba r'wheng etti ngi npu t Input::only('foo','bar'); //Disregard'foo'whengettin gi nput Input::except('foo ');


Sessi onInpu t(f la s h ) //Flashinputtothesession Input::flash(); Input::flashOnly(' foo','bar') ; Input::flashExcept ('foo','baz '); Input::old('key',' default_valu e') ;

Files //Useafilethat 'sbeenuplo ade d Input::file('filen ame'); //Determineifafilewasupl oad ed Input::hasFile('fi lename'); //Accessfilepro perties Input::file('name' )->getRealPa th( ); Input::file('name' )->getClient Ori gina lN ame( ); Input::file('name' )->getSize() ; Input::file('name' )->getMimeTy pe( ); //Moveanuploade dfile Input::file('name' )->move($des tin atio nP ath) ; //Moveanuploade dfile Input::file('name' )->move($des tin atio nP ath,$fi leN am e) ;

Cache Cache::put('key','value',$mi nut es); Cache::add('key','value',$mi nut es); Cache::forever('ke y','value') ; Cache::remember('k ey',$minute s,func ti on() {re tur n'v al ue'}); Cache::rememberFor ever('key',fun ctio n( ){r etur n' va lu e'}); Cache::forget('key '); Cache::has('key'); Cache::get('key'); Cache::get('key','default'); Cache::get('key',function(){ret urn'd efau lt';}) ; Cache::increment(' key'); Cache::increment(' key',$amoun t); Cache::decrement(' key'); Cache::decrement(' key',$amoun t); Cache::section('gr oup')->put(' key ',$ va lue) ; Cache::section('gr oup')->get(' key '); Cache::section('gr oup')->flush ();

Cooki es Cookie::get('key') ; //Createacookiethatlastsforeve r Cookie::forever('k ey','value' ); //Sendacookiew itharespon se $response=Respon se::make('He lloWor ld '); $response->withCoo kie(Cookie:: mak e('n am e','val ue' ,$m in utes ));


Sessi on s Session::get('key' ); Session::get('key' ,'default') ; Session::get('key' ,function() {r etur n'def ault ';}) ; Session::put('key' ,'value'); Session::all(); Session::has('key' ); Session::forget('k ey'); Session::flush(); Session::regenerat e(); Session::flash('ke y','value') ; Session::reflash() ; Session::keep(arra y('key1','k ey2 '));

Reque st s Request::path(); Request::is('foo/* '); Request::url(); Request::segment(1 ); Request::header('C ontent-Type' ); Request::server('P ATH_INFO'); Request::ajax(); Request::secure();

Respo ns es returnResponse::m ake($content s); returnResponse::m ake($content s,200) ; returnResponse::j son(array('k ey'=>'v alue ')); returnResponse::j son(array('k ey'=>'v alue ')) ->setCallback(In p ut:: get (' call back ') ) ; returnResponse::d ownload($fil epa th); returnResponse::d ownload($fil epa th,$f ilen ame,$h ea de rs ); //Createarespon seandmodif yahea de rva lue $response=Respon se::make($co nte nts,2 00); $response->header( 'Content-Typ e','ap pl icat ion/ jso n' ); return$response; //Attachacookietoarespon se returnResponse::m ake($content ) ->withCookie(Coo k ie:: mak e( 'key ',' va l ue '));

Redir ec ts returnRedirect::t o('foo/bar') ; returnRedirect::t o('foo/bar') ->w ith( 'k ey','va lue ') ; returnRedirect::t o('foo/bar') ->w ithI np ut(I nput ::g et () ); returnRedirect::t o('foo/bar') ->w ithI np ut(I nput ::e xc ep t( 'pas swo rd ')); returnRedirect::t o('foo/bar') ->w ithE rr ors( $val ida to r) ; returnRedirect::b ack(); returnRedirect::r oute('foobar '); returnRedirect::r oute('foobar ',arra y( 'val ue') ); returnRedirect::r oute('foobar ',arra y( 'key '=>'v al ue ') ); returnRedirect::a ction('FooCo ntr olle r@ inde x'); returnRedirect::a ction('FooCo ntr olle r@ baz' ,ar ray (' va lu e')) ; returnRedirect::a ction('FooCo ntr olle r@ baz' ,ar ray (' ke y'=>'va lu e')); //Ifintendedred irectisnotde fine d,def ault st ofo o/ bar. returnRedirect::i ntended('foo /ba r');


IoC App::bind('foo',f unction($app ){retu rnnewFoo ;} ); App::make('foo'); //Ifthisclasse xists,it'sret urne d App::make('FooBar' ); App::singleton('fo o',function (){ret ur nne wFo o;}) ; App::instance('foo ',newFoo); App::bind('FooRepo sitoryInterf ace ',' Ba rRep osit ory ') ; App::register('Foo ServiceProvi der '); //Listenforobje ctresolutio n App::resolving(fun ction($objec t){ });

Secur it y P assw or ds Hash::make('secr etpasswo rd '); Hash::check('sec retpassw or d',$has he dPas sw or d); Hash::needsRehas h($hashe dP assw ord) ;

A uth //Checkiftheuserislo ggedin Auth::check(); Auth::user(); Auth::attempt(ar ray('ema il '=>$em ai l,' pa ss wor d'=>$pa ssw ord )); //Rememberuserlogin Auth::attempt($c redentia ls ,tr ue); //Loginforasingler eq uest Auth::once($cred entials) ; Auth::login(User ::find(1 )) ; Auth::loginUsing Id(1); Auth::logout(); Auth::validate($ credenti al s); Auth::basic('use rname'); Auth::onceBasic( ); Password::remind ($creden ti als,fun ct ion( $m es sag e,$us er) {}) ;

E ncry pt io n Crypt::encrypt(' secretst ri ng') ; Crypt::decrypt($ encrypte dS trin g); Crypt::setMode(' ctr'); Crypt::setCipher ($cipher );

Valid at ion Validator::make( array('key'=>' F oo') , array('key'=>' r equi red |i n:Fo o') ); Validator::extend( 'foo',funct ion ($at tr ibut e,$ val ue ,$p aram s){ }) ; Validator::extend( 'foo','FooV ali dato r@ vali date '); Validator::resolve r(function($ tra nsla to r,$ data ,$ ru le s,$ms gs) { returnnewFooVa l idat or( $t rans lato r,$d ata,$ru les ,$ msgs); });


Valid at ionR ul es accepted active_url after:YYYY-MM-DD before:YYYY-MM-DD alpha alpha_dash alpha_num between:1,10 confirmed date date_format:YYYY-M M-DD different:fieldnam e email exists:table,colum n image in:foo,bar,baz not_in:foo,bar,baz integer numeric ip max:value min:value mimes:jpeg,png regex:[0-9] required required_if:field, value required_with:foo, bar,baz required_without:f oo,bar,baz same:field size:value unique:table,colum n,except,idC olu mn url

Views View::make('path/t o/view'); View::make('foo/ba r')->with('k ey' ,'v al ue') ; View::make('foo/ba r',array('k ey'=>'v alue ')); View::exists('foo/ bar'); //Shareavaluea crossallvi ews View::share('key','value'); //Nestingviews View::make('foo/ba r')->nest('n ame ',' fo o/ba z',$da ta ); //Registeraviewcomposer View::composer('vi ewname',fun cti on($ vi ew){ }); //Registermultipl eviewstoaco mpos er View::composer(arr ay('view1','vi ew2' ),fun ctio n($ vi ew ){ }); //Registeracomp oserclass View::composer('vi ewname','Fo oCo mpos er '); View::creator('vie wname',func tio n($v ie w){} );


BladeT empla te s @extends('layout.n ame') @section('name')/ /Beginase cti on @stop//Endasec tion @show//Endasec tionandthe ns howit @yield('name')//Showasecti onnamei natemp lat e @include('view.nam e') @include('view.nam e',array('k ey'=>'v alue ')); @lang('messages.na me') @choice('messages. name',1); @if @else @elseif @endif @unless @endunless @for @endfor @foreach @endforeach @while @endwhile {{$var}}//Echocontent {{{$var}}}//Ec hoescapedc ont ent {{--BladeComment--}}

Forms Form::open(array(' url'=>'foo /ba r','m etho d'= >' PU T' )) ; Form::open(array(' route'=>'f oo. bar' )) ; Form::open(array(' route'=>ar ray ('fo o. bar' ,$p ara me te r) )); Form::open(array(' action'=>' Foo Cont ro ller @met hod ') ); Form::open(array(' action'=>a rra y('F oo Cont roll er@ me th od ',$ par am eter))) ; Form::open(array(' url'=>'foo /ba r','f iles '=>tr ue )) ; Form::token(); Form::model($foo,array('route '= >ar ra y('f oo.b ar' ,$f oo ->ba r)) ); Form::close;

FormEl ement s Form::label('id','Description '); Form::label('id','Description ',arra y( 'cla ss'=>'f oo ') ); Form::text('name') ; Form::text('name',$value); Form::textarea('na me'); Form::textarea('na me',$value) ; Form::textarea('na me',$value,ar ray( 'c lass '=>'n am e' )) ; Form::hidden('foo' ,$value); Form::password('pa ssword'); Form::email('name' ,$value,ar ray ()); Form::file('name',array()); Form::checkbox('na me','value' ); Form::radio('name' ,'value'); Form::select('name ',array('ke y'=>' va lue' )); Form::select('name ',array('ke y'=>' va lue' ),' key ') ; Form::submit('Subm it!');


FormMa cros Form::macro('fooFi eld',functi on( ) {return'<inputt ype="custom" />' ;}) ; Form::fooField();

HTMLBu ilder HTML::macro('name' ,function() {}) ; HTML::entities($va lue); HTML::decode($valu e); HTML::script($url,$attributes ); HTML::style($url,$attributes) ; HTML::link($url,' title',$att rib utes ,$sec ure) ; HTML::secureLink($ url,'title' ,$ attr ib utes ); HTML::linkAsset($u rl,'title',$a ttri bu tes,$se cur e) ; HTML::linkSecureAs set($url,'t itl e',$a ttri bute s); HTML::linkRoute($n ame,'title' ,$ para me ters ,$a ttr ib ut es ); HTML::linkAction($ action,'tit le' ,$p ar amet ers,$a tt ri bu tes) ; HTML::mailto($emai l,'title',$at trib ut es); HTML::email($email ); HTML::ol($list,$a ttributes); HTML::ul($list,$a ttributes); HTML::listing($typ e,$list,$a ttr ibut es ); HTML::listingEleme nt($key,$ty pe,$va lu e); HTML::nestedListin g($key,$typ e,$val ue ); HTML::attributes($ attributes); HTML::attributeEle ment($key,$ val ue); HTML::obfuscate($v alue);

Strin gs //TransliterateaUTF-8valuetoASC II Str::ascii($value) Str::camel($value) Str::contains($hay stack,$need le) Str::endsWith($hay stack,$need les ) //Capastringwi thasingleins tanc eofagiv enva lu e. Str::finish($value ,$cap) Str::is($pattern,$value) Str::length($value ) Str::limit($value,$limit=10 0,$end='.. .') Str::lower($value) Str::words($value,$words=10 0,$end='.. .') Str::plural($value ,$count=2 ) //Generateamoretruly"rand om"alp ha -num ericst ri ng . Str::random($lengt h=16) //Generatea"ran dom"alpha-n ume ricst ring . Str::quickRandom($ length=16) Str::upper($value) Str::title($value) Str::singular($val ue) Str::slug($title,$separator='') Str::snake($value,$delimiter=' _') Str::startsWith($h aystack,$ne edl es) //Convertavaluetostudlyc apscas e. Str::studly($value ) Str::macro($name,$macro)


Helpe rs A rray s array_add($array ,'key',' valu e'); array_build($arr ay,func ti on() {}); array_divide($ar ray); array_dot($array ); array_except($ar ray,arr ay ('ke y')) ; array_fetch($arr ay,'key ') ; array_first($arr ay,func ti on($ key,$ valu e) {} ,$ def aul t); //Stripskeysf romthear ray array_flatten($a rray); array_forget($ar ray,'fo o' ); //Dotnotation array_forget($ar ray,'fo o. bar' ); array_get($array ,'foo',' defa ult' ); array_get($array ,'foo.b ar ',' defa ul t'); array_only($arra y,array (' key' )); //Returnarrayofkey= >valu es array_pluck($arr ay,'key ') ; //Returnandre move'ke y'fro mar ra y array_pull($arra y,'key' ); array_set($array ,'key',' valu e'); //Dotnotation array_set($array ,'key.s ub key' ,'v al ue') ; array_sort($arra y,funct io n(){ }); //Firstelementofana rr ay head($array); //Lastelementofanar ra y last($array);

P aths app_path(); public_path(); //Approotpath base_path(); storage_path();

S trin gs camel_case($valu e); class_basename($ class); //Escapeastri ng e('<html>'); starts_with('Foobar.','F oo') ; ends_with('Foob ar.','b ar .'); snake_case('fooB ar'); str_contains('He llofooba r.','fo o' ); //Result:foo/b ar/ str_finish('foo/ bar','/ ') ; str_is('foo*',' foobar') ; str_plural('car' ); str_random(25); str_singular('ca rs'); //Result:FooBa r studly_case('foo _bar'); trans('foo.bar') ; trans_choice('fo o.bar',$c ount );


U RLsan dLi n ks action('FooContr oller@me th od',$pa ra mete rs ); link_to('foo/bar ',$titl e,$at trib ut es,$s ec ure ); link_to_asset('i mg/foo.j pg ',$ titl e,$at tr ib ute s,$se cur e); link_to_route('r oute.nam e' ,$t itle ,$par am et ers ,$ att rib ute s); link_to_action(' FooContr ol ler@ meth od ',$ ti tl e,$pa ram s,$at trs ); //HTMLLink asset('img/photo .jpg',$ ti tle,$at tr ibut es ); //HTTPSlink secure_asset('im g/photo. jp g',$tit le ,$a tt ri but es) ; secure_url('path ',$para me ters ); route($route,$p arameter s,$ab solu te=t ru e) ; url('path',$par ameters=arra y(),$ secu re=nu ll) ;

M isce ll an eo u s csrf_token(); dd($value); value(function() {return' bar' ;}) ; with(newFoo)->c hainedMe th od() ;

Google Docs Document Source: https://docs.google.com/document/d/1NeCLL4fOgAmm4pYHIcBeWgCSCem5pqnGcwD_j4sNZyc/edit?usp=sharing


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.