You are on page 1of 26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

SampleApplication

AGuidetoUsingEloquentORMin
Laravel
Share

ChrisSevilleja

March3,2014

61Comments

Tweet

crud,eloquent,laravel

VIEWCODE

TheEloquentORMthatcomeswithLaravelmakesitincrediblyeasytointeract
withadatabase.TodaywelllookathowwecanuseEloquenttointeractwith
ourdatabaseanddo:
ThebasicCRUDfunctions
Setupanduseonetoonerelationships
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

1/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

Setupanduseonetomanyrelationships
Setupandusemanytomanyrelationships

HowDoesEloquentWork?
TheEloquentORMprovidesanActiveRecordimplementationtoworkwithyourdatabase.
ThismeansthateachmodelyoucreateinyourMVCstructurecorrespondstoatablein
yourdatabase.
A Bear modelwillcorrespondtoa bears tableinyourdatabase.Sincewehave
conventionwhencreatingourmodelsanddatabasetables,wecaneasilycalldatafrom
ourdatabase.
Forexample,togetall bears froma Bear model,allyouwoulddois Bear::all() .Using
thisfunctionwouldquerythedatabaseandgeneratetheproperSQLcommand.Hereare
somequickexamples:

Supersimple!Therearemanymoreapplicationsofthisandwellgetintothemfarther
intothisarticle.

SampleApplication
Letscreateasampleapplicationabout bears .Letssaytherearemanybears.Thereare
differenttypesofbearswithdifferentweightsanddangerlevels.
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

2/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

Wewillalsosaythereare fish .Eachfishbelongstoasinglebearsincebearsdontlike


sharing.Thiswillbeouronetoonerelationship.
Bearsalsolovetoclimb trees .Eachbearwillhavemanytreestheyliketoclimb.This
willbeouronetomanyrelationship.
Therewillalsobe picnics .Manybearscangotomanypicnicssincetheyliketo
ransackasmanydeliciouspicnicsastheycan.Thiswillbeourmanytomany
relationship.

LaravelSetup
TogetstartedusingEloquent,wellneedtosetupourdatabaseandapplication.Lets
runthroughthatrealquick.Wellneedto:
InstallLaravel: composerinstallpreferdist
Changeourdatabasesettingsin app/config/database.php
Createmigrationsusingartisan
CreateEloquentmodels
Seedourdatabase
Thosefirsttwopartsareeasyenoughsogetthosedone.Thenwellworkonmigrating
andseedingourdatabase.
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

3/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

CreatingOurMigrations
Withourmigrations,wewillbeaddingthreetablestoourdatabase: bears , fish ,
and picnics .Formoreinformationonusingmigrations,readtheLaraveldocs.

Migrations
BearsMigration
Letscreateourmigration.Throughthecommandline,type:
phpartisanmigrate:makecreate_bears_tablecreate=bears

Letsgoinandaddourfields.

//app/database/migrations/####_##_##_######_create_bears_table.php
...
Schema::create('bears',function(Blueprint$table)
{
$table>increments('id');

$table>string('name');
$table>string('type');
$table>integer('danger_level');//thiswillbebetween110
$table>timestamps();
});
...

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

4/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

Bydefault,thesemigrationswillincludeanautoincrementing id .Itwillalsoinclude
timestampsforthefields created_at and updated_at .updated_atwillbeautomatically
updatedwhenevertherecordisupdated.

FishMigration
phpartisanmigrate:makecreate_fish_tablecreate=fish

//app/database/migrations/####_##_##_######_create_fish_table.php
...
Schema::create('fish',function(Blueprint$table)
{
$table>increments('id');

$table>integer('weight');//we'llusethistodemonstratesearchingbyweigh
t
$table>integer('bear_id');//thiswillcontainourforeignkeytothebears
table
$table>timestamps();
});
...

PluralvsSingularDatabaseTableNamesWithourbears,wecancreate
thestandardpluraltablename(iebears,picnics).Withfish,itsdifferent.
Doweusefishorfishes?Thegoodnewsiswecanusewhicheverwewant
andthenoverridethedefaultswhendefiningour Eloquentmodel .

TreeMigration
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

5/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

phpartisanmigrate:makecreate_trees_tablecreate=trees

//app/database/migrations/####_##_##_######_create_trees_table.php
...
Schema::create('trees',function(Blueprint$table)
{
$table>increments('id');

$table>string('type');
$table>integer('age');//howoldisthetree
$table>integer('bear_id');//whichbearclimbsthistree
$table>timestamps();
});
...

PicnicMigration
Sincewewillbecreatingaonetomanyrelationship,wewillneedtwotables.Onefor
thepicnicsandanothertolinkabeartoapicnic.
phpartisanmigrate:makecreate_picnics_tablecreate=picnics

//app/database/migrations/####_##_##_######_create_picnics_table.php
...
Schema::create('picnics',function(Blueprint$table)
{
$table>increments('id');

$table>string('name');
$table>integer('taste_level');//howtastyisthispicnic?
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

6/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

$table>timestamps();
});
...

Nowwewillneedatabletolinkourbearstoapicnic.Wellcreateapivottablehere.This
ishowwecandefineourmanytomanyrelationship.
phpartisanmigrate:makecreate_bears_picnics_tablecreate=bears_picnics

//app/database/migrations/####_##_##_######_create_bears_picnics_table.php
...
Schema::create('bears_picnics',function(Blueprint$table)
{
$table>increments('id');

$table>integer('bear_id');//theidofthebear
$table>integer('picnic_id');//theidofthepicnicthatthisbearisat
$table>timestamps();
});
...

Nowwehaveawaytolinkourmultiplebearstomultiplepicnics.Thisishowwecreate
ourmanytomanyrelationship.

MigratingOurDatabase

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

7/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

Withourmigrationfilesmade,migrateyourdatabaseusingartisan:
phpartisanmigrate

EloquentModels
Nowthatwehavemigratedourdatabase,wewillneedtoseedourdatabase.The
processofseedinghoweverisinsertingrecordsintoourdatabaseandthiswillrequire
Eloquent!Wewillneedtocreateourmodelsbeforewecanseedthedatabase.
LetsmakeourEloquentmodels.Thisisalsowherewewilldefineourrelationships.

BearModel
Letslookatour Bear modelfirst.

