Laravel Cheat Sheet is a cheat sheet for creating web apps with the Laravel framework using the PHP language. Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern and based on Symfony. Most of the summaries and examples are based on the official documentation.

Laravel Queue

Queue::push('SendMail', array('message' => $message));
Queue::push('SendEmail@send', array('message' => $message));
Queue::push(function($job) use $id {});

Same payload to multiple workers

Queue::bulk(array('SendEmail', 'NotifyUser'), $payload);

Starting the queue listener

php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60

Process only the first job on the queue

php artisan queue:work

Start a queue worker in daemon mode

php artisan queue:work --daemon

Create migration file for failed jobs

php artisan queue:failed-table

Listing failed jobs

php artisan queue:failed

Delete failed job by id

php artisan queue:forget 5

Delete all failed jobs

php artisan queue:flush

Laravel Redirect

return Redirect::to('foo/bar');
return Redirect::to('foo/bar')->with('key', 'value');
return Redirect::to('foo/bar')->withInput(Input::get());
return Redirect::to('foo/bar')->withInput(Input::except('password'));
return Redirect::to('foo/bar')->withErrors($validator);

Create a new redirect response to the previous location

return Redirect::back();

Create a new redirect response to a named route

return Redirect::route('foobar');
return Redirect::route('foobar', array('value'));
return Redirect::route('foobar', array('key' => 'value'));

Create a new redirect response to a controller action

return Redirect::action('FooController@index');
return Redirect::action('FooController@baz', array('value'));
return Redirect::action('FooController@baz', array('key' => 'value'));

If intended redirect is not defined, defaults to foo/bar.

return Redirect::intended('foo/bar');

Laravel Route

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

RESTful Controllers

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']]);

Triggering Errors

App::abort(404);
$handler->missing(...) in ErrorServiceProvider::boot();
throw new NotFoundHttpException;

Route Parameters

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

HTTP Verbs

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(){});

Secure Routes(TBD)

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

Route Constraints

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]'))

Set a pattern to be used across routes

Route::pattern('bar', '[0-9]+')

HTTP Middleware

Assigning Middleware To Routes

Route::get('admin/profile', ['middleware' => 'auth', function(){}]);

Named Routes

Route::currentRouteName();
Route::get('foo/bar', array('as' => 'foobar', function(){}));
Route::get('user/profile', [
  'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
$url = route('profile');
$redirect = redirect()->route('profile');

Route Prefixing

Route::group(['prefix' => 'admin'], function()
{
  Route::get('users', function(){
      return 'Matches The "/admin/users" URL';
  });
});

Route Namespacing

This route group will carry the namespace ‘Foo\Bar’

Route::group(array('namespace' => 'Foo\Bar'), function(){})

Sub-Domain Routing

{sub} will be passed to the closure

Route::group(array('domain' => '{sub}.example.com'), function(){});

Laravel Config

Config::get('app.timezone');

get with Default value

Config::get('app.timezone', 'UTC');

set Configuration

Config::set('database.default', 'sqlite');

Laravel File

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');

Lang

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');

Laravel SSH

Executing Commands

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;
});

Tasks

define

SSH::define($taskName, array $commands);

execute

SSH::task($taskName, function($line)
{
  echo $line.PHP_EOL;
});

SFTP Uploads

SSH::put($localFile, $remotePath);
SSH::putString($string, $remotePath);

Laravel Cache

Cache::put('key', 'value', $minutes);
Cache::add('key', 'value', $minutes);
Cache::forever('key', 'value');
Cache::remember('key', $minutes, function(){ return 'value' });
Cache::rememberForever('key', function(){ return 'value' });
Cache::forget('key');
Cache::has('key');
Cache::get('key');
Cache::get('key', 'default');
Cache::get('key', function(){ return 'default'; });
Cache::tags('my-tag')->put('key','value', $minutes);
Cache::tags('my-tag')->has('key');
Cache::tags('my-tag')->get('key');
Cache::tags('my-tag')->forget('key');
Cache::tags('my-tag')->flush();
Cache::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);
Cache::section('group')->put('key', $value);
Cache::section('group')->get('key');
Cache::section('group')->flush();

Laravel HTML

HTML::macro('name', function(){});

Convert an HTML string to entities

HTML::entities($value);

Convert entities to HTML characters

HTML::decode($value);

Generate a link to a JavaScript file

HTML::script($url, $attributes);

Generate a link to a CSS file

HTML::style($url, $attributes);

Generate an HTML image element

HTML::image($url, $alt, $attributes);

Generate a HTML link

HTML::link($url, 'title', $attributes, $secure);

Generate a HTTPS HTML link

HTML::secureLink($url, 'title', $attributes);

Generate a HTML link to an asset

HTML::linkAsset($url, 'title', $attributes, $secure);

Generate a HTTPS HTML link to an asset

HTML::linkSecureAsset($url, 'title', $attributes);

Generate a HTML link to a named route

HTML::linkRoute($name, 'title', $parameters, $attributes);

Generate a HTML link to a controller action

HTML::linkAction($action, 'title', $parameters, $attributes);

Generate a HTML link to an email address

HTML::mailto($email, 'title', $attributes);

Obfuscate an e-mail address to prevent spam-bots from sniffing it

HTML::email($email);

Generate an ordered list of items

HTML::ol($list, $attributes);

Generate an un-ordered list of items

HTML::ul($list, $attributes);

Create a listing HTML element

HTML::listing($type, $list, $attributes);

Create the HTML for a listing element

HTML::listingElement($key, $type, $value);

Create the HTML for a nested listing attribute

HTML::nestedListing($key, $type, $value);

Build an HTML attribute string from an array

HTML::attributes($attributes);

Build a single attribute element

HTML::attributeElement($key, $value);

Obfuscate a string to prevent spam-bots from sniffing it

HTML::obfuscate($value);

Laravel Model

Basic Usage

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';
}

More

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();

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::remember(5)->get();
Model::remember(5, 'cache-key-name')->get();
Model::cacheTags('my-tag')->remember(5)->get();
Model::cacheTags(array('my-first-key','my-second-key'))->remember(5)->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');

Soft Delete

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();

Events

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);

Eloquent Configuration

Disables mass assignment exceptions from being thrown from model inserts and updates

Eloquent::unguard();

Renables any ability to throw mass assignment exceptions

Eloquent::reguard();

Laravel DB Cheat Sheet

Basic Database Usage

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();

Laravel Query Builder

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();

Laravel Joins

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();

Laravel Aggregates

$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');

DB::table('name')->remember(5)->get();
DB::table('name')->remember(5, 'cache-key-name')->get();
DB::table('name')->cacheTags('my-key')->remember(5)->get();
DB::table('name')->cacheTags(array('my-first-key','my-second-key'))->remember(5)->get();

Laravel Raw Expressions

$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();

#laravel #php #developer

Laravel Cheat Sheet - Simple Cheat Sheet for Laravel
34.60 GEEK