Eloquent ORM | Laravel | Basics
Eloquent ORM:
The object contains the following properties. Each of the property is mapped to the column of the database
If your model class is User, you should use User::all() to return all the tuples iof the databaseThe where clause:
Flight::where('active',1)->orderBy('name')->take(10)->get();
To get the first row of the row result set given by the where clause:-
$flight = Flight::where('number','1000')->first();
$flight->number = '1000';
$flight->refresh();
echo $flight->number;
foreach($flights as $flight) {
echo $flight->name;
}
Flight::chunk(200, function(Collection $flights) {
foreach($flights as $flight) {
}
});
To return rows from the rowset based on primary key, use:
Flight::findOrFail(1);
Here, primary key is 1.
If therte is no row with primary key1 , the script will stop executing
Using where clause:
Flight::where("legs",">",3)->firstOrFail();
To return the number of rows, use:
$flight = Flight::where("active:",1)->count();
$max = Flight::where('active',1)->max('price');
Insertion:
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
Inserting in another way:
use App\Models\Flight;
$flight = Flight::create([
"name" => "London to Paris",
]);
Updates:
use App\Models\Flight;
$flight = Flight::find(1);
$flight->name = "London to PAris";
$flight->save();
Bulk updates:
Flight::where("active",1)->where('destination','LA')->update(['delayed' => 1]);
To check if the row is modified from when its created, use
$user->isDirty();
$user->isDirty('first_name');
$user->isDirty('title');
$user->isDirty(['title','first_name']);
To check if the row is not changed since its creation, use
$user->isClean();
$user->isClean('title');
$user->isClean('first_name');
$user->isClean(['title','first_name']);
How to define relationships in Laravel:
1. one-one
Suppose a user has a email address. This is a HasOne relation and is written as$this->hasOne(Email::class);
The full path of the HasOne class is Illuminate\Database\Eloquent\Relations\HasOneDefining the iverse of the relationship.
$this->belongsTo(User::class);
2. one-to-many
Suppose a Post has many comments
$this->hasMany(Comment::class);
$comments = Post::find(1)->comments;
foreach($comments as $comment) {
}
Since all relationships also serve as query builders, you may add further constraints to the relatoinship query by calling the comments() method and continuing to chain the query
$comment = Post::find(1)->comments()->where('title','foo')->first();
The above query will find the first comment whose title is foo for teh Post whose id is 1
Inverse of the above relation
$this->belongsTo(Post::class);
Accessors and Mutators:
- An accessor transforms an Eloquent attribute value when it is accessed
-
public function getName() { return ucfirst($this->attribute['name']); }
- A mutator transforms an Eloquent attribute value when it is stored
-
public function setName($name) { $this->attribute['name'] = ucfirst($name); }
Many-Many Relationships
Many to-many relationships occur when multiple records in a table have an association with multiple records in another table
As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our User model has many Role models that it is related to. After accessing this relationship, we may access the intermediate table using the pivot attribute on the models:
use App\Models\User;
$user = User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
return $this->belongsToMany(Role::class, 'role_user');
Serialization (Conversion of user collection returned by Eloquent query chaining to Array)
$users = User::all();
return $users->toArray();
Deserialization to JSON
To convert a model to JSON, you should use the toJson method. Like toArray, the toJson method is recursive, so all attributes and relations will be converted to JSON. You may also specify any JSON encoding options that are supported by PHP.
use App\Models\User;
$user = User::find(1);
return $user->toJson();
return $user->toJson(JSON_PRETTY_PRINT);
Alternatively, you may cast a model or collection
Comments
Post a Comment