Jump to: navigation, search

Laravel Cheat Sheet

Contents

Artisian

  1. php artisan migrate:make create_users_table [--bench="vendor/package"]
  2. php artisan migrate [--bench="vendor/package"]
  3. php artisan migrate --env=local
  4. php artisan migrate:rollback
  5. php artisan migrate:reset
  6. php artisan migrate:refresh
  7. php artisan db:seed
  8. php artisan config:publish
  9. php artisan serve
  10. php artisan list


Composer

  1. composer create-project laravel/laravel folder_name
  2. composer install
  3. composer update
  4. composer dump-autoload
  5. composer self-update


Routing

  1. Route::get('foo', function(){});
  2. Route::get('foo', 'ControllerName@function');
  3. Route::controller('foo', 'FooController');


Triggering Errors

  1. App::abort(404);
  2. App::missing(function($exception){});
  3. throw new NotFoundHttpException;


Route Parameters

  1. Route::get('foo/{bar}', function($bar){});
  2. Route::get('foo/{bar?}', function($bar = 'bar'){});


HTTP Verbs

  1. Route::any('foo', function(){});
  2. Route::post('foo', function(){});
  3. Route::put('foo', function(){});
  4. Route::patch('foo', function(){});
  5. Route::delete('foo', function(){});
  6. Route::resource('foo', 'FooController');
  7. // RESTful actions


Secure Routes

  1. Route::get('foo', array('https', function(){}));


Route Constraints

  1. Route::get('foo/{bar}', function($bar){})
  2.         ->where('bar', '[0-9]+');
  3. Route::get('foo/{bar}/{baz}', function($bar, $baz){})
  4.         ->where(array('bar' => '[0-9]+', 'baz' => '[A-Za-z]'))


Filters

  1. Route::filter('auth', function(){});
  2. // Declare an auth filter
  3. Route::filter('foo', 'FooFilter');
  4. // Register a class as a filter
  5. Route::get('foo', array('before' => 'auth', function(){}));
  6. // Routes in this group are guarded by the 'auth' filter
  7. Route::group(array('before' => 'auth'), function(){});
  8. Route::when('foo/*', 'foo');
  9. // Pattern filter
  10. Route::when('foo/*', 'foo', array('post'));
  11. // HTTP verb pattern


Named Routes

  1. Route::currentRouteName();
  2. Route::get('foo/bar', array('as' => 'foobar', function(){}));


Route Prefixing

  1. // This route group will carry the prefix 'foo'
  2.  Route::group(array('prefix' => 'foo'), function(){})


Sub-Domain Routing

  1. // {sub} will be passed to the closure
  2.  Route::group(array('domain' => '{sub}.example.com'), function(){});


URLs

  1. URL::full();
  2. URL::current();
  3. URL::previous();
  4. URL::to('foo/bar', $parameters, $secure);
  5. URL::action('FooController@method', $parameters, $absolute);
  6. URL::route('foo', $parameters, $absolute);
  7. URL::secure('foo/bar', $parameters);
  8. URL::asset('css/foo.css', $secure);
  9. URL::secureAsset('css/foo.css');
  10. URL::isValidUrl('http://example.com');
  11. URL::getRequest();
  12. URL::setRequest($request);
  13. URL::getGenerator();
  14. URL::setGenerator($generator);


Events

  1. Event::fire('foo.bar', array($bar));
  2. Event::listen('foo.bar', function($bar){});
  3. Event::listen('foo.*', function($bar){});
  4. Event::listen('foo.bar', 'FooHandler', 10);
  5. Event::listen('foo.bar', 'BarHandler', 5);
  6. Event::listen('foor.bar', function($event){ return false; });
  7. Event::queue('foo', array($bar));
  8. Event::flusher('foo', function($bar){});
  9. Event::flush('foo');
  10. Event::subscribe(new FooEventHandler);


DB

  1. $results = DB::select('select * from users where id = ?', array('value'));
  2. DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
  3. DB::update('update users set votes = 100 where name = ?', array('John'));
  4. DB::delete('delete from users');
  5. DB::statement('drop table users');
  6. DB::listen(function($sql, $bindings, $time){ code_here() });
  7. DB::transaction(function(){  code_here() });


