Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laravel 4 Eloquent Cheat Sheet.

Conventions:

Defining Eloquent model (will assume that DB table named is set as plural of class name and primary key named "id"):

class Shop extends Eloquent {}

Using custom table name

protected $table = 'my_shops';

Using custom primary key (instead of "id"):

protected $primaryKey = 'my_key';

Disabling use of "created_at" and "updated_at" columns:

public $timestamps = false;

Retrieving records:

Retrieving all records(rows) of a given model:

$shops = Shop::all();

Find and get a record by primary key:

$shop = Shop::find(1);

Retrieving single record that matches a certain column : $shop = Shop::where('name', 'Starbucks')->first();

Retrieving specific columns of the result (by default get() returns all columns): $shops = Shop::where('name', 'Starbucks')->get('name','address','url');

Retrieving single column of result : $shopAddresses = Shop::where('name', 'Starbucks')->pluck('address');

Retrieving records matching a criteria:

$profitableShops = Shop::where('orders_cache','>','100')->get(); where() takes 3 parameters, name of the column, operator and value to be compared against. The operator can be one of the following: '=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike'

Retrieve only a specified number of records matching a criteria:

$californianShops = Shop::where('state', 'CA')->take(10)->get();

Skip a specified number of records:

$someShops = Shops::where('name', 'Starbucks')->skip(10)->get();

Combining "skip" and "take" (useful for making custom paginators):

$shops = Shops::where('name', 'Starbucks')->skip(25)->take(25)->get();

Using forPage() to accomplish the above statement:

$shops = Shops::where('name', 'Starbucks')->forPage(2,25)->get();

Aggregates

Counting the number of rows of the query results:

$countStarbucks = Shop::where('name','Starbucks')->count();

Getting a maximum value of the query result:

$maxCoffeePrice = Product::where('name','Coffee')->max('price');

Getting a minimum value of the query result:

$minCoffeePrice = Product::where('name','Coffee')->min('price');

Getting an average value of the query result:

$averageCoffeePrice = Product::where('name','Coffee')->avg('price');

Getting a sum of the query result:

$totalWeight = Product::where('name','Coffee')->sum('weight');

Incrementing and decrementing values of a column:

Shop::where('orders_cache','>','100')->increment('orders_cache');

Shop::where('orders_cache','>','100')->decrement('orders_cache');

Todo :

  • or, between, whereNull, whereIn
  • inserts
  • updates
  • deletes
  • soft deletes
  • unions
  • raw expressions
  • grouping
  • joins
  • Fillable
  • Guarded
@dedurus

This comment has been minimized.

Show comment
Hide comment
@dedurus

dedurus May 28, 2013

One correction:
$shops = Shop::where('name', 'Starbucks')->get('name','address','url');

should be

$shops = Shop::where('name', 'Starbucks')->get( array('name','address','url') );

get() takes an array as a parameter

dedurus commented May 28, 2013

One correction:
$shops = Shop::where('name', 'Starbucks')->get('name','address','url');

should be

$shops = Shop::where('name', 'Starbucks')->get( array('name','address','url') );

get() takes an array as a parameter

@drakakisgeo

This comment has been minimized.

Show comment
Hide comment
@drakakisgeo

drakakisgeo Nov 12, 2013

Its a Laravel3 thing :-)

Its a Laravel3 thing :-)

@tacticalcom

This comment has been minimized.

Show comment
Hide comment
@tacticalcom

tacticalcom Dec 4, 2013

This is great. Thanks for posting!

I'm curious how you would do the following statement:

select * from foo where bar in (1,3,10);

Currently I'm doing this:

Foo::where('bar',1)
    ->orWhere('bar',3)
    ->orWhere('bar',10);

But what I hope is that there is something like this:

Foo::where('bar','in',array(1,3,10));

This is great. Thanks for posting!

I'm curious how you would do the following statement:

select * from foo where bar in (1,3,10);

Currently I'm doing this:

