Laravel Classroom image

Yasar  Khan / Professional / Web Technology
 
To post your Question Join Classroom
 
Lesson Topics's No:-  |1 | 2 | 3 | 4 | 5 | 6|Last
Lessons:-Eloquent ORM

Eloquent ORM
An ORM is a really useful package, it stands for Object Relational Mapper. Sounds pretty
complicated right? Let’s break it down a little. (add bass beat) The mapper part, is because
we are mapping our PHP objects or classes to database tables and rows. The Relational part will
become clear in the relationships section.
There are many ORM solutions out there, but none as Eloquent as… well Eloquent. Eloquent
ships with Laravel, and can be used out of the box. For this portion I am going to assume that
you set up your database as described in the Migrations chapter, and that you are familiar with
the methods and chaining from the Fluent Query Builder chapter. We are going to build on
these.
You see Eloquent is an alternative to using Fluent, but it shares many of the same methods. The
only difference is that we are going to be interacting with Eloquent models as results, rather than
the stdObject we get back from Fluent. It’s going to make our code look even clearer. Let’s dive
right in and check out the Eloquent model.
11.1 Creating and using Eloquent Models
1 <?php
2
3 // application/models/user.php
4
5 class User extends Eloquent
6 {
7
8 }
Actually thats it.. no really, I am serious. You see, Eloquent trusts you. It knows that you have
already created a nice migration for the users table. It doesn’t need you to tell it about the fields
that exist. It’s going to trust that you know them. You should, you wrote the migration and
made the table. Oh by the way, you did put an increments('id') in your table right? This is a
common practice and Eloquent needs this to work.
Another thing you might have noticed about the model is that the class is called User and the
table is called users. This isn’t a typo. Eloquent is so clever that it can detect the plurals for the
English language. Our object is singular, so we define it as a User. However our database table
users will contain any number of users, so Laravel knows to look for a table with a plural of the
object name.
You may have picked up on the fact that it only detects plurals for the English language. What
if you use another language, or a certain plural doesn’t work for you? Simply add the word and
its plural version to the array in the application/config/strings.php file. Now it will work
as expected!
Maybe you don’t like having the table name as plural form? Not a problem, simply use the static
$table class attribute to specify another table name. For example..1 <?php
2
3 class User extends Eloquent
4 {
5 public static $table = 'app_users';
6 }
Right, typing that huge model definition must have worn you out (please note the sarcasm). Let’s
have a go at using our new model.
1 <?php
2
3 $user = User::find(1);
Wait hold on… we have seen this before. Do you remember find() from our Fluent chapter?
It brings back a single result by its primary key. You will find that Eloquent uses many of the
methods used by Fluent. This is really convenient because you can use a combination of both
database libraries without forgetting which method is for what. Sweet!
For eloquent simply use the object’s name, and supply a static method. We don’t need to use
DB::table() for this one.
You can use the result object in a similar way. The truth is you are now interacting with an
Eloquent object, but you couldn’t really tell the difference at this point. Let’s get that users
name.
1 <?php
2
3 echo $user->name;
Yep thats the same as last time. Nice and easy.
What if we would rather have our User object returned as an array? Simply call the to_array()
method on any Eloquent model to receive an array instead of an object.
1 <?php
2
3 $user = $user->to_array();
If you want to exclude certain fields from this array, you could add a $hidden static attribute to
your Eloquent model, containing an array of all the fields to exclude. For example :
1 <?php
2
3 class User extends Eloquent
4 {
5 public static $hidden = array('nickname');
6 }Say we want multiple results back? We can use the fancy all() method to bring back every
user, then we can have a sexy user party.
1 <?php
2
3 $users = User::all();
What we now have is an array of user objects. We can loop through them to access each one
individually. Simple as that.
1 <?php
2
3 foreach ($users as $user)
4 {
5 add_to_sexy_party($user);
6 }
Nice, its really swinging in here. Quite a few guys though.. Well let’s increase our chances and
get rid of the other guys. Then it really will be a sexy party!
1 <?php
2
3 $sexy_users = User::where('sex', '=', 'female')->get();
Whoop, lots better! The eye-candy threshold went up significantly. You see we just used a
where() chain method and get() just like we did with fluent. There is nothing new there, just
increased clarity.
I could cover all the query methods again for returning results, but I don’t really need to. Simply
flick back a chapter and mentally replace the word Fluent with Eloquent. You will get the idea.
Instead, let’s see what has changed. Creating and updating objects (rows) just got a whole lot
easier!
1 <?php
2
3 $user = new User();
4
5 $user->name = 'Captain Sexypants';
6 $user->mojo = '100%';
7
8 $user->save();
Best not to invite Captain Sexypants to our party, we won’t get any action with him around.
Even his parrot has swagger.You see we simply create a new User object, set class attributes for the fields that exist (we don’t
need to set the ID, Eloquent handles that) and save() the object to write our changes to the
database. This is commonly known as the Active Record design pattern. It’s a really nice way
of interacting with our rows by treating them the same as any other object in our application.
It’s like the database and all that nasty SQL doesn’t even exist!
If we already have a key-value array describing our friend ‘Captain Sexypants’ then we can
either pass it as a constructor parameter to the new object, or use the mass-assignment method
fill() to add him to the database. Check this out..
1 <?php
2
3 $user = new User(array(
4 'name' => 'Captain Sexypants',
5 'mojo' => '100%'
6 ));
7
8 $user->save();
or
1 <?php
2
3 $arr = array(
4 'name' => 'Captain Sexypants',
5 'mojo' => '100%'
6 );
7
8 $user = new User();
9 $user->fill($arr);
10 $user->save();
Please be careful not to let any extra information slip through when using mass-assignment as
it could result in a potential security risk.
So what about updating a row? It’s very similar, except we need to query for the user we want
to change first. Let’s see..
1 <?php
2
3 $user = User::where('name', '=', 'Captain Sexypants')->first();
Here we use first() because we want to make sure we only get one object back. We can’t
change the values on an array, we would have to loop through each one and that would make a
longer example than we need!1 <?php
2
3 $user->mojo = '5%';
4 $user->save();
Well I couldn’t take all his mojo, that wouldn’t be fair. At least he can come to the party now.
So you see, updating is performed exactly the same way as inserting except that we need to find
the object that we want to update first.
Do you remember using $table->timestamps() with in the migrations chapter to make
updated_at and created_at fields? Eloquent will update these automatically for you, inserting
a timestamp when an object is created and updating the updated_at field every time you save. If
you would like to disable this feature simply add the $timestamps class attribute to your model
and set it to false.
1 <?php
2
3 class User extends Eloquent
4 {
5 public static $timestamps = false;
6 }

 

 

 
 
 

Yasar  Khan

Skills    Laravel

Qualifications :-
Location :-Dehradun,Dehradun,Uttarakhand,India
Description:- Hi i am yasar working as web developer since last 3 years.
Explore
 

  Students (0)