Eloquent

  1. Model::create(array('key' => 'value'));
  2. Model::destroy(1);
  3. Model::all();
  4. Model::find(1);
  5. Model::findOrFail(1);
  6. // Trigger an exception
  7. Model::where('foo', '=', 'bar')->get();
  8. Model::where('foo', '=', 'bar')->first();
  9. Model::where('foo', '=', 'bar')->firstOrFail();
  10. // Exception
  11. Model::where('foo', '=', 'bar')->count();
  12. Model::where('foo', '=', 'bar')->delete();
  13. Model::whereRaw('foo = bar and cars = 2', array(20))->get();
  14. Model::on('connection-name')->find(1);
  15. Model::with('relation')->get();
  16. Model::all()->take(10);
  17. Model::all()->skip(10);


Soft Delete

  1. Model::withTrashed()->where('cars', 2)->get();
  2. Model::withTrashed()->where('cars', 2)->restore();
  3. Model::where('cars', 2)->forceDelete();
  4. Model::onlyTrashed()->where('cars', 2)->get();


Events

  1. Model::creating(function($model){});
  2. Model::created(function($model){});
  3. Model::updating(function($model){});
  4. Model::updated(function($model){});
  5. Model::saving(function($model){});
  6. Model::saved(function($model){});
  7. Model::deleting(function($model){});
  8. Model::deleted(function($model){});
  9. Model::observe(new FooObserver);


Mail

  1. Mail::send('email.view', $data, function($message){});
  2. Mail::send(array('html.view', 'text.view'), $data, $callback);
  3. Mail::queue('email.view', $data, function($message){});
  4. Mail::queueOn('queue-name', 'email.view', $data, $callback);
  5. Mail::later(5, 'email.view', $data, function($message){});
  6. Mail::pretend();
  7. // Write all email to logs instead of sending


Queues

  1. Queue::push('SendMail', array('message' => $message));
  2. Queue::push('SendEmail@send', array('message' => $message));
  3. Queue::push(function($job) use $id {});
  1. php artisan queue:listen
  2. php artisan queue:listen connection
  3. php artisan queue:listen --timeout=60
  4. php artisan queue:work


Localization

  1. App::setLocale('en');
  2. Lang::get('messages.welcome');
  3. Lang::get('messages.welcome', array('foo' => 'Bar'));
  4. Lang::has('messages.welcome');
  5. Lang::choice('messages.apples', 10);


Files

  1. File::exists('path');
  2. File::get('path');
  3. File::getRemote('path');
  4. File::getRequire('path');
  5. File::requireOnce('path');
  6. File::put('path', 'contents');
  7. File::append('path', 'data');
  8. File::delete('path');
  9. File::move('path', 'target');
  10. File::copy('path', 'target');
  11. File::extension('path');
  12. File::type('path');
  13. File::size('path');
  14. File::lastModified('path');
  15. File::isDirectory('directory');
  16. File::isWritable('path');
  17. File::isFile('file');
  18. File::glob($patterns, $flag);
  19. // Find path names matching a given pattern.
  20. File::files('directory');
  21. // Get an array of all files in a directory.
  22. File::allFiles('directory');
  23. // Get all of the files from the given directory (recursive).
  24. File::directories('directory');
  25. // Get all of the directories within a given directory.
  26. File::makeDirectory('path',  $mode = 0777, $recursive = false);
  27. File::copyDirectory('directory', 'destination', $options = null);
  28. File::deleteDirectory('directory', $preserve = false);
  29. File::cleanDirectory('directory');


Input

  1. Input::get('key');
  2. Input::get('key', 'default');
  3. // Default if the key is missing
  4. Input::has('key');
  5. Input::all();
  6. // Only retrieve 'foo' and 'bar' when getting input
  7. Input::only('foo', 'bar');
  8. // Disregard 'foo' when getting input
  9. Input::except('foo');


Session Input

  1. // Flash input to the session
  2. Input::flash();
  3. Input::flashOnly('foo', 'bar');
  4. Input::flashExcept('foo', 'baz');
  5. Input::old('key','default_value');


Files

  1. // Use a file that's been uploaded
  2. Input::file('filename');
  3. // Determine if a file was uploaded
  4. Input::hasFile('filename');
  5. // Access file properties
  6. Input::file('name')->getRealPath();
  7. Input::file('name')->getClientOriginalName();
  8. Input::file('name')->getSize();
  9. Input::file('name')->getMimeType();
  10. // Move an uploaded file
  11. Input::file('name')->move($destinationPath);
  12. // Move an uploaded file
  13. Input::file('name')->move($destinationPath, $fileName);


