1
Q

Generate a resource class using Artisan!

A

php artisan make:resource ExampleResource

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

What is a resource class?

A

A resource class represents a single model that needs to be transformed into a JSON structure.

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

Which method does every resource class need to specify and what is it used for?

A

The toArray() method returns the array of attributes that should be converted to JSON when the resource is returned as a response from a route or controller method

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

Which method should you use when creating the resource instance in your route or controller if you are returning a collection of resources or a paginated response?

A

ExampleResource::collection(Example::all());

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

When returning a resource collection from a route, Laravel resets the collection’s keys so that they are in numerical order. What do you need to add to the resource class to stop Laravel from doing that and keep the original keys?

A

public $preserveKeys = true;

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

By default Laravel will wrap everything under a “data” key when generating a JSON response. How can you stop Laravel from doing so?

A

(in the boot() method of the AppServiceProvider)
JsonResource::withoutWrapping();

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

When returning paginated collections via a resource response, Laravel will wrap your resource data in a data key even if the withoutWrapping method has been called. Why does that happen?

A

Because paginated responses always contain meta and links keys with information about the paginator’s state. To show an example of why that makes the data key necessary:

{
    "data": [
        {
            "id": 1,
            "name": "Eladio Schroeder Sr.",
            "email": "therese28@example.com"
        },
        {
            "id": 2,
            "name": "Liliana Mayert",
            "email": "evandervort@example.com"
        }
    ],
    "links":{
        "first": "http://example.com/users?page=1",
        "last": "http://example.com/users?page=1",
        "prev": null,
        "next": null
    },
    "meta":{
        "current_page": 1,
        "from": 1,
        "last_page": 1,
        "path": "http://example.com/users",
        "per_page": 15,
        "to": 10,
        "total": 10
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Make this toArray() method only return ‘secret’, if the user() has isAdmin() = true!

public function toArray(Request $request): array
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'secret' => $this->secret-value,
    ];
}
A
public function toArray(Request $request): array
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'secret' => $this->when($request->user()->isAdmin(), 'secret-value'),
    ];
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Which method should you use instead of when() if multiple attributes should be included in the resource response based on the same condition?

A
mergeWhen(INSERT CONDITION, [
    'first-secret' => 'value',
    'second-secret' => 'value',
])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can you make sure that something is only included under the condition that it is loaded at the point of the resource trying to get it?

A

'example' => ExampleResource::collection($this->whenLoaded('example'))

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

Given a model called “Flight”, what will the corresponding database be named according to Laravel conventions?

A

flights

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

Which property do you need to add to a model to rename the database to something that does not follow the Laravel naming conventions?

A

protected $table = 'example';

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

Eloquent will automatically cast the primary key to an integer and increment it. How can you stop Eloquent from incrementing it and how could you change it to a string?

A
public $incrementing = false;

protected $keyType = 'string';
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are UUIDs?

A

universally unique alpha-numeric identifiers

They are a 36 character long identifier that can be used instead of a primary key.

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

How can you use UUIDs instead of the normal auto-incrementing primary keys?

A
use Illuminate\Database\Eloquent\Concerns\HasUuids;

// ...

