Eloquent Flashcards

1
Q

What does MVC stand for?

A

Model View Controller

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the definition of ActiveRecord?

A

An architectural pattern found in software that stores in–memory object data in relational databases.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does ORM stand for?

A

Object–relational Mapping

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the definition of Object–Relational Mapping?

A

In computer science is a programming technique for converting data between incompatible type systems in object–oriented programming languages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which Laravel feature utilizes is ORM?

A

Eloquent

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

When does a Mass Assignment error occur?

A

A Mass Assignment vulnerability occurs unless you specify either a fillable or guarded attribute on the model.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the result of using Soft Delete on a model?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How would you Mass Update records?

A

Any number of models that match a given query can be updated:

App\Flight::where(‘active’, 1)–>where(‘destination’, ‘San Diego’)–>update([‘delayed’ => 1]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the simplest way to create a record using eloquent?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the Aggregates methods provided by query builder?

A

count(), max(), min(), avg() and sum()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What Eloquent methods will throw a Not Found Exception if the record is not found?

A

findOrFail() and firstOrFail()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What Eloquent methods will retrieve a single record?

A

find() and first()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the purpose of the Eloquent cursor() method?

A

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) {
     //
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the purpose of the Eloquent chunk() method?

A

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) {
        //
    }
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the purpose of the Eloquent delete() method?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How would you Mass Delete records?

A

Multiple models can be deleted if they match the given query:

App\Flight::where(‘active’, 0)–>delete();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the purpose of the save() method?

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the purpose of the Model variable $fillable?

A

$fillable serves as a white list of attributes that should be mass assignable on a model

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the purpose of the Model variable $guarded?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the other creation methods?

A

firstOrCreate() , firstOrNew() and updateOrCreate()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the purpose of the Eloquent firstOrCreate() method?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the purpose of the Eloquent firstOrNew() method?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the purpose of the Eloquent updateOrCreate() method?

A

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().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the purpose of the Eloquent withTrashed() method?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the purpose of the Eloquent

onlyTrashed() method?

A

The onlyTrashed method will retrieve only soft deleted models:

$flights = App\Flight::onlyTrashed()–>where(‘airline_id’, 1)–>get();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the purpose of the Eloquent restore() method?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How would you Mass Restore soft deleted records?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is the purpose of the Eloquent forceDelete() method?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What are the Eloquent event methods apart of a models lifecycle?

A

creating(), created(), updating(), updated(), saving(), saved(), deleting(), deleted(), restoring() and restored()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Where would you register an Eloquent event listener?

A

A service provider:

public function boot() {
    User::creating(function ($user) {
         return $user–>isValid();
     });
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Where would you register an Observer class?

A

A service provider or the AppServiceProvider

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the purpose of the Observer class?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the purpose of Global Scopes?

A

Global scopes allow you to add constraints to all queries for a given model.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is the purpose of Anonymous Global Scopes?

A

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);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the purpose of the Eloquent withoutGlobalScope() method?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Using the withoutGlobalScopes() method how would remove several or all global scopes?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is the purpose of Local Scopes?

A

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);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is the purpose of Dynamic Scopes?

A

A local scope that accepts parameters:

public function scopeOfType($query, $type)
{
return $query–>where(‘type’, $type);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What are the different types of eloquent relationships?

A
One To One, One To Many, 
Many To Many, 
Has Many Through, 
Polymorphic Relations and 
Many To Many Polymorphic Relations
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is the definition of a One to One relationship?

A

A one–to–one relationship is a very basic relation. For example, a User model might be associated with one Phone.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What is the definition of a One to Many relationship?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is the definition of a Many to Many relationship?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is the definition of a Has Many Through relationship?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What are Polymorphic Relations?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What are Many To Many Polymorphic Relations?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is the purpose of Eager Loading?

A

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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What is the purpose of Lazy Eager Loading?

A

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’);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is the purpose of the Eloquent has() method?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

Besides the has() method, what other methods are available?

A

whereHas() and orWhereHas()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Besides the doesntHave() method, what other methods are available?

A

whereDoesntHave()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is the purpose of the Eloquent withCount() method?

A

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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is the purpose of the Eloquent doesntHave() method?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is the purpose of the Eloquent updateExistingPivot() method?

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What is the purpose of the Eloquent toggle() method?

A

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]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

What is the purpose of the Eloquent sync() method?

A

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]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What is the purpose of the Eloquent syncWithoutDetaching() method?

A

If you do not want to detach existing IDs, you may use the syncWithoutDetaching method:

$user–>roles()–>syncWithoutDetaching([1, 2, 3]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

What is the purpose of the Eloquent attach() method?

A

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]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

What is the purpose of the Eloquent detach() method?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

How is it possible to use attach() or detach() for multiple IDs?

A

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]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

What is the purpose of the Eloquent associate() method?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What is the purpose of the Eloquent dissociate() method?

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

What is the purpose of the Eloquent create() method?

A

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.’,
]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

What is the difference between the Eloquent save() & create() methods?

A

The difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What is the purpose of the Eloquent saveMany() method?

A

If you need to save multiple related models, you may use the saveMany method:

$post = App\Post::find(1);

$post–>comments()–>saveMany([
new App\Comment([‘message’ => ‘A new comment.’]),
new App\Comment([‘message’ => ‘Another comment.’]),
]);

65
Q

What is the purpose of Nested Eager Loading?

A

To eager load nested relationships, you may use dot syntax. For example, let’s eager load all of the book’s authors and all of the author’s personal contacts in one Eloquent statement:

$books = App\Book::with(‘author.contacts’)–>get();

66
Q

What is the purpose of Eager Loading Multiple Relationships?

A

Sometimes you may need to eager load several different relationships in a single operation. To do so, just pass additional arguments to the with method:

$books = App\Book::with(‘author’, ‘publisher’)–>get();

67
Q

How would you update a parent’s timestamp when the child model is updated?

A

Add a touches property containing the names of the relationships to the child model:

protected $touches = [‘post’];

68
Q

What is the purpose of the Eloquent hasOne() method?

A
The hasOne method defines a one–to–one relationship on a model:
public function phone()
{
    return $this–>hasOne('App\Phone');
}
69
Q

What is the purpose of the Eloquent belongsTo() method?

A

The belongsTo method defines an inverse one–to–one or many relationship on a model:

public function user()
{
return $this–>belongsTo(‘App\User’);
}

70
Q

What is the purpose of the Eloquent hasMany() method?

A

The hasMany method defines a one–to–many relationship on a model:

public function comments()
{
return $this–>hasMany(‘App\Comment’);
}

71
Q

What is the purpose of the Eloquent belongsToMany() method?

A

The belongsToMany method defines a many–to–many relationship on a model, including inverse:

public function roles()
{
return $this–>belongsToMany(‘App\Role’);
}

72
Q

What is the purpose of the Eloquent hasManyThrough() method?

A

The hasManyThrough method defines a has–many–through relationship on a model:
public function posts()
{
return $this–>hasManyThrough(‘App\Post’, ‘App\User’);
}

73
Q

What is the purpose of the Eloquent morphTo() method?

A
The morphTo method defines a polymorphic, inverse one–to–one or many relationship on a model:
public function commentable()
{
     return $this–>morphTo();
}
74
Q

What is the purpose of the Eloquent morphMany() method?

A

The morphMany method defines a polymorphic one–to–many relationship on a model:
public function comments()
{
return $this–>morphMany(‘App\Comment’, ‘commentable’);
}

75
Q

What is the purpose of the Eloquent morphToMany() method?

A

The morphToMany method defines a polymorphic many–to–many relationship for a model:
public function tags()
{
return $this–>morphToMany(‘App\Tag’, ‘taggable’);
}

76
Q

What is the purpose of the Eloquent morphedByMany() method?

A

The morphedByMany method defines a polymorphic, inverse many–to–many relationship for a model:
public function posts()
{
return $this–>morphedByMany(‘App\Post’, ‘taggable’);
}

77
Q

What is the purpose of the Collection all() method?

A

The all method returns the underlying array represented by the collection:

collect([1, 2, 3])–>all();
// [1, 2, 3]
78
Q

What is the purpose of the Collection avg() method?

A

The avg method returns the average of all items in the collection:

collect([1, 2, 3, 4, 5])–>avg();
// 3

If the collection contains nested arrays or objects, you should pass a key to use for determining which values to calculate the average:

$collection = collect([
[‘name’ => ‘JavaScript: The Good Parts’, ‘pages’ => 176],
[‘name’ => ‘JavaScript: The Definitive Guide’, ‘pages’ => 1096],
]);

$collection–>avg('pages');
// 636
79
Q

What is the purpose of the Collection chunk() method?

A

The chunk method breaks the collection into multiple, smaller collections of a given size:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection–>chunk(4);

$chunks–>toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
80
Q

What is the purpose of the Collection collapse() method?

A

The collapse method collapses a collection of arrays into a single, flat collection:

$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

$collapsed = $collection–>collapse();

$collapsed–>all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
81
Q

What is the purpose of the Collection combine() method?

A

The combine method combines the keys of the collection with the values of another array or collection:

$collection = collect([‘name’, ‘age’]);

$combined = $collection–>combine([‘George’, 29]);

$combined–>all();
// ['name' => 'George', 'age' => 29]
82
Q

What is the purpose of the Collection contains() method?

A

The contains method determines whether the collection contains a given item:

$collection = collect([‘name’ => ‘Desk’, ‘price’ => 100]);

$collection–>contains('Desk');
// true
$collection–>contains('New York');
// false

You may also pass a key / value pair to the contains method, which will determine if the given pair exists in the collection:

$collection = collect([
[‘product’ => ‘Desk’, ‘price’ => 200],
[‘product’ => ‘Chair’, ‘price’ => 100],
]);

$collection–>contains('product', 'Bookcase');
// false

Finally, you may also pass a callback to the contains method to perform your own truth test:

$collection = collect([1, 2, 3, 4, 5]);

$collection–>contains(function ($value, $key) {
    return $value > 5;
});
// false
83
Q

What is the purpose of the Collection count() method?

A

The count method returns the total number of items in the collection:

$collection = collect([1, 2, 3, 4]);

$collection–>count();
// 4
84
Q

What is the purpose of the Collection diff() method?

A

The diff method compares the collection against another collection or a plain PHP array based on its values. This method will return the values in the original collection that are not present in the given collection:

$collection = collect([1, 2, 3, 4, 5]);

$diff = $collection–>diff([2, 4, 6, 8]);

$diff–>all();
// [1, 3, 5]
85
Q

What is the purpose of the Collection diffKeys() method?

A

The diffKeys method compares the collection against another collection or a plain PHP array based on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection:

$collection = collect([
    'one' => 10,
    'two' => 20,
    'three' => 30,
    'four' => 40,
    'five' => 50,
]);
$diff = $collection–>diffKeys([
    'two' => 2,
    'four' => 4,
    'six' => 6,
    'eight' => 8,
]);
$diff–>all();
// ['one' => 10, 'three' => 30, 'five' => 50]
86
Q

What is the purpose of the Collection each() method?

A

The each method iterates over the items in the collection and passes each item to a callback:

$collection = $collection–>each(function ($item, $key) {
    //
});

If you would like to stop iterating through the items, you may return false from your callback:

$collection = $collection–>each(function ($item, $key) {
    if (/* some condition */) {
        return false;
    }
});
87
Q

What is the purpose of the Collection every() method?

A

The every method creates a new collection consisting of every n–th element:

$collection = collect([‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]);

$collection–>every(4);
// ['a', 'e']

You may optionally pass an offset as the second argument:

$collection–>every(4, 1);
// ['b', 'f']
88
Q

What is the purpose of the Collection except() method?

A

The except method returns all items in the collection except for those with the specified keys:

$collection = collect([‘product_id’ => 1, ‘price’ => 100, ‘discount’ => false]);

$filtered = $collection–>except([‘price’, ‘discount’]);

$filtered–>all();
// ['product_id' => 1]

For the inverse of except, see the only method.

89
Q

What is the purpose of the Collection filter() method?

A

The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:

$collection = collect([1, 2, 3, 4]);

$filtered = $collection–>filter(function ($value, $key) {
return $value > 2;
});

$filtered–>all();
// [3, 4]

If no callback is supplied, all entries of the collection that are equivalent to false will be removed:

$collection = collect([1, 2, 3, null, false, ‘’, 0, []]);

$collection–>filter()–>all();
// [1, 2, 3]

For the inverse of filter, see the reject method.

90
Q

What is the purpose of the Collection first() method?

A

The first method returns the first element in the collection that passes a given truth test:

collect([1, 2, 3, 4])–>first(function ($value, $key) {
    return $value > 2;
});
// 3

You may also call the first method with no arguments to get the first element in the collection. If the collection is empty, null is returned:

collect([1, 2, 3, 4])–>first();
// 1
91
Q

What is the purpose of the Collection flatMap() method?

A

The flatMap method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by a level:

$collection = collect([
    ['name' => 'Sally'],
    ['school' => 'Arkansas'],
    ['age' => 28]
]);
$flattened = $collection–>flatMap(function ($values) {
    return array_map('strtoupper', $values);
});
$flattened–>all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];
92
Q

What is the purpose of the Collection flatten() method?

A

The flatten method flattens a multi–dimensional collection into a single dimension:

$collection = collect([‘name’ => ‘taylor’, ‘languages’ => [‘php’, ‘javascript’]]);

$flattened = $collection–>flatten();

$flattened–>all();
// ['taylor', 'php', 'javascript'];

You may optionally pass the function a “depth” argument:

$collection = collect([
    'Apple' => [
        ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    ],
    'Samsung' => [
        ['name' => 'Galaxy S7', 'brand' => 'Samsung']
    ],
]);

$products = $collection->flatten(1);

$products->values()->all();

/*
[
[‘name’ => ‘iPhone 6S’, ‘brand’ => ‘Apple’],
[‘name’ => ‘Galaxy S7’, ‘brand’ => ‘Samsung’],
]
*/

In this example, calling flatten without providing the depth would have also flattened the nested arrays, resulting in [‘iPhone 6S’, ‘Apple’, ‘Galaxy S7’, ‘Samsung’]. Providing a depth allows you to restrict the levels of nested arrays that will be flattened.

93
Q

What is the purpose of the Collection flip() method?

A

The flip method swaps the collection’s keys with their corresponding values:

$collection = collect([‘name’ => ‘taylor’, ‘framework’ => ‘laravel’]);

$flipped = $collection–>flip();

$flipped–>all();

// [‘taylor’ => ‘name’, ‘laravel’ => ‘framework’]

94
Q

What is the purpose of the Collection forget() method?

A

The forget method removes an item from the collection by its key:

$collection = collect([‘name’ => ‘taylor’, ‘framework’ => ‘laravel’]);

$collection–>forget(‘name’);

$collection–>all();

// [‘framework’ => ‘laravel’]

95
Q

What is the purpose of the Collection forPage() method?

A

The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection–>forPage(2, 3);

$chunk–>all();
// [4, 5, 6]
96
Q

What is the purpose of the Collection get() method?

A

The get method returns the item at a given key. If the key does not exist, null is returned:

$collection = collect([‘name’ => ‘taylor’, ‘framework’ => ‘laravel’]);

$value = $collection->get(‘name’);

// taylor
You may optionally pass a default value as the second argument:

$collection = collect([‘name’ => ‘taylor’, ‘framework’ => ‘laravel’]);

$value = $collection->get(‘foo’, ‘default-value’);

// default-value

You may even pass a callback as the default value. The result of the callback will be returned if the specified key does not exist:

$collection->get(‘email’, function () {
return ‘default-value’;
});

// default-value

97
Q

What is the purpose of the Collection groupBy() method?

A

The groupBy method groups the collection’s items by a given key:

$collection = collect([
[‘account_id’ => ‘account-x10’, ‘product’ => ‘Chair’],
[‘account_id’ => ‘account-x10’, ‘product’ => ‘Bookcase’],
[‘account_id’ => ‘account-x11’, ‘product’ => ‘Desk’],
]);

$grouped = $collection->groupBy(‘account_id’);

$grouped->toArray();

/*
[
‘account-x10’ => [
[‘account_id’ => ‘account-x10’, ‘product’ => ‘Chair’],
[‘account_id’ => ‘account-x10’, ‘product’ => ‘Bookcase’],
],
‘account-x11’ => [
[‘account_id’ => ‘account-x11’, ‘product’ => ‘Desk’],
],
]
*/

In addition to passing a string key, you may also pass a callback. The callback should return the value you wish to key the group by:

$grouped = $collection->groupBy(function ($item, $key) {
    return substr($item['account_id'], -3);
});

$grouped->toArray();

/*
[
‘x10’ => [
[‘account_id’ => ‘account-x10’, ‘product’ => ‘Chair’],
[‘account_id’ => ‘account-x10’, ‘product’ => ‘Bookcase’],
],
‘x11’ => [
[‘account_id’ => ‘account-x11’, ‘product’ => ‘Desk’],
],
]
*/

98
Q

What is the purpose of the Collection has() method?

A

The has method determines if a given key exists in the collection:

$collection = collect([‘account_id’ => 1, ‘product’ => ‘Desk’]);

$collection->has(‘product’);

// true

99
Q

What is the purpose of the Collection implode() method?

A

The implode method joins the items in a collection. Its arguments depend on the type of items in the collection. If the collection contains arrays or objects, you should pass the key of the attributes you wish to join, and the “glue” string you wish to place between the values:

$collection = collect([
[‘account_id’ => 1, ‘product’ => ‘Desk’],
[‘account_id’ => 2, ‘product’ => ‘Chair’],
]);

$collection->implode(‘product’, ‘, ‘);

// Desk, Chair
If the collection contains simple strings or numeric values, simply pass the "glue" as the only argument to the method:

collect([1, 2, 3, 4, 5])->implode(‘-‘);

// ‘1-2-3-4-5’

100
Q

What is the purpose of the Collection intersect() method?

A

The intersect method removes any values from the original collection that are not present in the given array or collection. The resulting collection will preserve the original collection’s keys:

$collection = collect([‘Desk’, ‘Sofa’, ‘Chair’]);

$intersect = $collection->intersect([‘Desk’, ‘Chair’, ‘Bookcase’]);

$intersect->all();

// [0 => ‘Desk’, 2 => ‘Chair’]

101
Q

What is the purpose of the Collection isEmpty() method?

A

The isEmpty method returns true if the collection is empty; otherwise, false is returned:

collect([])->isEmpty();

// true

102
Q

What is the purpose of the Collection keyBy() method?

A

The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:

$collection = collect([
[‘product_id’ => ‘prod-100’, ‘name’ => ‘desk’],
[‘product_id’ => ‘prod-200’, ‘name’ => ‘chair’],
]);

$keyed = $collection->keyBy(‘product_id’);

$keyed->all();

/*
[
‘prod-100’ => [‘product_id’ => ‘prod-100’, ‘name’ => ‘Desk’],
‘prod-200’ => [‘product_id’ => ‘prod-200’, ‘name’ => ‘Chair’],
]
*/

You may also pass a callback to the method. The callback should return the value to key the collection by:

$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
});

$keyed->all();

/*
[
‘PROD-100’ => [‘product_id’ => ‘prod-100’, ‘name’ => ‘Desk’],
‘PROD-200’ => [‘product_id’ => ‘prod-200’, ‘name’ => ‘Chair’],
]
*/

103
Q

What is the purpose of the Collection keys() method?

A

The keys method returns all of the collection’s keys:

$collection = collect([
‘prod-100’ => [‘product_id’ => ‘prod-100’, ‘name’ => ‘Desk’],
‘prod-200’ => [‘product_id’ => ‘prod-200’, ‘name’ => ‘Chair’],
]);

$keys = $collection->keys();

$keys->all();

// [‘prod-100’, ‘prod-200’]

104
Q

What is the purpose of the Collection last() method?

A

The last method returns the last element in the collection that passes a given truth test:

collect([1, 2, 3, 4])->last(function ($value, $key) {
return $value < 3;
});

// 2
You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:

collect([1, 2, 3, 4])->last();

// 4

105
Q

What is the purpose of the Collection map() method?

A

The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

$collection = collect([1, 2, 3, 4, 5]);

$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]

106
Q

What is the purpose of the Collection mapWithKeys() method?

A

The mapWithKeys method iterates through the collection and passes each value to the given callback. The callback should return an associative array containing a single key / value pair:

$collection = collect([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.com'
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.com'
    ]
]);

$keyed = $collection->mapWithKeys(function ($item) {
return [$item[‘email’] => $item[‘name’]];
});

$keyed->all();

/*
    [
        'john@example.com' => 'John',
        'jane@example.com' => 'Jane',
    ]
*/
107
Q

What is the purpose of the Collection max() method?

A

The max method returns the maximum value of a given key:

$max = collect([[‘foo’ => 10], [‘foo’ => 20]])->max(‘foo’);

// 20

$max = collect([1, 2, 3, 4, 5])->max();

// 5

108
Q

What is the purpose of the Collection merge() method?

A

The merge method merges the given array with the original collection. If a string key in the given array matches a string key in the original collection, the given array’s value will overwrite the value in the original collection:

$collection = collect([‘product_id’ => 1, ‘price’ => 100]);

$merged = $collection->merge([‘price’ => 200, ‘discount’ => false]);

$merged->all();

// [‘product_id’ => 1, ‘price’ => 200, ‘discount’ => false]

If the given array’s keys are numeric, the values will be appended to the end of the collection:

$collection = collect([‘Desk’, ‘Chair’]);

$merged = $collection->merge([‘Bookcase’, ‘Door’]);

$merged->all();

// [‘Desk’, ‘Chair’, ‘Bookcase’, ‘Door’]

109
Q

What is the purpose of the Collection min() method?

A

The min method returns the minimum value of a given key:

$min = collect([[‘foo’ => 10], [‘foo’ => 20]])->min(‘foo’);

// 10

$min = collect([1, 2, 3, 4, 5])->min();

// 1

110
Q

What is the purpose of the Collection nth() method?

A

The nth method creates a new collection consisting of every n-th element:

$collection = collect([‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]);

$collection->nth(4);

// ['a', 'e']
You may optionally pass an offset as the second argument:

$collection->nth(4, 1);

// [‘b’, ‘f’]

111
Q

What is the purpose of the Collection only() method?

A

The only method returns the items in the collection with the specified keys:

$collection = collect([‘product_id’ => 1, ‘name’ => ‘Desk’, ‘price’ => 100, ‘discount’ => false]);

$filtered = $collection->only([‘product_id’, ‘name’]);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']
For the inverse of only, see the except method.
112
Q

What is the purpose of the Collection partition() method?

A

The partition method may be combined with the list PHP function to separate elements that pass a given truth test from those that do not:

$collection = collect([1, 2, 3, 4, 5, 6]);

list($underThree, $aboveThree) = $collection->partition(function ($i) {
return $i < 3;
});

113
Q

What is the purpose of the Collection pipe() method?

A

The pipe method passes the collection to the given callback and returns the result:

$collection = collect([1, 2, 3]);

$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});

// 6

114
Q

What is the purpose of the Collection pluck() method?

A

The pluck method retrieves all of the values for a given key:

$collection = collect([
[‘product_id’ => ‘prod-100’, ‘name’ => ‘Desk’],
[‘product_id’ => ‘prod-200’, ‘name’ => ‘Chair’],
]);

$plucked = $collection->pluck(‘name’);

$plucked->all();

// [‘Desk’, ‘Chair’]

You may also specify how you wish the resulting collection to be keyed:

$plucked = $collection->pluck(‘name’, ‘product_id’);

$plucked->all();

// [‘prod-100’ => ‘Desk’, ‘prod-200’ => ‘Chair’]

115
Q

What is the purpose of the Collection pop() method?

A

The pop method removes and returns the last item from the collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->pop();

// 5

$collection->all();

// [1, 2, 3, 4]

116
Q

What is the purpose of the Collection prepend() method?

A

The prepend method adds an item to the beginning of the collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->prepend(0);

$collection->all();

// [0, 1, 2, 3, 4, 5]
You may also pass a second argument to set the key of the prepended item:

$collection = collect([‘one’ => 1, ‘two’, => 2]);

$collection->prepend(0, ‘zero’);

$collection->all();

// [‘zero’ => 0, ‘one’ => 1, ‘two’, => 2]

117
Q

What is the purpose of the Collection pull() method?

A

The pull method removes and returns an item from the collection by its key:

$collection = collect([‘product_id’ => ‘prod-100’, ‘name’ => ‘Desk’]);

$collection->pull(‘name’);

// ‘Desk’

$collection->all();

// [‘product_id’ => ‘prod-100’]

118
Q

What is the purpose of the Collection push() method?

A

The push method appends an item to the end of the collection:

$collection = collect([1, 2, 3, 4]);

$collection->push(5);

$collection->all();

// [1, 2, 3, 4, 5]

119
Q

What is the purpose of the Collection put() method?

A

The put method sets the given key and value in the collection:

$collection = collect([‘product_id’ => 1, ‘name’ => ‘Desk’]);

