Laravel Cheat Sheet - Simple Cheat Sheet for Laravel

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


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

$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::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}'), function(){});

Laravel Config


get with Default value

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

set Configuration

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

Laravel File


Get a file’s contents by requiring it


Require the given file once


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


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


Get the file type of a given file


Get the file size of a given file


Get the file’s last modification time


Determine if the given path is a directory


Determine if the given path is writable


Determine if the given path is a file


Find path names matching a given pattern.

File::glob($patterns, $flag);

Get an array of all files in a directory.


Get all of the files from the given directory (recursive).


Get all of the directories within a given 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



Lang::get('messages.welcome', array('foo' => 'Bar'));
Lang::choice('messages.apples', 10);

Lang::get alias


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;



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


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::get('key', 'default');
Cache::get('key', function(){ return 'default'; });
Cache::tags('my-tag')->put('key','value', $minutes);
Cache::increment('key', $amount);
Cache::decrement('key', $amount);
Cache::section('group')->put('key', $value);

Laravel HTML

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

Convert an HTML string to entities


Convert entities to HTML characters


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


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


Build a single attribute element

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

Obfuscate a string to prevent spam-bots from sniffing it


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


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!


Find using dual primary key

Model::find(array('first', 'last'));

Throw an exception if the lookup fails


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



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, 'cache-key-name')->get();

Default Eloquent sort is ascendant


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


Model::observe(new FooObserver);

Eloquent Configuration

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


Renables any ability to throw mass assignment exceptions


Laravel DB Cheat Sheet

Basic Database Usage


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::table('users')->update(['votes' => 1]);

Laravel Query Builder

Retrieving All Rows From A Table


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

Retrieving A Single Column From A Row

$name = DB::table('users')->where('name', 'John')->pluck('name');

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

Dynamic Where Clauses

$admin = DB::table('users')->whereId(1)->first();
$john = DB::table('users')
->whereIdAndEmail(2, '')
$jane = DB::table('users')
->whereNameOrAge('Jane', 22)

Order By, Group By, And Having

$users = DB::table('users')
->orderBy('name', 'desc')
->having('count', '>', 100)
DB::table('name')->having('count', '>', 100)->get();

Offset & Limit

$users = DB::table('users')->skip(10)->take(5)->get();

Laravel Joins

Basic Join Statement

          ->join('contacts', '', '=', 'contacts.user_id')
          ->join('orders', '', '=', 'orders.user_id')
          ->select('', '', 'orders.price')

Left Join Statement

      ->leftJoin('posts', '', '=', 'posts.user_id')

select * from users where name = ‘John’ or (votes > 100 and title <> ‘Admin’)

          ->where('name', '=', 'John')
              $query->where('votes', '>', 100)
                    ->where('title', '<>', 'Admin');

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, 'cache-key-name')->get();

Laravel Raw Expressions

$users = DB::table('users')
                   ->select(DB::raw('count(*) as user_count, status'))
                   ->where('status', '<>', 1)

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

What is GEEK

Buddha Community

Laravel Cheat Sheet - Simple Cheat Sheet for Laravel
Seamus  Quitzon

Seamus Quitzon


Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
    protected $fillable = [

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.


Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

Juned Ghanchi


Laravel App Development Company in India, Hire Laravel Developers

Hire our expert team of Laravel app developers for flexible PHP applications across various cloud service providers.

With this easy build technology, we develop feature-rich apps that make your complex business process a lot easier. Our apps are,

  • More secure and scalable.
  • A good framework lets you manage and organize resources better.
  • And have a rich community base.

Get your business a best in classlaravel app. Hire laravel app developers in India. We have the best organizational set-up to provide you the most advanced app development services.

#laravel app development company india #hire laravel developers india #laravel app development company #hire laravel developers #laravel development agency #laravel app programmers

sophia tondon

sophia tondon


Top Laravel Development Company India | Laravel Development Services

Laravel is a popular framework for website development, acquiring 25.85% of the PHP framework market share. As a most admired framework among PHP frameworks, it is being utilized for e-commerce, enterprise, social media, and various different types of websites.

There are more than 1 million websites worldwide available over the web that are created using Laravel. Laravel framework is the first preference of PHP developers as it allows them to develop highly scalable, flexible, and faster web applications.

Surely, you, too, would want to deliver a splendid and unhindered user experience to your target audience over the web. Laravel framework can help you achieve this pursuit at ease; all you need to do is hire Laravel developers from reliable & coveted hosts. But! There is no shortage of Laravel development companies that promise to deliver an excellent solution, but only some are able to deliver top-notch quality.

Therefore, I have decided to enlist top Laravel development companies to help you find a reliable and expert host for web development. So, stay hooked with me till the end of this article and explore the best Laravel developers in 2021.

While creating this list, I have kept the following pointers in reflection:

Years of excellence (average 8 years)
Rewards & Recognition
Client rating & feedback
Hourly/Monthly Price
Number of happy clients
Number of successfully launched projects
Minimum man-years experience
So, let’s not waste a minute and glance at top Laravel development companies to hire for creating excellent web solutions.

Read More -

#hire a laravel developer #hire laravel developer #hire laravel developers #laravel developer for hire #laravel developers #laravel developers for hire

sophia tondon

sophia tondon


Hire Laravel Developers | Laravel Development Company, Services India

Looking for a team of experienced offshore Laravel developers? Hire a top dedicated team of Laravel developers from India online with 6+ years of average experience on an hourly or dedicated (monthly) basis from ValueCoders and enjoy easy hiring, quality work, and on-demand scalability at up to 60% less cost.

Our offshore Laravel development experts are fully competent to build scalable, secure, and robust custom web apps suiting your business requirements.

First Time Right Process
Complete Control Over The Team
Certified Laravel Coders
Agile & DevOps Enablement
Non-Disclosure Agreement
No Contract Lock-Ins

Visit Us-

#hire a laravel developer #hire laravel developer #laravel development #hire laravel experts #find laravel developers #laravel development services india

Seamus  Quitzon

Seamus Quitzon


How to perform migration rollback in laravel

As we know that laravel migration provides very simple way to create database table structure. We need to create migration file and write table structure then migrate that migration. Sometimes we need to rollback that migration. So here we will discuss about the migration rollback in laravel.

We can run the rollback artisan command to rollback on a particular step. We can execute the following artisan command.

php artisan migrate:rollback --step=1

Every time when we will rollback, we will get the last batch of migration.

**Note: **This rollback command will work on laravel 5.3 or above version. For the version below 5.3, there is no command available for migration rollback in laravel.

We can also use the following command to rollback and re migrate.

php artisan migrate:refresh --step=2

It will rollback and remigrate last two migration.

You can also checkout the article for executing single migration by clicking on the link below.

How to migrate single migration in laravel

#laravel #how to perform rollback migration in laravel #laravel migration rollback #migration refresh in laravel #migration rollback batch in laravel #migration rollback for one specific migration #migration rollback in laravel