Foo::where('bar',1)
    ->orWhere('bar',3)
    ->orWhere('bar',10);

But what I hope is that there is something like this:

Foo::where('bar','in',array(1,3,10));
@Manc

This comment has been minimized.

Show comment
Hide comment
@Manc

Manc Dec 12, 2013

@tacticalcom, try:
Foo::whereIn('bar', array(1,3,10));

Manc commented Dec 12, 2013

@tacticalcom, try:
Foo::whereIn('bar', array(1,3,10));

@reviloera

This comment has been minimized.

Show comment
Hide comment
@reviloera

reviloera Feb 20, 2014

Thank you Saved me a great deal of time

Thank you Saved me a great deal of time

@eheuristic

This comment has been minimized.

Show comment
Hide comment
@eheuristic

eheuristic May 23, 2014

This is great post.
most of functionality covered in this post of Laravel
Thanks!

This is great post.
most of functionality covered in this post of Laravel
Thanks!

@ASFnetwork

This comment has been minimized.

Show comment
Hide comment
@ASFnetwork

ASFnetwork Jul 14, 2014

how to count a distinct will be?

how to count a distinct will be?

@wilbertverayin

This comment has been minimized.

Show comment
Hide comment
@wilbertverayin

wilbertverayin Jul 22, 2014

how about getting all columns of a table?

how about getting all columns of a table?

@shoaibnawaz

This comment has been minimized.

Show comment
Hide comment
@shoaibnawaz

shoaibnawaz Aug 18, 2014

SELECT foo, bar from mytable;
MyModel::all() returns all the rows with all columns but I need only few columns. I do not want to specify $hidden in model.
I think ->get(array('foo', 'bar')) will work on Illuminate\Database\Eloquent\Builder and for that I need to use MyModel::where()
According to documentation, where() and get() both are part of builder.
So how to get selected columns for all records without calling where()?

SELECT foo, bar from mytable;
MyModel::all() returns all the rows with all columns but I need only few columns. I do not want to specify $hidden in model.
I think ->get(array('foo', 'bar')) will work on Illuminate\Database\Eloquent\Builder and for that I need to use MyModel::where()
According to documentation, where() and get() both are part of builder.
So how to get selected columns for all records without calling where()?

@Wendtly

This comment has been minimized.

Show comment
Hide comment
@Wendtly

Wendtly Sep 11, 2014

Model::get(['field1','field2']);

Wendtly commented Sep 11, 2014

Model::get(['field1','field2']);

@tucq88

This comment has been minimized.

Show comment
Hide comment
@tucq88

tucq88 Nov 7, 2014

Please add some example about complex queries or multi conditions queries. I couldn't find any good example over internet :(

tucq88 commented Nov 7, 2014

Please add some example about complex queries or multi conditions queries. I couldn't find any good example over internet :(

@apache123

This comment has been minimized.

Show comment
Hide comment
@apache123

apache123 Nov 7, 2014

please add information about relationship in eloquent the docs is not clear

please add information about relationship in eloquent the docs is not clear

@ArtemFitiskin

This comment has been minimized.

Show comment
Hide comment
@ArtemFitiskin

ArtemFitiskin Nov 30, 2014

You wrote that by default get() returns all columns:

$shops = Shop::where('name', 'Starbucks')->get('name','address','url');

But nothing about how to do for get only one row (maybe it is not best solution):

$shop = Shop::where('name', 'Starbucks')->select(array('name','address','url'))->first();

You wrote that by default get() returns all columns:

$shops = Shop::where('name', 'Starbucks')->get('name','address','url');

But nothing about how to do for get only one row (maybe it is not best solution):

$shop = Shop::where('name', 'Starbucks')->select(array('name','address','url'))->first();
@HashmatWaziri

This comment has been minimized.

Show comment
Hide comment
@HashmatWaziri

HashmatWaziri Jun 21, 2015

how do you pass distinct values from database to select boxes?

how do you pass distinct values from database to select boxes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment