Eloquent Flashcards
What does MVC stand for?
Model View Controller
What is the definition of ActiveRecord?
An architectural pattern found in software that stores in–memory object data in relational databases.
What does ORM stand for?
Object–relational Mapping
What is the definition of Object–Relational Mapping?
In computer science is a programming technique for converting data between incompatible type systems in object–oriented programming languages.
Which Laravel feature utilizes is ORM?
Eloquent
When does a Mass Assignment error occur?
A Mass Assignment vulnerability occurs unless you specify either a fillable or guarded attribute on the model.
What is the result of using Soft Delete on a model?
When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model and inserted into the database.
How would you Mass Update records?
Any number of models that match a given query can be updated:
App\Flight::where(‘active’, 1)–>where(‘destination’, ‘San Diego’)–>update([‘delayed’ => 1]);
What is the simplest way to create a record using eloquent?
To create a new record in the database, simply create a new model instance, set attributes on the model, then call the save method:
$flight = new Flight;
$flight–>name = $request–>name;
$flight–>save();
What are the Aggregates methods provided by query builder?
count(), max(), min(), avg() and sum()
What Eloquent methods will throw a Not Found Exception if the record is not found?
findOrFail() and firstOrFail()
What Eloquent methods will retrieve a single record?
find() and first()
What is the purpose of the Eloquent cursor() method?
The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage.
foreach (Flight::where('foo', 'bar')–>cursor() as $flight) { // }
What is the purpose of the Eloquent chunk() method?
The chunk method will retrieve a chunk of Eloquent models, feeding them to a given Closure for processing. Using the chunk method will conserve memory when working with large result sets.
Flight::chunk(200, function ($flights) { foreach ($flights as $flight) { // } });
What is the purpose of the Eloquent delete() method?
To delete a model, call the delete method on a model instance or if you know the primary key of the model, you may delete the model without retrieving it:
$flight = App\Flight::find(1);
$flight–>delete();
Or
App\Flight::destroy([1, 2, 3]);
How would you Mass Delete records?
Multiple models can be deleted if they match the given query:
App\Flight::where(‘active’, 0)–>delete();
What is the purpose of the save() method?
The save method may also be used to update models that already exist in the database:
$flight = App\Flight::find(1);
$flight–>name = ‘New Flight Name’;
$flight–>save();
Perhaps you need to insert a new Comment for a Post model. Instead of manually setting the post_id attribute on the Comment, you may insert the Comment directly from the relationship’s save method:
$comment = new App\Comment([
‘message’ => ‘A new comment.’
]);
$post = App\Post::find(1);
$post–>comments()–>save($comment);
What is the purpose of the Model variable $fillable?
$fillable serves as a white list of attributes that should be mass assignable on a model
What is the purpose of the Model variable $guarded?
The $guarded property should contain an array of attributes that you do not want to be mass assignable. All other attributes not in the array will be mass assignable. So, $guarded functions like a black list.
What are the other creation methods?
firstOrCreate() , firstOrNew() and updateOrCreate()
What is the purpose of the Eloquent firstOrCreate() method?
The firstOrCreate() method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the given attributes.
What is the purpose of the Eloquent firstOrNew() method?
The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it.
What is the purpose of the Eloquent updateOrCreate() method?
Update an existing model or create a new model if none exists.
Like the firstOrCreate method, updateOrCreate persists the model, so there’s no need to call save().
What is the purpose of the Eloquent withTrashed() method?
You may force soft deleted models to appear in a result set using the withTrashed method on the query:
$flights = App\Flight::withTrashed()–>where(‘account_id’, 1)–>get();
Or
$flight–>history()–>withTrashed()–>get();
What is the purpose of the Eloquent
onlyTrashed() method?
The onlyTrashed method will retrieve only soft deleted models:
$flights = App\Flight::onlyTrashed()–>where(‘airline_id’, 1)–>get();
What is the purpose of the Eloquent restore() method?
Sometimes you may wish to un–delete a soft deleted model. To restore a soft deleted model into an active state, use the restore method on a model instance:
$flight–>restore();
How would you Mass Restore soft deleted records?
You may also use the restore method in a query to quickly restore multiple models. Again, like other mass operations, this will not fire any model events for the models that are restored:
App\Flight::withTrashed()–>where(‘airline_id’, 1)–>restore();
What is the purpose of the Eloquent forceDelete() method?
Sometimes you may need to truly remove a model from your database. To permanently remove a soft deleted model from the database, use the forceDelete method:
$flight–>forceDelete();
Or
$flight–>history()–>forceDelete();
What are the Eloquent event methods apart of a models lifecycle?
creating(), created(), updating(), updated(), saving(), saved(), deleting(), deleted(), restoring() and restored()
Where would you register an Eloquent event listener?
A service provider:
public function boot() { User::creating(function ($user) { return $user–>isValid(); }); }
Where would you register an Observer class?
A service provider or the AppServiceProvider
What is the purpose of the Observer class?
If you are listening for many events on a given model, you may use observers to group all of your listeners into a single class.
What is the purpose of Global Scopes?
Global scopes allow you to add constraints to all queries for a given model.
What is the purpose of Anonymous Global Scopes?
Eloquent also allows you to define global scopes using Closures, which is particularly useful for simple scopes that do not warrant a separate class:
static::addGlobalScope(‘age’, function (Builder $builder) {
$builder–>where(‘age’, ‘>’, 200);
});
What is the purpose of the Eloquent withoutGlobalScope() method?
If you would like to remove a global scope for a given query, you may use the withoutGlobalScope method. The method accepts the class name of the global scope as its only argument:
User::withoutGlobalScope(AgeScope::class)–>get();
Using the withoutGlobalScopes() method how would remove several or all global scopes?
If you would like to remove several or even all of the global scopes, you may use the withoutGlobalScopes method:
User::withoutGlobalScopes()–>get();
Or
User::withoutGlobalScopes([
FirstScope::class,
SecondScope::class
])–>get();
What is the purpose of Local Scopes?
Local scopes allow you to define common sets of constraints that you may easily re–use throughout your application. For example, you may need to frequently retrieve all users that are considered popular. To define a scope, simply prefix an Eloquent model method with scope:
public function scopePopular($query){
return $query–>where(‘votes’, ‘>’, 100);
}
What is the purpose of Dynamic Scopes?
A local scope that accepts parameters:
public function scopeOfType($query, $type)
{
return $query–>where(‘type’, $type);
}
What are the different types of eloquent relationships?
One To One, One To Many, Many To Many, Has Many Through, Polymorphic Relations and Many To Many Polymorphic Relations
What is the definition of a One to One relationship?
A one–to–one relationship is a very basic relation. For example, a User model might be associated with one Phone.
What is the definition of a One to Many relationship?
A one–to–many relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments.
What is the definition of a Many to Many relationship?
Many–to–many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of Admin.
What is the definition of a Has Many Through relationship?
The has–many–through relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post models through an intermediate User model. In this example, you could easily gather all blog posts for a given country.
What are Polymorphic Relations?
Polymorphic relations allow a model to belong to more than one other model on a single association. For example, imagine users of your application can comment both posts and videos. Using polymorphic relationships, you can use a single comments table for both of these scenarios.
What are Many To Many Polymorphic Relations?
In addition to traditional polymorphic relations, you may also define many–to–many polymorphic relations. For example, a blog Post and Video model could share a polymorphic relation to a Tag model. Using a many–to–many polymorphic relation allows you to have a single list of unique tags that are shared across blog posts and videos.
What is the purpose of Eager Loading?
When accessing Eloquent relationships as properties, the relationship data is lazy loaded. This means the relationship data is not actually loaded until you first access the property. However, Eloquent can “eager load” relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem:
$books = App\Book::with(‘author’)–>get();
foreach ($books as $book) {
echo $book–>author–>name;
}
What is the purpose of Lazy Eager Loading?
Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models:
$books = App\Book::all();
if ($someCondition) {
$books–>load(‘author’, ‘publisher’);
}
What is the purpose of the Eloquent has() method?
When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, imagine you want to retrieve all blog posts that have at least one comment. To do so, you may pass the name of the relationship to the has method:
$posts = App\Post::has(‘comments’)–>get();
Besides the has() method, what other methods are available?
whereHas() and orWhereHas()
Besides the doesntHave() method, what other methods are available?
whereDoesntHave()
What is the purpose of the Eloquent withCount() method?
If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models:
$posts = App\Post::withCount(‘comments’)–>get();
foreach ($posts as $post) {
echo $post–>comments_count;
}
What is the purpose of the Eloquent doesntHave() method?
When accessing the records for a model, you may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that don’t have any comments. To do so, you may pass the name of the relationship to the doesntHave method:
App\Post::doesntHave(‘comments’)–>get();
What is the purpose of the Eloquent updateExistingPivot() method?
If you need to update an existing row in your pivot table, you may use updateExistingPivot method. This method accepts the pivot record foreign key and an array of attributes to update:
$user = App\User::find(1);
$user–>roles()–>updateExistingPivot($roleId, $attributes);
What is the purpose of the Eloquent toggle() method?
The many–to–many relationship also provides a toggle method which toggles the attachment status of the given IDs. If the given ID is currently attached, it will be detached. Likewise, if it is currently detached, it will be attached:
$user–>roles()–>toggle([1, 2, 3]);
What is the purpose of the Eloquent sync() method?
You may also use the sync method to construct many–to–many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:
$user–>roles()–>sync([1, 2, 3]);
You may also pass additional intermediate table values with the IDs:
$user–>roles()–>sync([1 => [‘expires’ => true], 2, 3]);
What is the purpose of the Eloquent syncWithoutDetaching() method?
If you do not want to detach existing IDs, you may use the syncWithoutDetaching method:
$user–>roles()–>syncWithoutDetaching([1, 2, 3]);
What is the purpose of the Eloquent attach() method?
Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let’s imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach method:
$user = App\User::find(1);
$user–>roles()–>attach($roleId);
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
$user–>roles()–>attach($roleId, [‘expires’ => $expires]);
What is the purpose of the Eloquent detach() method?
Of course, sometimes it may be necessary to remove a role from a user. To remove a many–to–many relationship record, use the detach method. The detach method will remove the appropriate record out of the intermediate table; however, both models will remain in the database:
// Detach a single role from the user... $user–>roles()–>detach($roleId);
// Detach all roles from the user... $user–>roles()–>detach();
How is it possible to use attach() or detach() for multiple IDs?
For convenience, attach and detach also accept arrays of IDs as input:
$user = App\User::find(1);
$user–>roles()–>detach([1, 2, 3]);
$user–>roles()–>attach([1 => [‘expires’ => $expires], 2, 3]);
What is the purpose of the Eloquent associate() method?
When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:
$account = App\Account::find(10);
$user–>account()–>associate($account);
$user–>save();
What is the purpose of the Eloquent dissociate() method?
When removing a belongsTo relationship, you may use the dissociate method. This method will set the relationship’s foreign key to null:
$user–>account()–>dissociate();
$user–>save();
What is the purpose of the Eloquent create() method?
In addition to the save and saveMany methods, you may also use the create method, which accepts an array of attributes, creates a model, and inserts it into the database.
$post = App\Post::find(1);
$comment = $post–>comments()–>create([
‘message’ => ‘A new comment.’,
]);
What is the difference between the Eloquent save() & create() methods?
The difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array.