class Example extends Model
{
    use HasUuids;

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

How can you use ULIDs instead of the normal auto-incrementing primary keys?

A
use Illuminate\Database\Eloquent\Concerns\HasUlids;

// ...

class Example extends Model
{
    use HasUlids;

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

By default, Eloquent will automatically manage “created_at” and “updated_at” columns for your model’s corresponding database table. How can you stop Eloquent from doing so?

A

public $timestamps = false;

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

Customize the names of your “created_at” and “updated_at” columns!

A
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'updated_date';

you can also enter other things for the names, these are just examples

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

Which property do you need to change the default value of for your model to not use the same database connection that is configured as the default for your application?

A

protected $connection = 'mysql';

mysql is just an example here

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

In the AppServiceProvider class, disable lazy loading if the application is running in a non-production environment!

A

(in boot() method)
Model::preventLazyLoading(! $this->app->isProduction());

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

What does the refresh() method do?

A

The refresh() method will re-hydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well. Example:

$flight = Flight::where('number', 'FR 900')->first();
 
$flight->number = 'FR 456';
 
$flight->refresh();
 
$flight->number; // "FR 900"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What happens if a ModelNotFoundException is not caught?

A

A 404 HTTP response is automatically sent back to the client

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

What is the firstOrCreate method used for?

A

It attempts to locate a database record using a given column / value pair and if the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument.

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

What is the difference between the firstOrNew and the firstOrCreate method?

A

firstOrNew will attempt to locate a record in the database matching the given attributes like firstOrCreate. 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 and will need to be manually persisted using the “save” method

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

Which method can you use to update models that already exist in the database?

A

You can use the “save” method to update models, the updated_at timestamp will automatically be updated when using save()

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

How can you update a model if it already exists, but if it doesn’t then make and persist the model instead?

A

updateOrCreate()

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

Given the model Flight, mark all flights with the “destination” “Hamburg”, that are “active” = 1, as “delayed” = 1!

A
Flight::where('active', 1)
            ->where('destination', 'Hamburg')
            ->update(['delayed' => 1]);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What do the methods “isDirty, isClean and wasChanged” do?

A

The isDirty method determines if any of the model’s attributes have been changed since the model was retrieved.
isClean will determine if an attribute has remained unchanged since the model was retrieved.
wasChanged determines if any attributes were changed when the model was last saved within the current request cycle.

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

How can you get the original data of a model after it was changed?

A

$model->getOriginal('attributename');

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

Why could using the create method fail for a model?

A

Either a $fillable or $guarded property needs to be specified, otherwise the mass assignment protection, that exists for all Eloquent models, would stop the create method from running

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

What is a mass assignment vulnerability?

A

It occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed to your model’s create method, allowing the user to escalate themselves to an administrator.

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

Make the “example” attribute mass assignable within a given model’s class!

A

protected $fillable = ['example'];

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

How can you make all attributes of a model mass assignable inside of the model’s class?

A

protected $guarded = [];

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

What happens to attributes, that are attempted to be mass assigned but are not in the $fillable array?

A

They are silently discarded

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

Which trait do you need to add to a model to enable soft deleting for said model?

A
use Illuminate\Database\Eloquent\Softdeletes;

class Example extends Model
{
    use SoftDeletes;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How can you “un-delete” a soft deleted model?

A

$model->restore();

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

Restore all soft deleted Flight models, that have the “airline_id” 1!

A
Flight::withTrashed()
            ->where('airline_id', 1)
            ->restore();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Given a model with soft deleting enabled, how can you truly delete something?

A

->forceDelete();

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

Retrieve only soft deleted models, not including the non-deleted ones!

A

Example::onlyTrashed()->get();

you could also add stuff like “where” into the query

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

Which trait should you use to periodically delete items in a model?

A
use Illuminate\Database\Eloquent\Prunable;

class Example extends Model
{
    use Prunable;

    // ...