$collection->put(‘price’, 100);

$collection->all();

// [‘product_id’ => 1, ‘name’ => ‘Desk’, ‘price’ => 100]

120
Q

What is the purpose of the Collection random() method?

A

The random method returns a random item from the collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->random();

// 4 - (retrieved randomly)

You may optionally pass an integer to random to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive:

$random = $collection->random(3);

$random->all();

// [2, 4, 5] - (retrieved randomly)

121
Q

What is the purpose of the Collection reduce() method?

A

The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:

$collection = collect([1, 2, 3]);

$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});

// 6

The value for $carry on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:

$collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);

// 10

122
Q

What is the purpose of the Collection reject() method?

A

The reject method filters the collection using the given callback. The callback should return true if the item should be removed from the resulting collection:

$collection = collect([1, 2, 3, 4]);

$filtered = $collection->reject(function ($value, $key) {
return $value > 2;
});

$filtered->all();

// [1, 2]

For the inverse of the reject method, see the filter method.

123
Q

What is the purpose of the Collection reverse() method?

A

The reverse method reverses the order of the collection’s items:

$collection = collect([1, 2, 3, 4, 5]);

$reversed = $collection->reverse();

$reversed->all();

// [5, 4, 3, 2, 1]

124
Q

What is the purpose of the Collection search() method?

A

The search method searches the collection for the given value and returns its key if found. If the item is not found, false is returned.

$collection = collect([2, 4, 6, 8]);

$collection->search(4);

// 1

The search is done using a “loose” comparison, meaning a string with an integer value will be considered equal to an integer of the same value. To use strict comparison, pass true as the second argument to the method:

$collection->search(‘4’, true);

// false

Alternatively, you may pass in your own callback to search for the first item that passes your truth test:

$collection->search(function ($item, $key) {
return $item > 5;
});

// 2

125
Q

What is the purpose of the Collection shift() method?

A

The shift method removes and returns the first item from the collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]

126
Q

What is the purpose of the Collection shuffle() method?

A

The shuffle method randomly shuffles the items in the collection:

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] // (generated randomly)

127
Q

What is the purpose of the Collection slice() method?

A

The slice method returns a slice of the collection starting at the given index:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$slice = $collection->slice(4);

$slice->all();

// [5, 6, 7, 8, 9, 10]

If you would like to limit the size of the returned slice, pass the desired size as the second argument to the method:

$slice = $collection->slice(4, 2);

$slice->all();

// [5, 6]

The returned slice will preserve keys by default. If you do not wish to preserve the original keys, you can use the values method to reindex them.

128
Q

What is the purpose of the Collection sort() method?

A

The sort method sorts the collection. The sorted collection keeps the original array keys, so in this example we’ll use the values method to reset the keys to consecutively numbered indexes:

$collection = collect([5, 3, 1, 2, 4]);

$sorted = $collection->sort();

$sorted->values()->all();

// [1, 2, 3, 4, 5]

If your sorting needs are more advanced, you may pass a callback to sort with your own algorithm. Refer to the PHP documentation on usort, which is what the collection’s sort method calls under the hood.

129
Q

What is the purpose of the Collection sortBy() method?

A

The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in this example we’ll use the values method to reset the keys to consecutively numbered indexes:

$collection = collect([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);

$sorted = $collection->sortBy(‘price’);

$sorted->values()->all();

/*
[
[‘name’ => ‘Chair’, ‘price’ => 100],
[‘name’ => ‘Bookcase’, ‘price’ => 150],
[‘name’ => ‘Desk’, ‘price’ => 200],
]
*/

You can also pass your own callback to determine how to sort the collection values:

$collection = collect([
[‘name’ => ‘Desk’, ‘colors’ => [‘Black’, ‘Mahogany’]],
[‘name’ => ‘Chair’, ‘colors’ => [‘Black’]],
[‘name’ => ‘Bookcase’, ‘colors’ => [‘Red’, ‘Beige’, ‘Brown’]],
]);

$sorted = $collection->sortBy(function ($product, $key) {
    return count($product['colors']);
});

$sorted->values()->all();

/*
[
[‘name’ => ‘Chair’, ‘colors’ => [‘Black’]],
[‘name’ => ‘Desk’, ‘colors’ => [‘Black’, ‘Mahogany’]],
[‘name’ => ‘Bookcase’, ‘colors’ => [‘Red’, ‘Beige’, ‘Brown’]],
]
*/

130
Q

What is the purpose of the Collection sortByDesc() method?

A

This method has the same signature as the sortBy method, but will sort the collection in the opposite order.

131
Q

What is the purpose of the Collection splice() method?

A

The splice method removes and returns a slice of items starting at the specified index:

$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2);

$chunk->all();

// [3, 4, 5]

$collection->all();

// [1, 2]

You may pass a second argument to limit the size of the resulting chunk:

$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2, 1);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 4, 5]

In addition, you can pass a third argument containing the new items to replace the items removed from the collection:

$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2, 1, [10, 11]);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 10, 11, 4, 5]

132
Q

What is the purpose of the Collection split() method?

A

The split method breaks a collection into the given number of groups:

$collection = collect([1, 2, 3, 4, 5]);

$groups = $collection->split(3);

$groups->toArray();

// [[1, 2], [3, 4], [5]]

133
Q

What is the purpose of the Collection sum() method?

A

The sum method returns the sum of all items in the collection:

collect([1, 2, 3, 4, 5])->sum();

// 15

If the collection contains nested arrays or objects, you should pass a key to use for determining which values to sum:

$collection = collect([
[‘name’ => ‘JavaScript: The Good Parts’, ‘pages’ => 176],
[‘name’ => ‘JavaScript: The Definitive Guide’, ‘pages’ => 1096],
]);

$collection->sum(‘pages’);

// 1272

In addition, you may pass your own callback to determine which values of the collection to sum:

$collection = collect([
[‘name’ => ‘Chair’, ‘colors’ => [‘Black’]],
[‘name’ => ‘Desk’, ‘colors’ => [‘Black’, ‘Mahogany’]],
[‘name’ => ‘Bookcase’, ‘colors’ => [‘Red’, ‘Beige’, ‘Brown’]],
]);

$collection->sum(function ($product) {
    return count($product['colors']);
});

// 6

134
Q

What is the purpose of the Collection take() method?

A

The take method returns a new collection with the specified number of items:

$collection = collect([0, 1, 2, 3, 4, 5]);

$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]

You may also pass a negative integer to take the specified amount of items from the end of the collection:

$collection = collect([0, 1, 2, 3, 4, 5]);

$chunk = $collection->take(-2);

$chunk->all();

// [4, 5]

135
Q

What is the purpose of the Collection toArray() method?

A

The toArray method converts the collection into a plain PHP array. If the collection’s values are Eloquent models, the models will also be converted to arrays:

$collection = collect([‘name’ => ‘Desk’, ‘price’ => 200]);

$collection->toArray();

/*
    [
        ['name' => 'Desk', 'price' => 200],
    ]
*/
136
Q

What is the purpose of the Collection toJson() method?

A

The toJson method converts the collection into JSON:

$collection = collect([‘name’ => ‘Desk’, ‘price’ => 200]);

$collection->toJson();

// ‘{“name”:”Desk”, “price”:200}’

137
Q

What is the purpose of the Collection transform() method?

A

The transform method iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback:

$collection = collect([1, 2, 3, 4, 5]);

$collection->transform(function ($item, $key) {
return $item * 2;
});

$collection->all();

// [2, 4, 6, 8, 10]

138
Q

What is the purpose of the Collection union() method?

A

The union method adds the given array to the collection. If the given array contains keys that are already in the original collection, the original collection’s values will be preferred:

$collection = collect([1 => [‘a’], 2 => [‘b’]]);

$union = $collection->union([3 => [‘c’], 1 => [‘b’]]);

$union->all();

// [1 => [‘a’], 2 => [‘b’], [3 => [‘c’]]

139
Q

What is the purpose of the Collection unique() method?

A

The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in this example we’ll use the values method to reset the keys to consecutively numbered indexes:

$collection = collect([1, 1, 2, 2, 3, 4, 2]);

$unique = $collection->unique();

$unique->values()->all();

// [1, 2, 3, 4]

When dealing with nested arrays or objects, you may specify the key used to determine uniqueness:

$collection = collect([
[‘name’ => ‘iPhone 6’, ‘brand’ => ‘Apple’, ‘type’ => ‘phone’],
[‘name’ => ‘iPhone 5’, ‘brand’ => ‘Apple’, ‘type’ => ‘phone’],
[‘name’ => ‘Apple Watch’, ‘brand’ => ‘Apple’, ‘type’ => ‘watch’],
[‘name’ => ‘Galaxy S6’, ‘brand’ => ‘Samsung’, ‘type’ => ‘phone’],
[‘name’ => ‘Galaxy Gear’, ‘brand’ => ‘Samsung’, ‘type’ => ‘watch’],
]);

$unique = $collection->unique(‘brand’);

$unique->values()->all();

/*
[
[‘name’ => ‘iPhone 6’, ‘brand’ => ‘Apple’, ‘type’ => ‘phone’],
[‘name’ => ‘Galaxy S6’, ‘brand’ => ‘Samsung’, ‘type’ => ‘phone’],
]
*/

You may also pass your own callback to determine item uniqueness:

$unique = $collection->unique(function ($item) {
return $item[‘brand’].$item[‘type’];
});

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
        ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
*/
140
Q

What is the purpose of the Collection values() method?

A

The values method returns a new collection with the keys reset to consecutive integers:

$collection = collect([
10 => [‘product’ => ‘Desk’, ‘price’ => 200],
11 => [‘product’ => ‘Desk’, ‘price’ => 200]
]);

$values = $collection->values();

$values->all();

/*
[
0 => [‘product’ => ‘Desk’, ‘price’ => 200],
1 => [‘product’ => ‘Desk’, ‘price’ => 200],
]
*/

141
Q

What is the purpose of the Collection where() method?

A

The where method filters the collection by a given key / value pair:

$collection = collect([
[‘product’ => ‘Desk’, ‘price’ => 200],
[‘product’ => ‘Chair’, ‘price’ => 100],
[‘product’ => ‘Bookcase’, ‘price’ => 150],
[‘product’ => ‘Door’, ‘price’ => 100],
]);

$filtered = $collection->where(‘price’, 100);

$filtered->all();

/*
[
[‘product’ => ‘Chair’, ‘price’ => 100],
[‘product’ => ‘Door’, ‘price’ => 100],
]
*/

The where method uses loose comparisons when checking item values. Use the whereStrict method to filter using “strict” comparisons.

142
Q

What is the purpose of the Collection whereStrict() method?

A

This method has the same signature as the where method; however, all values are compared using “strict” comparisons.

143
Q

What is the purpose of the Collection whereIn() method?

A

The whereIn method filters the collection by a given key / value contained within the given array.

$collection = collect([
[‘product’ => ‘Desk’, ‘price’ => 200],
[‘product’ => ‘Chair’, ‘price’ => 100],
[‘product’ => ‘Bookcase’, ‘price’ => 150],
[‘product’ => ‘Door’, ‘price’ => 100],
]);

$filtered = $collection->whereIn(‘price’, [150, 200]);

$filtered->all();

/*
[
[‘product’ => ‘Bookcase’, ‘price’ => 150],
[‘product’ => ‘Desk’, ‘price’ => 200],
]
*/

The whereIn method uses “loose” comparisons when checking item values. Use the whereInStrict method to filter using strict comparisons.

144
Q

What is the purpose of the Collection whereInStrict() method?

A

This method has the same signature as the whereIn method; however, all values are compared using strict comparisons.

145
Q

What is the purpose of the Collection zip() method?

A

The zip method merges together the values of the given array with the values of the original collection at the corresponding index:

$collection = collect([‘Chair’, ‘Desk’]);

$zipped = $collection->zip([100, 200]);

$zipped->all();

// [[‘Chair’, 100], [‘Desk’, 200]]

146
Q

What are higher order messages?

A

Collections also provide support for “higher order messages”, which are short-cuts for performing common actions on collections. The collection methods that provide higher order messages are: contains, each, every, filter, first, map, partition, reject, sortBy, sortByDesc, and sum.

Each higher order message can be accessed as a dynamic property on a collection instance. For instance, let’s use the each higher order message to call a method on each object within a collection:

$users = User::where(‘votes’, ‘>’, 500)->get();

$users->each->markAsVip();

Likewise, we can use the sum higher order message to gather the total number of “votes” for a collection of users:

$users = User::where(‘group’, ‘Development’)->get();

return $users->sum->votes;

147
Q

What methods allow you to format Eloquent attribute values when you retrieve or set them on model instances?

A

Accessors and Mutators

148
Q

How do you define a Accessor?

A

To define an accessor, create a getFooAttribute method on your model where Foo is the “studly” cased name of the column you wish to access. In this example, we’ll define an accessor for the first_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name attribute:

149
Q

How do you define a Mutator?

A

To define a mutator, define a setFooAttribute method on your model where Foo is the “studly” cased name of the column you wish to access. So, again, let’s define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:

attributes[‘first_name’] = strtolower($value);
}
}
The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model’s internal $attributes property. So, for example, if we attempt to set the first_name attribute to Sally:

$user = App\User::find(1);

$user->first_name = ‘Sally’;
In this example, the setFirstNameAttribute function will be called with the value Sally. The mutator will then apply the strtolower function to the name and set its resulting value in the internal $attributes array.

150
Q

Which class extends the PHP DateTime class to provide an assortment of helpful methods?

A

Carbon

151
Q

What is the purpose of the $casts model attribute?

A

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to:

protected $casts = [
‘is_admin’ => ‘boolean’,
];

152
Q

What cast types are supported by $cast attribute?

A

The supported cast types are: integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.

153
Q

What is the purpose of the $hidden model attribute?

A

Sometimes you may wish to limit the attributes, such as passwords, that are included in your model’s array or JSON representation. To do so, add a $hidden property to your model:

protected $hidden = [‘password’];

154
Q

What is the purpose of the $visible model attribute?

A

Alternatively, you may use the visible property to define a white–list of attributes that should be included in your model’s array and JSON representation. All other attributes will be hidden when the model is converted to an array or JSON:

protected $visible = [‘first_name’, ‘last_name’];

155
Q

What Eloquent methods allow you to temporarily modify attribute visibility?

A

makeVisible() and makeHidden()

156
Q

What is the purpose of the Eloquent makeVisible() method?

A

If you would like to make some typically hidden attributes visible on a given model instance, you may use the makeVisible method. The makeVisible method returns the model instance for convenient method chaining:

return $user–>makeVisible(‘attribute’)–>toArray();

157
Q

What is the purpose of the Eloquent makeHidden() method?

A

Likewise, if you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method:

return $user–>makeHidden(‘attribute’)–>toArray();

158
Q

What is the purpose of the $append model attribute?

A

After creating an accessor and the attribute has been added to the appends list, it will be included in both the model’s array and JSON representations. Attributes in the appends array will also respect the visible and hidden settings configured on the model:

protected $appends = [‘is_admin’];