Cache

  1. Cache::put('key', 'value', $minutes);
  2. Cache::add('key', 'value', $minutes);
  3. Cache::forever('key', 'value');
  4. Cache::remember('key', $minutes, function(){ return 'value' });
  5. Cache::rememberForever('key', function(){ return 'value' });
  6. Cache::forget('key');
  7. Cache::has('key');
  8. Cache::get('key');
  9. Cache::get('key', 'default');
  10. Cache::get('key', function(){ return 'default'; });
  11. Cache::increment('key');
  12. Cache::increment('key', $amount);
  13. Cache::decrement('key');
  14. Cache::decrement('key', $amount);
  15. Cache::section('group')->put('key', $value);
  16. Cache::section('group')->get('key');
  17. Cache::section('group')->flush();


Cookies

  1. Cookie::get('key');
  2. // Create a cookie that lasts for ever
  3. Cookie::forever('key', 'value');
  4. // Send a cookie with a response
  5. $response = Response::make('Hello World');
  6. $response->withCookie(Cookie::make('name', 'value', $minutes));


Sessions

  1. Session::get('key');
  2. Session::get('key', 'default');
  3. Session::get('key', function(){ return 'default'; });
  4. Session::put('key', 'value');
  5. Session::all();
  6. Session::has('key');
  7. Session::forget('key');
  8. Session::flush();
  9. Session::regenerate();
  10. Session::flash('key', 'value');
  11. Session::reflash();
  12. Session::keep(array('key1', 'key2'));


Requests

  1. Request::path();
  2. Request::is('foo/*');
  3. Request::url();
  4. Request::segment(1);
  5. Request::header('Content-Type');
  6. Request::server('PATH_INFO');
  7. Request::ajax();
  8. Request::secure();


Responses

  1. return Response::make($contents);
  2. return Response::make($contents, 200);
  3. return Response::json(array('key' => 'value'));
  4. return Response::json(array('key' => 'value'))
  5.         ->setCallback(Input::get('callback'));
  6. return Response::download($filepath);
  7. return Response::download($filepath, $filename, $headers);
  8. // Create a response and modify a header value
  9. $response = Response::make($contents, 200);
  10. $response->header('Content-Type', 'application/json');
  11. return $response;
  12. // Attach a cookie to a response
  13. return Response::make($content)
  14.         ->withCookie(Cookie::make('key', 'value'));


Redirects

  1. return Redirect::to('foo/bar');
  2. return Redirect::to('foo/bar')->with('key', 'value');
  3. return Redirect::to('foo/bar')->withInput(Input::get());
  4. return Redirect::to('foo/bar')->withInput(Input::except('password'));
  5. return Redirect::to('foo/bar')->withErrors($validator);
  6. return Redirect::back();
  7. return Redirect::route('foobar');
  8. return Redirect::route('foobar', array('value'));
  9. return Redirect::route('foobar', array('key' => 'value'));
  10. return Redirect::action('FooController@index');
  11. return Redirect::action('FooController@baz', array('value'));
  12. return Redirect::action('FooController@baz', array('key' => 'value'));


IoC

  1. App::bind('foo', function($app){ return new Foo; });
  2. App::make('foo');
  3. App::make('FooBar');
  4. // If this class exists, it's returned
  5. App::singleton('foo', function(){ return new Foo; });
  6. App::instance('foo', new Foo);
  7. App::bind('FooRepositoryInterface', 'BarRepository');
  8. App::register('FooServiceProvider');
  9. App::resolving(function($object){});
  10. // Listen for object resolution


Security

Passwords

  1. Hash::make('secretpassword');
  2. Hash::check('secretpassword', $hashedPassword);
  3. Hash::needsRehash($hashedPassword);


Auth

  1. Auth::check();
  2. // Check if the user is logged in
  3. Auth::user();
  4. Auth::attempt(array('email' => $email, 'password' => $password));
  5. Auth::attempt($credentials, true);
  6. // Remember user login
  7. Auth::once($credentials);
  8. // Log in for a single request
  9. Auth::login(User::find(1));
  10. Auth::loginUsingId(1);
  11. Auth::logout();
  12. Auth::validate($credentials);
  13. Auth::basic('username');
  14. Auth::onceBasic();
  15. Password::remind($credentials, function($message, $user){});