    public function prunable(): Builder
    {
        return static::where('created_at', '<=', now()->INSERT            HOW LONG THINGS SHOULD STAY BEFORE PERIODICALLY       BEING DELETED HERE);
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

If you want something to be executed before the prunable method permanently removes a model from the database, in which method of the model should you implement that code?

A
protected function pruning():void
{
    // ...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Adding the prunable trait won’t actually make models get deleted periodically yet, what do you also need to implement where and how can you choose the increments that models should get pruned in?

A

(in the routes/console.php file)

use Illuminate\Support\Facades\Schedule
Schedule::command('model:prune')->daily();

in this particular example, models will be pruned every day, but you can also use something like “->weekly();” or whichever other time frame you wish to use.

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

What do you need to do to only prune certain models?

A
Schedule::command('model:prune' [
    '--model' => [Example::class, SecondExample::class],
])->daily();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Sometimes you may want to have some models be pruned with a different regularity than others or only want to prune them manually. How can you stop the Schedule::command from pruning specific models?

A
Schedule::command('model:prune', [
    '--except' => [Example::class, ExampleTwo::class],
])->daily();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

How can you test your prunable query without actually having it run?

A

php artisan model:prune –pretend

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

What happens to soft deleted models if a prunable query is ran on their model?

A

They get permanently deleted

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

Pruning retrieves the models before deletion, but that can be very inefficient with larger applications. How can you prune models more efficiently?

A

instead of using the standard prunable trait, you can use the “MassPrunable” trait, which does not retrieve all models before deletion, hence being more efficient.

use Illuminate\Database\Eloquent\MassPrunable;

class Example extends Model
{
    use MassPrunable;

    // ...

    public function prunable(): Builder
    {
        return static::where(’created_at’, '<=', now()->INSERT TIMEFRAME);
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

How can you create an unsaved copy of an existing model instance and why can that be useful?

A

->replicate([INSERT ATTRIBUTES TO BE EXCLUDED])->fill([INSERT ATTRIBUTES TO BE UPDATED FOR THE UNSAVED COPY)];

Given model instances that share many of the same attributes, it can make sense to just replicate one of the models, exclude the not needed attributes and overwrite / add the differing attributes, instead of just creating two wholly separate models from scratch, that have a lot of the same things. Because the replicated model is not saved by default, you may save if using the ->save() method.

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

What do global scopes allow you to do and how can that be useful?

A

They allow you to add constraints to all queries for a given model.
Writing your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constrains.

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

Create a global scope using Artisan!

A

php artisan make:scope ExampleScope

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

What is the one method that needs to be implemented when creating a global scope?

A
public function apply(Builder $builder, Model $model): void
{
    $builder->where(created_at', '<', now()->subYears(2000));
}

In this example the global scope is limited to everything before the year 2000, which could be used to find old models in your project, but you can obviously also include any other type of where clause to limit the scope.

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

How can you assign a global scope to a model?

A
use Illuminate\Database\Eloquent\Attributes\ScopedBy;

#[ScopedBy([ExampleScope::class])]
class Example extends Model
{
    // ...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

Given a model that uses a global scope, you may not always want to include said scope for every single query. How can you create a query, that goes beyond the scope?

A

Example::withoutGlobalScope(ExampleScope::class)->get();

in this case, the Example model usually has the global scope ExampleScope, but for this particular query the scope is ignored.

you can also include an array of global scopes to be ignored for the query if multiple scopes are applied to a model and you would like to bypass multiple or all of them.

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

Create a local scope “popular” where the $query’s “votes” attribute is larger than 100!

A

(within most relevant model)

public function scopePopular(Builder $query): void
{
    $query->where('votes', '>', 100);
}

if you now want to utilize this scope, you can simply just use “->popular()” as an argument now and it will do whatever you limited the scope to, which makes it extremely useful to quickly and easily add scopes to queries.
It is very important, that you start the local scope’s method name with “scope” and whatever you add afterwards will be how the scope will be called upon, so a “scopeActive” local scope could be added to a query by utilizing “->active()”. You can also chain multiple local scopes in one query.

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

How can you include local scopes into a query in a way where either one or the other scope gets applied?

A

(using example local scopes called “popular()” and “active()” for “User” model)

$users = User::popular()->orWhere->active()->get();

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

What can you do to check if 2 models are the same (the same meaning that they have the same primary key, table and database connection)?

A

is() / isNot()

for example:

if ($post->is($anotherPost)) {
    // ...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

What is the append() method used for?

A

The append method may be used to indicate that an attribute should be appended for every model in the collection. This method accepts an array of attributes or a single attribute:

$users->append('team');
 
$users->append(['team', 'is_admin']);
58
Q

What is the contains method used for?

A

The contains method may be used to determine if a given model instance is contained by the collection. This method accepts a primary key or a model instance:

$users->contains(1);
 
$users->contains(User::find(1));
59
Q

What is the diff() method used for?

A

The diff method returns all of the models that are not present in the given collection:

use App\Models\User;
 
$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());
60
Q

What does the except method do?

A

The except method returns all of the models that do not have the given primary keys:

$users = $users->except([1, 2, 3]);

61
Q

What does the find method do?

A

The find method returns the model that has a primary key matching the given key. If $key is a model instance, find will attempt to return a model matching the primary key. If $key is an array of keys, find will return all models which have a primary key in the given array:

$users = User::all();
 
$user = $users->find(1);
62
Q

What does the fresh method do?

A

The fresh method retrieves a fresh instance of each model in the collection from the database. In addition, any specified relationships will be eager loaded:

$users = $users->fresh();
 
$users = $users->fresh('comments');
63
Q

What does the load method do?

A

The load method eager loads the given relationships for all models in the collection:

$users->load(['comments', 'posts']);
 
$users->load('comments.author');
 
$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);
64
Q

What is the loadMissing method used for?

A

The loadMissing method eager loads the given relationships for all models in the collection if the relationships are not already loaded:

$users->loadMissing(['comments', 'posts']);
 
$users->loadMissing('comments.author');
 
$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active');
65
Q

What is the only() method used for?

A

The only method returns all of the models that have the given primary keys:

$users = $users->only([1, 2, 3]);

66
Q

What does the unique method do?

A

The unique method returns all of the unique models in the collection. Any models with the same primary key as another model in the collection are removed:

$users = $users->unique();

67
Q

What does an accessor do?

A

An accessor transforms an Eloquent attribute value when it is accessed.

68
Q

How can you make your accessor transform multiple model attributes into a single “value object”?

A

To do so, your get closure may accept a second argument of $attributes, which will be automatically supplied to the closure and will contain an array of all of the model’s current attributes:

use App\Support\Address;
use Illuminate\Database\Eloquent\Casts\Attribute;
 
/**
 * Interact with the user's address.
 */
protected function address(): Attribute
{
    return Attribute::make(
        get: fn (mixed $value, array $attributes) => new Address(
            $attributes['address_line_one'],
            $attributes['address_line_two'],
        ),
    );
}
69
Q

Some value objects can be very computationally intensive to retrieve, how can you force an accessor to cache the values?

A

->shouldCache();

70
Q

How can you disable the object caching behavior of attributes?

A

->withoutObjectCaching();

71
Q

What does a mutator do?

A

A mutator transforms an Eloquent attribute value when it is set.

72
Q

Given the attribute “firstName()”, make the accessor capitalize the first letter of the retrieved string and make the mutator convert the string to lower case.

A
protected function firstName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower($value),
        );
    }
73
Q

How can you make your accessor and / or mutator convert multiple values within the same “return Attribute::make”?

A

By giving them an array of things to convert instead of just giving one query.

74
Q

What is the advantage of using attribute casting instead of accessors and mutators?

A

Attribute casing provides similar functionality without requiring you to define any additional methods on your model.

75
Q

Given an “is_admin” attribute, which stores an integer value of 0 or 1 in the database, use attribute casting to return a boolean instead.

A
protected function casts(): array
    {
        return [
            'is_admin' => 'boolean',
        ];
    }
76
Q

Which method should you use to add temporary attribute casts at runtime?

A
$example->mergeCasts([
    'is_admin' => 'integer',
    'options' => 'object',
]);
77
Q

Why are array casts useful when working with columns that are stored as serialized JSON?

A

Adding the array cast to a field that contains serialized JSON will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model. When you update the value of a deserialized attribute, it will automatically be serialized back into JSON for storage.

78
Q

Store a collection of the enum “ServerStatus” under the column “statuses” by casting the enum into a single column!

A
protected function casts(): array
{
    return [
        'statuses' => AsEnumCollection::of(ServerStatus::class),
    ];
}
79
Q

How can you create a custom cast type using Artisan?

A

php artisan make:cast Example

80
Q

All custom cast classes implement the CastsAttributes interface. Which 2 methods need to be defined by classes that implement this interface and what do they do?

A

get() / set()

The get method is responsible for transforming a raw value from the database into a cast value, while the set method should transform a cast value into a raw value that can be stored in the database. Both are required to be implemented.

81
Q

When defining custom casts that are casting values to objects, what should the set() method return?

A

It should return an array of key / value pairs that will be used to set raw, storable values on the model.

82
Q

When attributes that are cast to value objects are resolved, they are cached by Eloquent. Therefore, the same object instance will be returned if the attribute is accessed again. How can you disable the object caching behavior of custom cast classes?

A

(in said public cast class)

public bool $withoutObjectCaching = true;

83
Q

How can you make an inbound only custom cast using Artisan?

A

php artisan make:cast Example –inbound

84
Q

What is different between normal and inbound casting?

A

With inbound casting you can only transform values that are being set on the model and can’t perform any operations when attributes are being retrieved from the model.

85
Q

You may want to allow your application’s value objects to define their own custom cast classes. Instead of attaching the custom cast class to your model, you may alternatively attach a value object class that implements which interface?

A

the Illuminate\Contracts\Database\Eloquent\Castable interface

86
Q

Which method do objects that implement the Castable interface have to implement and what is it responsible for?

A

Objects that implement the Castable interface must define a castUsing method that returns the class name of the custom caster class that is responsible for the casting to and from the Castable class.

87
Q

Describe a one to one database relationship!

A

Exactly one model is directly associated with exactly one other model, for example:
A User model might be associated with one Phone model. To define this relationship, we will place a phone method on the User model. The phone method should call the hasOne method and return its result. The hasOne method is available via the Illuminate\Database\Eloquent\Model class.

For this example the phone method would look like this:

    public function phone(): HasOne
    {
        return $this->hasOne(Phone::class);
    }
88
Q

How can you define the inverse of a hasOne relationship on the other side of the relationship?

A

Using the example of a User model being associated with one Phone model:

(in the Phone model)

public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

The inverse of hasOne is belongsTo

89
Q

What is a one to many relationship?

A

It is used to define relationships, where a single model is the parent to one or more child models. For example, a blog post may have an infinite number of comments. To stick with this example, here is the necessary “comments()” function that needs to be implemented into the Post model:

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
90
Q

Given a one to many relationship between the models Post and Comment, write the method needed in the Comment method to signify that many comments can be related to one Post!

A
public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }
91
Q

The belongsTo, hasOne, hasOneThrough and morphOne relationships allow you to define a default model that will be returned if the given relationship is null. How can you add a default response instead?

A
public function example(): BelongsTo{
{
    return $this->belongsTo(Example::class)->withDefault([
        'test' => 'This is a test',
    ]);
}
92
Q

Given the model Post and the variable $user, define $posts as the posts of the user!

A

$posts = Post::whereBelongsTo($user)->get();

93
Q

Often, when retrieving a single model using the latestOfMany, oldestOfMany, or ofMany methods, you already have a “has many” relationship defined for the same model. For convenience, Laravel allows you to easily convert this relationship into a “has one” relationship by invoking the “one()” method on the relationship. Use it to find the order, where “price” is “max”:

public function orders(): HasMany
{
    return $this->hasMany(Order::class);
}
A
public function largestOrder(): HasOne
{
    return $this->orders()->one()->ofMany('price', 'max');
}
94
Q

Define the has one through relationship type!

A

It defines a one to one relationship with another model. However, this relationship indicates that the declaring model can be matched with one instance of another model by proceeding through a third model.
For example, in a vehicle repair shop application, each Mechanic model may be associated with one Car model, and each Car model may be associated with one Owner model. While the mechanic and the owner have no direct relationship within the database, the mechanic can access the owner through the Car model.

95
Q

A mechanic has a one to one relationship with a car, so does the owner of the car. How can you access the Owner model in the Mechanic model through the Car model?

A
public function carOwner(): HasOneThrough
{
    return $this->hasOneThrough(Owner::class, Car::class);
}

The first passed model is the one we wish to access and the second argument is the name of the intermediate model, that is used as the bridge between the two not directly connected models.

96
Q

If the relationship between 2 models through a 3rd one is already indirectly established by having model a and model b in a relationship and model b and c, how can you simplify the definition of a “has one through” relationship?

A
// String based syntax...
return $this->through('b')->has('c');

// Dynamic syntax...
return $this->throughB()->hasC();

this is from the perspective of model a to get to model c

97
Q

If model A has a one to one relationship with model B and model B has many model C relationships, what is the relationship between model A and the C models called?

A

hasManyThrough()

98
Q

What is the name of the relationship between multiple model As and multiple model Bs? For example, a user may have multiple roles but those roles might also be assigned to a lot of other users.

A

many to many relationships are between multiple instances of a model on both sides. They are defined by writing a method that returns the result of the belongsToMany method.

99
Q

What is the inverse of the belongsToMany method?

A

belongsToMany(). A many to many relationship is the one type of relationship where both sides get the same method implemented to define their relationship with each other

100
Q

Given users, that have an id and a name and roles that have an id and a name, what does the intermediate table for a many to many relationship between have to look like structurally?

users
id - integer
name - string

roles
id - integer
name - string

A

role_user
user_id - integer
role_id - integer

101
Q

What does a polymorphic relationship do?

A

A polymorphic relationship allows the child model to belong to more than one type of model using a single association. For example, on a website that lets you share videos and posts, a comment might belong to both the Post and Video models.

102
Q

Which 2 methods are used for polymorphic one to one relationships?

A

morphTo() and morphOne()

morphTo() is for the parent model of the one currently being coded in and the morphOne() methods are for the actual relationship referencing the method that implemented morphTo as their second argument while the first argument is the class the relationship exists with.

103
Q

Where lies the difference between a one to many and a polymorphic one to many relationship?

A

With a polymorphic one to many relationship the child model can belong to more than one type of model using a single association which the normal one to many relationship child can’t.

104
Q

Explain what a polymorphic many to many relationship is!

A

2 models, where every instance has a relationship with a third model, is a polymorphic many to many relationship. For example:
A Post model and a Video model could share a polymorphic relation to a Tag model. Using a many-to-many polymorphic relation in this situation would allow your application to have a single table of unique tags that may be associated with posts or videos.

105
Q

Working with the example of a many to many polymorphic relationship, where we have the models “Post” and “Video” who share a polymorphic relationship with a Tag model. Give the variable types:

posts
    id - 
    name - 
 
videos
    id - 
    name - 
 
tags
    id - 
    name - 
 
taggables
    tag_id - 
    taggable_id - 
    taggable_type -
A
posts
    id - integer
    name - string
 
videos
    id - integer
    name - string
 
tags
    id - integer
    name - string
 
taggables
    tag_id - integer
    taggable_id - integer
    taggable_type - string
106
Q

Which method should you use in a polymorphic many to many relationship on the side of the parent models?

A

MorphToMany

You create a method of this type within the Model and include a morphToMany within that class that names the relationship.

Example:

    public function categories(): MorphToMany
    {
        return $this->morphToMany(Tag::class, 'categorizable');
    }
107
Q

Define the relationship name of a many to many polymorphic relationship within the return of its MorphToMany method! For this example, name the method tags and the relationship name taggable!

A
public function tags(): MorphToMany
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
108
Q

Which method should you use to define a polymorphic many to many relationship in the child model of said relationship?

A

MorphToMany methods for both parents, then return within those methods using “morphedByMany(ParentClass::class, ‘relationshipname’);)

For example, given a Tag model who’s parents are “Post” and “Video”:

public function posts(): MorphToMany
{
		return $this->morphedByMany(Post::class, 'taggable');
}

/**
 * Get all of the videos that are assigned this tag.
 */
public function videos(): MorphToMany
{
		return $this->morphedByMany(Video::class, 'taggable');
}
109
Q

Given the child model Tag, how can you access the tags related to a Post (from the model Post) with a $post already set and the tags not manually defined?

A
foreach ($post->tags as $tag) {
   // ...
}

“tags” was dynamically created in this context, you don’t need to manually define it.

You can also use dynamic relationship properties for the parents within the child model, it works both ways.

110
Q

How can you add constraints onto a query while running a method, that defined an Eloquent relationship?

A

You can simply add the other constraints onto the method call using ->

VERY IMPORTANT DETAIL, DON’T DO THIS WITH orWhere CLAUSES!!!!!!!
To explain the reasoning behind that using an example:

$user->posts()
        ->where('active', 1)
        ->orWhere('votes', '>=', 100)
        ->get();

will generate the following SQL:

select *
from posts
where user_id = ? and active = 1 or votes >= 100

Suddenly it doesn’t need to be the specified user which is active or has over 100 votes, but instead its the specified user when they are active or ANY user with over 100 posts

111
Q

How can you use orWhere clauses when chaining them onto a relationship method?

A

By using logical groups to group the conditional checks between parentheses. For example:

$user->posts()
        ->where(function (Builder $query) {
            return $query->where('active', 1)
                         ->orWhere('votes', '>=', 100);
        })
        ->get();
112
Q

If you have a model A and want to test if it does have an existing relationship with a model B, how can you check that?

A

$result = ModelA::has('relationshipname')->get();

113
Q

Which method is used to find out if a relationship between two models has a certain variable set a certain way?

A
$result = ModelA::whereRelation('relationshipname', 'variable', state)->get()

For example:
$posts = Post::whereRelation('comments', 'is_approved', false)->get();
or

$posts = Post::whereRelation(
    'comments', 'created_at', '>=', now()->subHour()
)->get();;
114
Q

Check if a condition is not met within a specified relationship!

A

$result = ModelA::doesntHave('relationship')->get();

you can also have a whereDoesntHave that includes whichever where conditions you may want to include

115
Q

How can you check for the existence of “morph to” relationships?

A

::whereHasMorph or ::whereDoesntHaveMorph

These methods accept the name of the relationship as the first argument, the names of the related models as the second and finally you may provide a closure which customizes the relationship query

116
Q

What is the difference between lazy loading and eager loading?

A

With lazy loading the related models don’t have their relationship data loaded until you first access the property. Eager loading with Eloquent allows you to load the relationships at the same time as you query the parent model.

117
Q

Why should you eager load some things instead of lazy loading them?

A

Eager loading alleviates the “N+1” query problem. If you try to retrieve 25 items with lazy loading in place, then your code will run 26 queries but if eager loading was used then that cuts the amount of queries down to 2.

118
Q

How can you eager load several different relationships at the same time?

A

$results = ModelA::with(['relationshipa', 'relationshipb'])->get();

119
Q

How can you eager load a relationship’s relationship?

A

By using the with method and using dot syntax, for example to eager load all of the contacts of an autor:

$books = Book::with('author.contacts')->get();

120
Q

Is there a way to eager load something that has already been lazy loaded? If yes, which method is used?

A

->load(INSERT THE ATTRIBUTES TO BE LOADED);

if you only want to load a relationship if it has not already been loaded, use the loadMissing() method instead!

121
Q

What do you need to do to eager load a nested relationship that has already been lazy loaded?

A

loadMorph()

122
Q

Which method can stop your application from trying to lazy load anything and instead only eager load?

A

In the boot() method of the AppServiceProvider class:

Model::preventLazyLoading(! $this->app->isProduction());

The condition in the brackets is optional but definitely useful in case of there being an accidental lazy loaded relationship present in your production code. Model is also not a placeholder in this case, by entering that exact code snippet into the mentioned method the whole application will no longer use lazy loading. After preventing lazy loading, your application will throw a Illuminate\Database\LazyLoadingViolationException exception when it attempts to lazy load any Eloquent relationship.

123
Q

Which method can add new models to relationships and why may you want to do that?

A

->save(INSERT MODEL TO ADD)

It’s very useful because it allows you to add things like comments to posts without manually needing to set the post id in the Comment model. To give a code snippet for this particular example:

$comment = new Comment(['message' => 'A new comment.']);
 
$post = Post::find(1);
 
$post->comments()->save($comment);
124
Q

How can you save multiple related models to a relationship?

A

->saveMany([INSERT MODELS]);

125
Q

What do you need to do to save your model and all of its associated relationships?

A

->push();

If you wish to save a model and its associated relationships without raising any events, use the pushQuietly() method instead

126
Q

What is the major difference between the save and create methods?

A

save accepts a full Eloquent model instance while create accepts a plain PHP array. create also offers a createQuetly, createMany and createManyQuietly variant.

127
Q

How can you assign a child model to a new parent model?

A

->associate();

128
Q

How can you remove a child model from a parent model?

A

->disassociate();

129
Q

Which method attaches one model to another in a many to many relationship?

A

->attach();

This is useful to, for example, assign a role to a user where a user can have multiple roles and a role can be had by multiple users.

130
Q

How can you remove the attachment of 2 models in a polymorphic many to many relationship?

A

->detach();

This could be used to, for example, remove the role of a user by providing the role id within the brackets. To specifically remove every role from a user, just to stick with this example, the code may look like this:

$user->roles()->detach();

131
Q

Construct a many-to-many association using the sync method!

A

$modelinstance->dynamicmethod()->sync([1, 2, 3]);

132
Q

Which method will either attach if a given related model ID is detached or detach if it is attached?

A

->toggle([INSERT STUFF TO TOGGLE]);

133
Q

It may be useful to also update the “updated_at” column of a parent model if a child gets updated. How can you accomplish this?

A

within the child model:

protected $touches = ['model or array of models that is supposed to be updated written in all lower case']

Parent model timestamps will only be updated if the child model is updated using Eloquent’s save method

134
Q

How can you convert a model and its loaded relationships to an array?

A

->toArray();

This method is recursive so all attributes and all relations (including the relations of relations) will be converted to arrays.

135
Q

If you only want to convert the attributes of a model to an array without including all of the relationships of the model, how can you do that?

A

->attributesToArray();

136
Q

How can you serialize all attributes and relationships of a model as a JSON?

A

->toJson();

This is also recursive, so it will convert every attribute, relationship and the relationships of relationships to a JSON format.

137
Q

All Eloquent relationship methods are defined using camel case method names, a relationship’s JSON attribute will be snake case. What do these terms mean?

A

thisIsCamelCase and this_is_snake_case

camel case gets written as one word and the first letter of every word inside of it gets capitalized, while with snake case the words are split apart by underscores and everything is lower case.

138
Q

Some attributes should not be included when outputting a model’s attributes as an array or as a JSON, like passwords. Which way can you stop them from being included in the output?

A

Within the model, that you want to exclude attributes out of:

protected $hidden = ['password', 'whateverelse'];

To hide relationships, add the relationship’s method name to your Eloquent model’s $hidden property.

139
Q

Sometimes you may only want certain selected attributes to be shown when a model is converted to an array or a JSON. How can you define them?

A

Within the model, that you want to only show certain attributes out of:

protected $visible = ['attribute', 'whateverotherattributes'];

All attributes, that are not present in the $visible array, will be hidden when the model is converted to an array or JSON.

140
Q

How can you add attributes to the list of visible or hidden attributes temporarily for one command and how can you temporarily overwrite them for one command?

A

example commands:

return $user->makeVisible('attribute')->toArray();
return $user->makeHidden('attribute')->toArray();
return $user->setVisible(['id', 'name'])->toArray();
return $user->setHidden(['email', 'password', 'remember_token'])->toArray();

The first command adds an attribute or an array of attributes to the already preexisting list of attributes to be shown. The second command does the same but for hidden attributes. The third command actually takes priority over the list of attributes set originally and for the span of that command only the attributes listed in the command will be visible and the last one does the same thing but for hidden attributes.