//app/models/Bear.php
<?php
classBearextendsEloquent{

//MASSASSIGNMENT
//definewhichattributesaremassassignable(forsecurity)
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

8/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

//weonlywantthese3attributesabletobefilled
protected$fillable=array('name','type','danger_level');
//DEFINERELATIONSHIPS
//eachbearHASonefishtoeat
publicfunctionfish(){
return$this>hasOne('Fish');//thismatchestheEloquentmodel
}
//eachbearclimbsmanytrees
publicfunctiontrees(){
return$this>hasMany('Tree');
}
//eachbearBELONGStomanypicnic
//defineourpivottablealso
publicfunctionpicnics(){
return$this>belongsToMany('Picnic','bears_picnics','bear_id','picnic_
id');
}
}

MassAssignmentWehavetosetourmassassignableattributessothatwemakesure
thatonlytheattributeswewantareallowedtobechanged.
DefiningRelationshipsWhendefiningrelationships,thenameofthefunctioncanbe
whateveryouwantittobenamed.Itmakessenseheresincewewillbefinding
the fish thatbelongstothebear.Ontheline return$this>hasOne('Fish') however,
youwillneedtomatchthenameoftheEloquentmodelthatcorrespondstothatitem.
Therearedifferentwayswecandefinerelationships.There
are hasOne , hasMany , belongsTo , belongsToMany ,andmore.ReadtheEloquent
Relationshipdocstoseeallthethingsyoucando.
EloquentModelandDatabaseTableNamingConventionsBydefault,whenyoudefine
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

9/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

anEloquentmodel,younameitforthesingularterm.Inthiscase Bear .Eloquentwillthen


looktothedatabaseforthelowercaseandpluralversionofthatword.Inthiscase,this
modelwillbelinkedtoour bears tablewecreatedinourmigration.

FishModel
Hereisour Fish model.

//app/models/Fish.php
<?php
classFishextendsEloquent{

//MASSASSIGNMENT
//definewhichattributesaremassassignable(forsecurity)
//weonlywantthese3attributesabletobefilled
protected$fillable=array('weight','bear_id');
//LINKTHISMODELTOOURDATABASETABLE
//sincethepluraloffishisntwhatwenamedourdatabasetablewehavetod
efineit
protected$table='fish';
//DEFINERELATIONSHIPS
publicfunctionbear(){
return$this>belongsTo('Bear');
}
}

Likewetalkedaboutearlier,sincewenamedourtable fish ,thenitdoesntfollow


convention.Wewillexplicitlycalloutthedatabasenameusing protected$table .
Similartohowwedefinedourrelationshipinthe Bear model,wewilldefinetheinverseof
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

10/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

thatrelationship.A Fish belongstoa Bear .

TreeModel

//app/models/Tree.php
<?php
classTreeextendsEloquent{

//MASSASSIGNMENT
//definewhichattributesaremassassignable(forsecurity)
//weonlywantthese3attributesabletobefilled
protected$fillable=array('type','age','bear_id');
//DEFINERELATIONSHIPS
publicfunctionbear(){
return$this>belongsTo('Bear');
}
}

PicnicModel
Youknowthedrillnow.Letsmakethe Picnic model.

//app/models/Picnic.php
<?php
classPicnicextendsEloquent{

//MASSASSIGNMENT
//definewhichattributesaremassassignable(forsecurity)
//weonlywantthese3attributesabletobefilled
protected$fillable=array('name','taste_level');
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

11/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

//DEFINERELATIONSHIPS
//defineamanytomanyrelationship
//alsocallthelinkingtable
publicfunctionbears(){
return$this>belongsToMany('Bear','bears_picnics','picnic_id','bear_id
');
}
}

Justlikeourothermodels,wehavedefinedmassassignableattributesandrelationships.
Whendefiningmanytomanyrelationships,youuse belongsToMany() andnot
hasMany. hasMany isusedforonetomanyrelationships.
Nowthatwehaveourmigrationsandmodelsdone,wecanseedourdatabase.Wewill
useEloquentforinsertingintoourdatabaseforourseeds.
FormoreinformationonEloquentconceptslikecreatingEloquentmodels,performing
CRUD,ordefiningrelationships,definitelyreadtheLaravelEloquentdocs.

SeedingOurDatabase
Forthoseofyouwhodontknow,seedingallowsustofillourdatabasewithdummy
informationtoplaywith.Thisisgreatwhendevelopingourapplicationsandneeddatato
populateourapplication.
Wewillcreatedatabaseseedersinsideofthe app/database/seeds/DatabaseSeeder.php .
Usuallyyouwouldwanttocreateseparateseedfiles,butweregoingtodumpeverything
intothisfiletomakethissimple.(WewanttogettoqueryingthingswithEloquent
already!)

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

12/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

//app/database/seeds/DatabaseSeeder.php
<?php
classDatabaseSeederextendsSeeder{
/**
*Runthedatabaseseeds.
*
*@returnvoid
*/
publicfunctionrun()
{
Eloquent::unguard();
//callourclassandrunourseeds
$this>call('BearAppSeeder');
$this>command>info('Bearappseedsfinished.');//showinformationint
hecommandlineaftereverythingisrun
}
}
//ourownseederclass
//usuallythiswouldbeitsownfile
classBearAppSeederextendsSeeder{

publicfunctionrun(){
//clearourdatabase
DB::table('bears')>delete();
DB::table('fish')>delete();
DB::table('picnics')>delete();
DB::table('trees')>delete();
DB::table('bears_picnics')>delete();
//seedourbearstable
//we'llcreatethreedifferentbears
//bear1isnamedLawly.Sheisextremelydangerous.Especiallywhenhung
ry.
$bearLawly=Bear::create(array(
'name'=>'Lawly',
'type'=>'Grizzly',
'danger_level'=>8
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

13/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

));
//bear2isnamedCerms.Hehasaloudgrowlbutisprettymuchharmless.
$bearCerms=Bear::create(array(
'name'=>'Cerms',
'type'=>'Black',
'danger_level'=>4
));
//bear3isnamedAdobot.Heisapolarbear.Hedrinksvodka.
$bearAdobot=Bear::create(array(
'name'=>'Adobot',
'type'=>'Polar',
'danger_level'=>3
));
$this>command>info('Thebearsarealive!');
//seedourfishtable
//ourfishwonthavenames...becausetheyregoingtobeeaten
//wewillusethevariablesweusedtocreatethebearstogettheirid
Fish::create(array(
'weight'=>5,
'bear_id'=>$bearLawly>id
));
Fish::create(array(
'weight'=>12,
'bear_id'=>$bearCerms>id
));
Fish::create(array(
'weight'=>4,
'bear_id'=>$bearAdobot>id
));

$this>command>info('Theyareeatingfish!');
//seedourtreestable
Tree::create(array(
'type'=>'Redwood',
'age'=>500,
'bear_id'=>$bearLawly>id
));
Tree::create(array(
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

14/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

'type'=>'Oak',
'age'=>400,
'bear_id'=>$bearLawly>id
));
$this>command>info('Climbbears!Befree!');
//seedourpicnicstable
//wewillcreateonepicnicandapplyallbearstothisonepicnic
$picnicYellowstone=Picnic::create(array(
'name'=>'Yellowstone',
'taste_level'=>6
));
$picnicGrandCanyon=Picnic::create(array(
'name'=>'GrandCanyon',
'taste_level'=>5
));

//linkourbearstopicnics
//forourpurposeswe'lljustaddallbearstobothpicnicsforourmany
tomanyrelationship
$bearLawly>picnics()>attach($picnicYellowstone>id);
$bearLawly>picnics()>attach($picnicGrandCanyon>id);
$bearCerms>picnics()>attach($picnicYellowstone>id);
$bearCerms>picnics()>attach($picnicGrandCanyon>id);
$bearAdobot>picnics()>attach($picnicYellowstone>id);
$bearAdobot>picnics()>attach($picnicGrandCanyon>id);
$this>command>info('Theyareterrorizingpicnics!');
}
}

SeedingaDatabasewithRelationships
Inourseederfile,wearecreatingbears,fish,picnics,andlinkingmanybearstoone
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

15/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

picnic.
GrabbingtheIDofaNewlyCreatedRecordWeneedtograbtheidoftheinserted
bearsandpicnicsowewillsavetherecordintoavariableoncreation.Afterdoingthis,
weareabletopulltheidusing $bearLawly>id .
Whydowedothis?Whydowepulltheidofanewlycreatedrecord?Thereareafew
reasonsforthis.One,sowecancreateourrelationshipscorrectly.Second,afterseeding
yourdatabasemultipletimes,theidofyourrecordswillalwaysbeincrementingsince
thatshowwesetupourdatabase.Asyoucanseeinthepicturebelow,theidofour
bearsare 10 , 11 ,and 12 .Dynamicallycreatingourrelationshipsinsteadofhardcodingin
theidletsusnotworryaboutmessingwithourseedfilesaftertheyhavebeencreated.
Withourseederfilereadytogo,letsgointothecommandlineandexecuteourseeds.
phpartisandb:seed

Wecanalsolookintoourdatabaseandseethenewrecords.

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

16/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

Justlikethat,wenowhaverecordsinourdatabase.Wecanfinallygettothefunpartand
showoffthetruepowerofEloquent!Finally!
Next,wewillgothroughallthetypesofqueriesyoucancreatewithEloquentandwewill
seehoweasyitistoquerydatabaseswithonetooneandmanytomanyrelationships.

UsingEloquentQueryingourDatabase
Withmigrationsandseedingfinallydone,wellgothroughsomebasicrealworld
scenarioswherewewouldneedtoaccesstheinformationwevejustputintoournew
database.
WithEloquent,itisthateasytocreaterecordsforourdatabase.Justcallyourmodeland
thefunctionyouneed.Itisalsoincrediblyeasytoread,update,ordeleterecordsoutof
ourdatabase.LetslookatCRUDfunctionalitywithEloquent.

CRUDWithEloquent
CreatingRecords

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

17/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

Youvealreadyseenhowtocreaterecordssinceweusedthe ::create methodinour


seeders.

//createabear
Bear::create(array(
'name'=>'SuperCool',
'type'=>'Black',
'danger_level'=>1
));
//alternativelyyoucancreateanobject,assignvalues,thensave
$bear=newBear;
$bear>name='SuperCool';
$bear>type='Black';
$bear>danger_level=1;
//savethebeartothedatabase
$bear>save();

Inadditiontothecreatemethod,youcanalsocreateanewobjectandassigndifferent
attributestoit.Oncethatisoveryoucancallthe save() function.
Anothermethodforcreationisusing firstOrCreate() or firstOrNew() .Thesewillletus
trytofindabearwithcertainattributes,ifthatbearisnotfound,thenwewilleithercreate
itintothedatabaseorinstantiateanewinstance.

//findthebearorcreateitintothedatabase
Bear::firstOrCreate(array('name'=>'Lawly'));
//findthebearorinstantiateanewinstanceintotheobjectwewant
$bear=Bear::firstOrNew(array('name'=>'Cerms'));
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

18/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

GettingandFindingRecords
Wecanbuildallofourqueriessimply.Selectstatements,getalls,andfindingrecordsare
alldoableandeasy.
Hereareafewexamplesofusecases.

//getallthebears
$bears=Bear::all();
//findaspecificbearbyid
$bear=Bear::find(1);
//findabearbyaspecificattribute
$bearLawly=Bear::where('name','=','Lawly')>first();
//findabearwithdangerlevelgreaterthan5
$dangerousBears=Bear::where('danger_level','>',5)>get();

FirstvsGetWhenqueryingthedatabaseandcreating where statements,youwillhaveto


use get() or first() .Firstwillreturnonlyonerecordandgetwillreturnanarrayof
recordsthatyouwillhavetoloopover.

UpdatingRecords
Toupdatearecord,justfindtherecordyoudliketoupdate,changetheattributes,and
save.Supersimple!
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

19/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

//let'schangethedangerlevelofLawlytolevel10
//findthebear
$lawly=Bear::where('name','=','Lawly')>first();
//changetheattribute
$lawly>danger_level=10;
//savetoourdatabase
$lawly>save();

DeletingRecords
Deletingrecordsmightbeeasierthanupdatingrecords.Therearetwomethods:pullthe
recordyouwantanddeleteitorjustusethe destroy method.

//findanddeletearecord
$bear=Bear::find(1);
$bear>delete();
//deletearecord
Bear::destroy(1);
//deletemultiplerecords
Bear::destroy(1,2,3);
//findanddeleteallbearswithadangerlevelover5
Bear::where('danger_level','>',5)>delete();

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

20/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

QueryingRelationships
NowthisiswhereEloquentgetsfun.Withmostapplications,youwillhaverelationships
amongstthepartsofyourdatabase.Wehavealreadydefinedthese:bearswillhaveone
fishandpicnicswillhavemanybears.

OnetoOneRelationship
LetsseehowwecanuseEloquenttoquerytheserelationshipsandgetourbears
somethingtoeat!Sincewedefinedtherelationshipsinourmodels,queryingwillbe
incrediblyeasy.

//findabearnamedAdobot
$adobot=Bear::where('name','=','Adobot')>first();
//getthefishthatAdobothas
$fish=$adobot>fish;
//gettheweightofthefishAdobotisgoingtoeat
$fish>weight;
//alternativelyyoucouldgostraighttotheweightattribute
$adobot>fish>weight;

OnetoManyRelationships
Forthisexample,letslookatallthetreesthatourLawlybearclimbs.

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

21/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

//findthetreeslawlyclimbs
$lawly=Bear::where('name','=','Lawly')>first();
foreach($lawly>treesas$tree)
echo$tree>type.''.$tree>age;

ManytoManyRelationship
Forthisexample,wewillgetthepicnicsthatourCermsbeargoesto.Wecanalsogetall
thebearsthatgototheYellowstonepicnic.

//getthepicnicsthatCermsgoesto
$cerms=Bear::where('name','=','Cerms')>first();
//getthepicnicsandtheirnamesandtastelevels
foreach($cerms>picnicsas$picnic)
echo$picnic>name.''.$picnic>taste_level;
//getthebearsthatgototheGrandCanyonpicnic
$grandCanyon=Picnic::where('name','=','GrandCanyon')>first();
//showthebears
foreach($grandCanyon>bearsas$bear)
echo$bear>name.''.$bear>type.''.$bear>danger_level;

Asyoucansee,bysettingupourEloquentModels,wecaneasilyqueryourdatabase.
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

22/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

Demonstration
Letsshowallthisoffinanactualviewfilesowecanseehowwepassthisdatatoour
Laravelview.Whatgoodisallthisworkifwedontshowourusersright?
Wewillneedtwothings:arouteandaviewfile.Letsrunthroughthesequicklytoshowoff
allthegreatEloquentthingswejustlearned.

OurRoute

//app/routes.php
...
//createourroute,returnaviewfile(app/views/eloquent.blade.php)
//wewillalsosendtherecordswewanttotheview
Route::get('eloquent',function(){
returnView::make('eloquent')
//allthebears(willalsoreturnthefish,trees,andpicnicsthatb
elongtothem)
>with('bears',Bear::all()>with('trees','picnics'));
});

OurViewFile
WewilluseLaravelBladeTemplatingtoloopthroughourdataandshowitoffinourview
now.Letscreateourviewfileat app/views/eloquent.blade.php .
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

23/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

<!app/views/eloquent.blade.php>
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="UTF8">
<title>EloquentBears</title>
<!CSS>
<!BOOTSTRAP>
<linkrel="stylesheet"href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/boo
tstrap.min.css">
<style>
body{paddingtop:50px;}/*addsomepaddingtothetopofoursite*/
</style>
</head>
<bodyclass="container">
<divclass="colsm8colsmoffset2">
<!BEARS>
<!loopoverthebearsandshowoffsomethings>
@foreach($bearsas$bear)
<!GETOURBASICBEARINFORMATION>
<h2>{{$bear>name}}<small>{{$bear>type}}:Level{{$bear>danger_lev
el}}</small></h2>
<!SHOWOFFTHETREES>
<h4>Trees</h4>
@foreach($bear>treesas$tree)
<p>{{$tree>type}}</p>
@endforeach
<!SHOWOFFTHEPICNICS>
<h4>Picnics</h4>
@foreach($bear>picnicsas$picnic)
<p>{{$picnic>name}}:TasteLevel{{$picnic>taste_level}}</p>
@endforeach
@endforeach
</div>
</body>
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

24/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

</html>

Nowwhenyougoviewyourappinyourbrowserat: http://example.com/eloquent ,you


willseeallthedatabeingpulledfromyourdatabase.

Conclusion
Wellthatwasalotofinformation!Thanksforreadingalongandhopefullyallthis
informationhasgivenyouagoodprimeronhowtouseEloquentforarealworld
application.Wevegonethrough:
Migrations
Eloquentmodels
Seeding
Definingrelationships
Queryingourdatabase
Queryingrelationships
Whilewehavecoveredagoodmanytopics,thereisstillsomuchmoreyoucandowhen
dealingwithdatabasesinyourapplication.Formoreinformation,Ialwaysencourage
readingthroughthealltheEloquentdocs.Youcandiveintothingslikepivottables,
polymorphicrelationships,advancedquerying,andsomuchmore.
Also,formorereadingonactualapplicationsthatusethedatabase,checkoutourtutorial
onLaravelCRUDwithResourceControllers.

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

25/26

14/2/2015

AGuidetoUsingEloquentORMinLaravelScotch

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22tile%22%20style%3D%22boxsizing%3A%20borderbox%3B%20borderradius%3A%200px%200px

26/26

You might also like