Encryption

  1. Crypt::encrypt('secretstring');
  2. Crypt::decrypt($encryptedString);
  3. Crypt::setMode('ctr');
  4. Crypt::setCipher($cipher);


Validation

  1. Validator::make(
  2.         array('key' => 'Foo'),
  3.         array('key' => 'required


Rules

  1. accepted
  2. active_url
  3. after:YYYY-MM-DD
  4. before:YYYY-MM-DD
  5. alpha
  6. alpha_dash
  7. alpha_num
  8. between:1,10
  9. confirmed
  10. date
  11. date_format:YYYY-MM-DD
  12. different:fieldname
  13. email
  14. exists:table,column
  15. image
  16. in:foo,bar,baz
  17. not_in:foo,bar,baz
  18. integer
  19. numeric
  20. ip
  21. max:value
  22. min:value
  23. mimes:jpeg,png
  24. regex:[0-9]
  25. required
  26. required_if:field,value
  27. required_with:foo,bar,baz
  28. required_without:foo,bar,baz
  29. same:field
  30. size:value
  31. unique:table,column,except,idColumn
  32. url


Views

  1. View::make('path/to/view');
  2. View::make('foo/bar')->with('key', 'value');
  3. View::make('foo/bar', array('key' => 'value'));
  4. // Share a value across all views
  5. View::share('key', 'value');
  6. // Nesting views
  7. View::make('foo/bar')->nest('name', 'foo/baz', $data);
  8. // Register a view composer
  9. View::composer('viewname', function($view){});
  10. //Register multiple views to a composer
  11. View::composer(array('view1', 'view2'), function($view){});
  12. // Register a composer class
  13. View::composer('viewname', 'FooComposer');
  14. View::creator('viewname', function($view){});


Blade Templates

  1. @extends('layout.name')
  2. @section('name')
  3. // Begin a section
  4. @stop
  5. // End a section
  6. @yield('name')
  7. // Show a section name in a template
  8. @include('view.name')
  9. @include('view.name', array('key' => 'value'));
  10. @lang('messages.name')
  11. @choice('messages.name', 1);
  12. @if
  13. @else
  14. @elseif
  15. @endif
  16. @unless
  17. @endunless
  18. @for
  19. @endfor
  20. @foreach
  21. @endforeach
  22. @while
  23. @endwhile
  24. [[:Template:$var]]
  25. // Echo content
  26. {{{ $var }}}
  27. // Echo escaped content
  28. [[:Template:-- Blade Comment --]]


Forms

  1. Form::open(array('url' => 'foo/bar', 'method' => 'PUT'));
  2. Form::open(array('route' => 'foo.bar'));
  3. Form::open(array('route' => array('foo.bar', $parameter)));
  4. Form::open(array('action' => 'FooController@method'));
  5. Form::open(array('action' => array('FooController@method', $parameter)));
  6. Form::open(array('url' => 'foo/bar', 'files' => true));
  7. Form::token();
  8. Form::model($foo, array('route' => array('foo.bar', $foo->bar)));


Form Elements

  1. Form::label('id', 'Description');
  2. Form::label('id', 'Description', array('class' => 'foo'));
  3. Form::text('name');
  4. Form::text('name', $value);
  5. Form::hidden('foo', $value);
  6. Form::password('password');
  7. Form::email('name', $value, array());
  8. Form::file('name', array());
  9. Form::checkbox('name', 'value');
  10. Form::radio('name', 'value');
  11. Form::select('name', array('key' => 'value'));
  12. Form::select('name', array('key' => 'value'), 'key');
  13. Form::submit('Submit!');
  14. Form::macro('fooField', function()
  15. {
  16.         return '<input type="custom"/>';
  17. });
  18. Form::fooField();


HTML Builder

  1. HTML::macro('name', function(){});
  2. HTML::entities($value);
  3. HTML::decode($value);
  4. HTML::script($url, $attributes);
  5. HTML::style($url, $attributes);
  6. HTML::link($url, 'title', $attributes, $secure);
  7. HTML::secureLink($url, 'title', $attributes);
  8. HTML::linkAsset($url, 'title', $attributes, $secure);
  9. HTML::linkSecureAsset($url, 'title', $attributes);
  10. HTML::linkRoute($name, 'title', $parameters, $attributes);
  11. HTML::linkAction($action, 'title', $parameters, $attributes);
  12. HTML::mailto($email, 'title', $attributes);
  13. HTML::email($email);
  14. HTML::ol($list, $attributes);
  15. HTML::ul($list, $attributes);
  16. HTML::listing($type, $list, $attributes);
  17. HTML::listingElement($key, $type, $value);
  18. HTML::nestedListing($key, $type, $value);
  19. HTML::attributes($attributes);
  20. HTML::attributeElement($key, $value);
  21. HTML::obfuscate($value);


Strings

  1. Str::ascii($value)
  2. // Transliterate a UTF-8 value to ASCII.
  3. Str::camel($value)
  4. Str::contains($haystack, $needle)
  5. Str::endsWith($haystack, $needles)
  6. Str::finish($value, $cap)
  7. // Cap a string with a single instance of a given value.
  8. Str::is($pattern, $value)
  9. Str::length($value)
  10. Str::limit($value, $limit = 100, $end = '...')
  11. Str::lower($value)
  12. Str::words($value, $words = 100, $end = '...')
  13. Str::plural($value, $count = 2)
  14. Str::random($length = 16)
  15. // Generate a more truly "random" alpha-numeric string.
  16. Str::quickRandom($length = 16)
  17. // Generate a "random" alpha-numeric string.
  18. Str::upper($value)
  19. Str::title($value)
  20. Str::singular($value)
  21. Str::slug($title, $separator = '-')
  22. Str::snake($value, $delimiter = '_')
  23. Str::startsWith($haystack, $needles)
  24. Str::studly($value)
  25. // Convert a value to studly caps case.
  26. Str::macro($name, $macro)


Helpers

Arrays

  1. array_add($array, 'key', 'value');
  2. array_build($array, function(){});
  3. array_divide($array);
  4. array_dot($array);
  5. array_except($array, array('key'));
  6. array_fetch($array, 'key');
  7. array_first($array, function($key, $value){}, $default);
  8. array_flatten($array);
  9. // Strips keys from the array
  10. array_forget($array, 'foo');
  11. array_forget($array, 'foo.bar');
  12. // Dot notation
  13. array_get($array, 'foo', 'default');
  14. array_get($array, 'foo.bar', 'default');
  15. array_only($array, array('key'));
  16. array_pluck($array, 'key');
  17. // Return array of key => values
  18. array_pull($array, 'key');
  19. // Return and remove 'key' from array
  20. array_set($array, 'key', 'value');
  21. array_set($array, 'key.subkey', 'value');
  22. // Dot notation
  23. array_sort($array, function(){});
  24. head($array);
  25. // First element of an array
  26. last($array);
  27. // Last element of an array


Paths

  1. app_path();
  2. public_path();
  3. base_path();
  4. // App root path
  5. storage_path();


Strings

  1. camel_case($value);
  2. class_basename($class);
  3. e('<html>');
  4. // Escape a string
  5. starts_with('Foo bar.', 'Foo');
  6. ends_with('Foo bar.', 'bar.');
  7. snake_case('fooBar');
  8. str_contains('Hello foo bar.', 'foo');
  9. str_finish('foo/bar', '/');
  10. // Result: foo/bar/
  11. str_is('foo*', 'foobar');
  12. str_plural('car');
  13. str_random(25);
  14. str_singular('cars');
  15. studly_case('foo_bar');
  16. // Result: FooBar
  17. trans('foo.bar');
  18. trans_choice('foo.bar', $count);


URLs and Links

  1. action('FooController@method', $parameters);
  2. link_to('foo/bar', $title, $attributes, $secure);
  3. link_to_asset('img/foo.jpg', $title, $attributes, $secure);
  4. link_to_route('route.name', $title, $parameters, $attributes);
  5. link_to_action('FooController@method', $title, $params, $attrs);
  6. asset('img/photo.jpg', $title, $attributes);
  7. // HTML Link
  8. secure_asset('img/photo.jpg', $title, $attributes);
  9. // HTTPS link
  10. secure_url('path', $parameters);
  11. route($route, $parameters, $absolute = true);
  12. url('path', $parameters = array(), $secure = null);


Miscellaneous

  1. csrf_token();
  2. dd($value);
  3. value(function(){ return 'bar'; });
  4. with(new Foo)->chainedMethod();