Eloquent ORM Flashcards
Generate a resource class using Artisan!
php artisan make:resource ExampleResource
What is a resource class?
A resource class represents a single model that needs to be transformed into a JSON structure.
Which method does every resource class need to specify and what is it used for?
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
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?
ExampleResource::collection(Example::all());
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?
public $preserveKeys = true;
By default Laravel will wrap everything under a “data” key when generating a JSON response. How can you stop Laravel from doing so?
(in the boot() method of the AppServiceProvider)JsonResource::withoutWrapping();
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?
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 } }
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, ]; }
public function toArray(Request $request): array { return [ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email, 'secret' => $this->when($request->user()->isAdmin(), 'secret-value'), ]; }
Which method should you use instead of when() if multiple attributes should be included in the resource response based on the same condition?
mergeWhen(INSERT CONDITION, [ 'first-secret' => 'value', 'second-secret' => 'value', ])
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?
'example' => ExampleResource::collection($this->whenLoaded('example'))
Given a model called “Flight”, what will the corresponding database be named according to Laravel conventions?
flights
Which property do you need to add to a model to rename the database to something that does not follow the Laravel naming conventions?
protected $table = 'example';
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?
public $incrementing = false; protected $keyType = 'string';
What are UUIDs?
universally unique alpha-numeric identifiers
They are a 36 character long identifier that can be used instead of a primary key.
How can you use UUIDs instead of the normal auto-incrementing primary keys?
use Illuminate\Database\Eloquent\Concerns\HasUuids; // ... class Example extends Model { use HasUuids; // ... }
How can you use ULIDs instead of the normal auto-incrementing primary keys?
use Illuminate\Database\Eloquent\Concerns\HasUlids; // ... class Example extends Model { use HasUlids; // ... }
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?
public $timestamps = false;
Customize the names of your “created_at” and “updated_at” columns!
const CREATED_AT = 'creation_date'; const UPDATED_AT = 'updated_date';
you can also enter other things for the names, these are just examples
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?
protected $connection = 'mysql';
mysql is just an example here
In the AppServiceProvider class, disable lazy loading if the application is running in a non-production environment!
(in boot() method)Model::preventLazyLoading(! $this->app->isProduction());
What does the refresh() method do?
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"
What happens if a ModelNotFoundException is not caught?
A 404 HTTP response is automatically sent back to the client
What is the firstOrCreate method used for?
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.
What is the difference between the firstOrNew and the firstOrCreate method?
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