YouTubestream· May 27, 2024· 1:34:34

I keep reading the entire Laravel documentation

Watch on YouTube ↗

transcript

171 moments
  1. Music

  2. Thank you.

  3. I'm going to go ahead and put it in the middle of the room.

  4. Thank you.

  5. so

  6. Thank you.

  7. I'm going to go ahead and put it in the middle of the room.

  8. Thank you.

  9. I'm going to go ahead and put it in the middle of the room.

  10. Thank you.

  11. so

  12. Thank you.

  13. so

  14. Thank you.

  15. All right.

  16. Let's get back into it.

  17. So Eloquent ORM. Introduction. Laravel includes Eloquent, an object relational mapper that makes it enjoyable to interact

  18. with your database. When using Eloquent, each database table has a corresponding model that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well. Generating model classes. To get started, let's create an Eloquent model. Models typically

  19. live in the app slash models directory and extend the Illuminate Database Eloquent Model class. You may use the Make Model Artisan command to generate a new model. So Make Model Flight, if you would like to generate a database migration when you generate the model, you may use the Migration or dash M option. You may generate various other types of classes when generating models such as factories, seeders, policies, controllers, and form requests. In addition, these options may be combined to create multiple classes at once.

  20. So generate a model in a flight factory class, flight cedar class, flight controller class,

  21. You can generate resource class and form request classes, a flight policy class. You can generate migration, factory, seeder, and controller, model migration, factory, seeder, policy, controller, and form requests, and generate a pivot model as well. Sometimes it can be difficult to determine all of a model's available attributes and relationships just by skimming its code. Instead, try the model show artisan command, which provides a continuing overview of all the models,

  22. attributes, and relations. Eloquent model conventions. Models generated by the make model command will be placed in the app models directory. Let's examine a basic model class and discuss some of Eloquent's key conventions. So class, flight, extends, model. Table names. After glancing at the example above, you may have noticed that we did not tell Eloquent which database table corresponds to our flight model. By convention, the snake case, plural name of the

  23. case class will be used as the table name unless another name is explicitly specified. So in this case, Eloquent will assume the flight model stores records in the flights table while an air traffic controller model would store records in the air traffic controllers table. If your models corresponding database table does not fit this convention, you may manually specify the models table name by defining a table property on the model. So

  24. protected table. Primary keys. Eloquent will also assume that each model's corresponding database table has a primary key column named ID. If necessary, you may define a protected primary key property on your model to specify a different column that serves as your model's primary key. In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that Eloquent will automatically cast the primary key to an integer. If you wish

  25. to use a non-incrementing or non-numeric primary key, you must define a public incrementing property on your model that is set to false. If your model's primary key is not an integer, you should define a protected key type property on your model. This property should have a value of string. Composite primary keys. Eloquent primary, uh, requires each model to have at least one uniquely identifying ID that can serve as its primary key. Composite primary

  26. keys are not supported by eloquent models. However, you are free to add additional multi-column and unique indexes to your database tables in addition to the table's uniquely identifying primary key. UUID and ULIDs. Instead of using auto-incrementing integers as your eloquent model's primary keys, you may choose to use UUIDs instead. UUIDs are universally unique

  27. alphanumeric identifiers that are 36 characters long. So if you would like a model to use a UUID key instead of an auto-incrementing integer key, you may use the Eloquent Concerns Has UUIDs trait on the model. Of course, you should ensure that the model has a UUID equivalent primary key column. Use Has UUIDs. By default, the Has UUIDs trait will generate ordered UUIDs

  28. for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically. You can override the UUID generation process for a given model by defining a new unique ID method on the model. In addition, you may specify which columns should receive UUIDs by defining a unique IDs method on the model. If you wish,

  29. may choose to utilize ULIDs instead of UIDs. ULIDs are similar to UUIDs, however, they are only 26 characters in length. Like ordered UUIDs, ULIDs are lexicographically sortable for efficient database indexing. To utilize ULIDs, you should use the Concerns Has ULIDs trait on your model. You should also ensure that the model has a ULID equivalent primary

  30. key column. Timestamps. By default, Eloquent expects created at and updated at columns to exist on your model's corresponding database. Eloquent will automatically set these columns values when models are created or updated. If you do not want these columns to be automatically managed by Eloquent, you should define a timestamps property on your model with a value of false.

  31. If you need to customize the format of your model's timestamps, set the Date Format property on your model. This property determines how date attributes are stored in the database as well as their format when the model is serialized to an array or JSON. If you need to customize the names of the columns used to store the timestamps, you may define createdAt and updatedAt constants on your model. If you would like to perform model operations without the model having its updatedAt timestamp

  32. modified, you may operate on the model with a closure given to the without timestamps method. By default, all eloquent models will use the default database connection that is configured for your application. If you would like to define a specific connection that should be used when interacting with a particular model, you should define a connection property on the model. By default, a newly instantiated model instance will not contain any attribute

  33. If you would like to define the default values for some of your model's attributes, you may define an attributes property on your model. Attribute values placed in the attributes array should be in their raw, storable format as they were just read from the database. Laravel offers several methods that allow you to configure eloquence, behavior, and strictness in a variety of situations. First, the prevent lazy loading method accepts an optional boolean argument that indicates if lazy loading should be prevented. For example, you may wish to only

  34. disable lazy loading in non-production environments so that your production environment will continue to function normally even if a lazy loaded relationship is accidentally present present in production code. Typically, this method should be invoked in the boot method of your application's app service provider. Also, you may instruct Laravel to throw an exception when attempting to fill an unfillable attribute by invoking the prevent silently discarding attributes method. This can help prevent unexpected errors during local development when attempting to set an

  35. attribute that has not been added to the model's fillable array. Once you have created a model and its associated database table, you are ready to start retrieving data from your database. You can think of each eloquent model as a powerful query builder, allowing you to fluently query the database table associated with the model. The models The EloquentAll method will retrieve all of the records from the models associated database table.

  36. The EloquentAll method will return all of the results in the models table. However, since each Eloquent model serves as a query builder, you may add additional constraints to queries and then evoke the Git method to retrieve the results. If you already have an instance of an Eloquent model that was retrieved from the database, you can refresh the model using the fresh and refresh methods. The refresh method will retrieve the model from the database. The existing model instance will not be affected.

  37. The refresh method will rehydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well. Collections. As we have seen, eloquent methods like all and git retrieve multiple records from the database. However, these methods don't return a plain PHP array. Instead an instance of eloquent collection is returned. Your eloquent collection class extends Laravel's base support collection class which provides a variety of helpful methods for interacting with data collections. For example, the reject

  38. method may be used to remove models from a collection based on the results of an invoked closure. In addition to the methods provided by Laravel's base collection class, the Eloquent collection class provides a few extra methods that are specifically intended for interacting with collections of Eloquent models. Since all of Laravel's collections implement PHP's Iterable interfaces. You may loop over collections as if they were an array. For each flight says

  39. flight, echo, flight, name. Chunking results. Your application may run out of memory if you attempt to load tens of thousands of eloquent rare records via the all or get methods. Instead of using these methods, the chunk method may be used to process large numbers of models more efficiently. The chunk method will retrieve a subset of eloquent models, passing them to a closure for processing. Since only the current chunk of eloquent models is retrieved at a time, the chunk method will provide significantly reduced memory usage when working with a large

  40. number of models. The first argument passed to the chunk method is the number of records you wish to receive per chunk. The closure passed as the second argument will be invoked for each chunk that is received from the database. A database query will be executed to retrieve each chunk of records passed to the closure. If you are filtering the results of the chunk method based on a column that you will also be updating while iterating over the results, you should use the chunk by ID method. Using the chunk method in these scenarios could lead to unexpected and inconsistent results.

  41. Internally, the chunk by ID method will always retrieve models with an ID column greater than the last model in the previous chunk. Chunking using lazy collections. The lazy method works similarly to the chunk method in the sense that behind the scenes it executes the query in chunks. However, instead of passing each chunk directly into a callback as is, the lazy method returns a flattened lazy collection of eloquent models, which lets you interact with the results

  42. as a single stream. If you are filtering the results of the lazy method based on a column that you'll also be updating while iterating over the results, you should use the lazy by ID method. Internally, the lazy by ID method will always retrieve models with an ID column greater than the last model in the previous chunk. You may filter the results based on the descending order of the ID using the lazy by ID descending method. Cursors. Similar to the lazy method, the cursor

  43. method may be used to significantly reduce your application's memory consumption when iterating through tens of thousands of eloquent model records. The cursor method will only execute a single database query. However, the individual eloquent models will not be hydrated until they are actually iterated over. Therefore, only one eloquent model is kept in memory at any given time while iterating over the cursor. Internally, the cursor method uses PHP generators to implement

  44. this functionality. So for each flightware destination, cursor as flight, the cursor returns a lazy collection instance. Lazy collections allows you to use many of the collection methods available on typical Laravel collections while only loading a single model into memory at a time. Although the cursor method uses far less memory than a regular query by only holding a single Eloquent model and memory at a time, it will still eventually run out of memory. This is due to PHP's

  45. PDO driver internally caching all raw query results in its buffer. If you're dealing with a very large number of Eloquent records, consider using the lazy method instead. Advanced subqueries, subquery selects. Eloquent also offers advanced subquery support, which allows you to pull information from related tables in a single query. For example, let's imagine that we have a table of flight destinations, and a table of flights to destinations. The flights table contains an

  46. arrived at column which indicates when the flight arrived at the destination. Using the subquery functionality available to the Query Builder's select and add select methods, we can select all of the destinations and the name of the flight that most recently arrived at that destination using a single query. Subquery ordering. In addition, the Query Builder's order by function supports subqueries. Continuing to use our flight example, we may use the functionality

  47. to sort all destinations based on when the last flight arrived at the destination. Again, this may be done while executing a single database query. Retrieving single models and aggregates. In addition to retrieving all of the records matching a given query, you may also retrieve single records using the find first or first where methods instead of returning a collection of models. These methods return a single model instance. Sometimes you may wish to perform some other action if no results

  48. are found, the findOr and firstOr methods will return a single model instance or, if no results are found, execute the given closure. The value returned by the closure will be considered the result of the method. Sometimes you wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and

  49. first or fail methods will retrieve the first result of the query. However, if no result is found, an illuminate database collect eloquent model not found exception will be thrown. If the model not found exception is not caught, a 404 HTTP response is automatically sent back to the client. Retrieving or creating models. The first or create method will attempt to locate a database record using the given column value pairs. If the model cannot be found in the database, a record will be inserted with the attributes resulting from merging

  50. the first array argument with the optional second array argument. The first or new method, like first or create, 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 first or new has not yet been persisted to the database. You will need to manually call the save method to persist it. Retrieving aggregates. When interacting with

  51. With Eloquent models, you may also use the count, sum, max, and other aggregate methods provided by the Laravel Query Builder. As you might expect, these methods return a scalar value instead of an Eloquent model instance. Inserts. Of course, when using Eloquent, we don't only need to retrieve models from the database, we also need to insert new records. Thankfully, Eloquent makes it simple. To insert a new record into the database, you should instantiate a new record, a new

  52. model instance and set attributes on the model, then call the save method on the model instance. So flight is new flight, flight name, request name, flight save. In this example, we assign the name field from the incoming HTTP request to the name attribute of the app models flight model instance. When we call the save method, a record will be inserted into the database. The models created at and updated at timestamps will automatically be set

  53. when the save method is called. So there is no need to set them manually. Alternatively, you may use the create method to save a new model using a single PHP statement. The inserted model instance will be returned to you by the create method. However, because using the create method you will need, before using the create method, you will need to specify either a fillable or guarded property on your model class. These properties are required because all eloquent models are protected against mass

  54. assignment. Vulnerabilities by default. The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it and set any attributes you wish to update. Then you should call the models save method. Again, the updated that timestamp will automatically be updated so there is no need to manually set its values.

  55. Occasionally you may need to update an existing model or create a new model if no matching model exists. Like the first or create method, the update or create method persists the model, so there's no need to manually call the save method. In the example below, if a flight exists with a departure location of Oakland and a destination location of San Diego, its price and discounted columns will be updated.

  56. If no such flight exists, a new flight will be created, which has the attributes resulting from merging the first argument array with the second argument array. Mass updates. Updates can also be performed against models that match a given query. In this example, all flights that are active and have a destination of San Diego will be marked as delayed. The update method expects an array of column and value pairs representing the columns that should be updated. The update method returns the number of affected rows.

  57. Examining attribute changes. Eloquent provides the isDirty, isClean, and wasChanged methods to examine the internal state of your model and determine how its attributes have changed from when the model was originally retrieved. The isDirty method determines if any of the model's attributes have been changed since the model was retrieved. You may pass a specific name of an array or attributes to the isDirty method to determine if any of the attributes are dirty. The isClean method will determine if an attribute has remained unchanged since the model was retrieved.

  58. This method also accepts an optional attribute argument. The wasChanged method determines if any attributes were changed when the model was last saved within the current request lifecycle. If needed, you may pass an attribute name to see if a particular attribute was changed. The getOriginal method returns an array containing the original attributes of the model regardless of any changes to the model since it was retrieved. If needed, you can pass a specific attribute name to get the original value

  59. particular attributes. MassAssignment. You may use the create method to save a new model using a single PHP statement. The insert in model instance will be returned to you by the method. However, before using the create method, you will need to specify either a fillable or guarded property on your model class. These properties are required because all eloquent models are protected against a mass assignment vulnerabilities by default.

  60. A mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes the column in your database that you did not expect. For example, a malicious user might send an isAdmin parameter through an HTTP request, which is then passed to your model's create method, allowing the user to escalate themselves to an administrator. So to get started, you should define which model attributes you want to make mass assignable. You may do this using the fillable property on the model.

  61. For example, let's make the name attribute of our flight model mass assignable. Once you have specified which attributes are mass assignable, you may use the create method to insert a new method, a new record in the database. The create method returns the newly created model instance. If you already have a model instance, you may use the fill method to populate it with an array of attributes. When assigning JSON columns, each column's mass assignable key must be specified in your model's fillable array.

  62. For security, Laravel does not support updating nested JSON attributes when using the guarded property. Allowing Mass Assignment. If you would like to make all of your attributes mass assignable, you may define your model's guarded property as an empty array. If you choose to un-guard your model, you should take special care to always handcraft the array's past Eloquent's fill, create, and update methods. By default, attributes that are not included in the fillable array are silently discarded when performing mass assignment operations. In production, this is expected behavior.

  63. However, during local development, it can lead to confusion as to why model changes are not taking effect. If you wish, you may instruct Laravel to throw an exception when attempting to fill an unfillable attribute by invoking the prevents silently discarding attributes method. Typically this method should be invoked in the boot method of your application's app service provider class. Upserts. Eloquent's upsert method may be used to update or create records in a single atomic operation.

  64. The method's first argument consists of the values to insert or update, while the second argument lists the columns that uniquely identify records within the associated table. The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database. The Upsert method will automatically set the created at and updated at timestamps if timestamps are enabled on the model. Deleting models. To delete a model, you may call the delete method on the model instance.

  65. You may call the truncate method to delete all of the model's associated database records. The truncate operation will also reset any auto-incrementing IDs on the model's associated table. In the example above, flight truncate, we are retrieving the model from the database before calling the delete method. However, if you know the primary key of the model, you may delete the model without explicitly retrieving it by calling the destroy method. In addition to accepting the single primary key, the destroy method will accept multiple primary keys, an array of primary keys,

  66. or a collection of primary keys. Of course, you may build an eloquent query to delete all models matching your query's criteria. In this example, we will delete all flights that are marked as inactive. Like mass updates, mass deletes will not dispatch model events for the models that are deleted. Soft deleting. In addition to actually removing records from your databases, Eloquent can also soft delete models. When models are soft deleted, they're not actually removed from your database. Instead, a deleted at attribute

  67. is set on the model, indicating the date and time at which the model was deleted. To enable soft deletes for a model, add the illuminate database Eloquent soft deletes trait to the model. You You should also add the deleted at column to your database table. The Laravel schema builder contains a helpful method to create this column. Now, when you call the delete method on the model, the deleted at column will be set to the current date and time. However, the model's database record will be left in the table.

  68. When querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results. To determine if a given model instance has been self-deleted, you may use the trashed method. Restoring self-deleted models. Sometimes you may wish to undelete a self-deleted model. To restore

  69. a self-deleted model, you may call the restore method on a model instance. The restore method will set the models deleted at column to null. You may also use the restore method in a query to restore multiple models. Again, like other mass operations, this will not dispatch any model events for the models that are restored. The restore method may also be used when building relationship queries. Sometimes we need to truly remove a model from your database. You may use the force delete method to permanently remove a soft deleted model from the database

  70. table. You may also use the force delete method when building eloquent relationship queries. Querying soft deleted models. As noted above, soft deleted models will automatically be excluded from query results. However, you may force deleted models to be included in a query's results by calling the withTrashed method on the query. So flight withTrashed where countID get. The withTrashed method may also be called when building a relationship

  71. query. Retrieving only soft deleted models. The only trashed method will retrieve only soft deleted models. Pruning models. Sometimes you may want to periodically delete models that are no longer needed. To accomplish this, you may add the eloquent prunable or eloquent mass prunable trait to the models you would like to periodically prune. After adding one of the traits to the model, implement a prunable method which returns an eloquent query builder that resolves the models

  72. that are no longer needed. So public function prunable returns static where created at is less than or equal to now with some month. When marking models as prunable, you may also define a pruning method on the model. This method will be called before the model is deleted. This method can be useful for deleting any additional resources associated with the model, such as stored files before the model is permanently removed from the database. After configuring your

  73. prunable model, you should schedule the model prune artisan command in your application's routes console.php file. You are free to choose the appropriate interval at which this command should run. Behind the scenes, the model prune command will automatically detect prunable models within your applications app models directory. If your models are in a different

  74. location, you may use the dash dash model option to specify the model class names. If you wish to exclude certain models from being pruned while pruning all of the detected models, you may use the dash dash accept option. You may test your prunable query by executing the model prune command with the pretend option. When pretending the model prune command will simply report how many records would be pruned if the command were to actually run.

  75. Mass pruning. When models are marked with the mass prunable trait, models are deleted from the database using mass deletion queries. Therefore, the pruning method will not be invoked, nor will the deletion and deleted models events be dispatched. This is because the models are never actually retrieved before deletion, thus making the pruning process

  76. much more efficient. Once the relationship is defined, you may access the user's role using the roles dynamic relationship property. Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the roles method and continuing to change conditions onto the query.

  77. Defining the inverse of the relationship. To define the inverse of a many to many relationship, you should define a method on the related model, which also returns the result of the belongs to many method. By default, only the model keys will be present on the pivot model. If you would like your intermediate table to have created at and updated at timestamps that are automatically maintained by Eloquent, the with timestamps method when defining the relationship,

  78. return this belongs to many. Filtering queries via intermediate table columns. You can also filter the results returned by belongs to many relationship queries using the where pivot, wherePivotNotIn, wherePivotBetween, wherePivotNull, and wherePivotNotNull methods when defining the relationship. Ordering queries via intermediate table columns. You can order the query results returned by belongsToMany relationship queries using the orderByPivot method. In the following example,

  79. we retrieve all the latest badges for the user. So this belongs to many badge class, where rank is gold or order by pivot created at descending. If you would like to define a custom model to represent the intermediate table of your many-to-many relationships, you may call the using method when defining the relationship. Custom pivot models give you the opportunity to define additional behavior on the pivot model, such as method and casts. Custom many-to-many pivot

  80. models should extend the RelationsPivot class, while CustomPolymorphicManyToManyPivot models should extend the RelationsMorphPivot class. For example, we may define a role model, which uses a custom role user pivot model. When defining the role user model, you should extend the Eloquent RelationsPivot class. CustomPivot models and incrementing IDs. If you had defined

  81. a many-to-many relationship that uses a custom pivot model, and that pivot model has an auto incrementing primary key, you should ensure your custom pivot model class defines an incrementing property that is set to true. One-to-one polymorphic.

  82. A one-to-one polymorphic relationship is similar to a typical one-to-one relation. However, the child model can belong to more than one type of model using a single association. For example, a blog post and a user may share a polymorphic relation to an image model. Using a one-to-one polymorphic relationship allows you to have a single table of unique images that may be associated with posts and users. Let's examine the table structure, so posts, users, images.

  83. Note the imageable ID and imageable type columns on the images table. The imageable ID column will contain the ID value of the post or user, while the imageable type column will contain the class name of the parent model. Next let's examine the model definitions needed to build this relationship. Retrieving the relationship. Once your database tables and models are defined, you may access the relationships via your models.

  84. To retrieve the image for a post, we can access the image dynamic relationship property. So post, find, image, post, image. You may retrieve the parent of the polymorphic model by accessing the name of the method that performs the call to morph to. In this case, that is the imageable method on the image model. So we will access that method as a dynamic relationship property. The imageable relationship on the image model will return either a post or user instance

  85. depending on which type of model owns the image. Constraining eager loads. Sometimes you may wish to eager load a relationship but also specify additional query relations for the eager loading query. You can accomplish this by passing an array of relationships to the with method where the array key is a relationship name and the array value is a closure that adds additional constraints to the eager loading query.

  86. Eager loading of morph2 relationships. If you are eager loading a morph2 relationship, Eloquent will run multiple queries to fetch each type of related model. You may add additional constraints to each of these queries using the morph2 relationships constraint method. In this example, Eloquent will only eager load posts that have not been hidden and videos that have a type value of educational. Sometimes you may need to eager load a relationship after the parent model has already

  87. been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models. Nested, eager, loading, and morph-to. And if you would like to load a morph-to relationship as well as nested relationships on the various entities that may be returned by that relationship, you may use the load-morph method. This method accepts the name of the morph-to relationship as its first argument, and an array of model relationship pairs as its second argument.

  88. As previously discussed, eager loading relationships can often provide significant performance benefits to your application. Therefore, if you would like, you may instruct the variable to always prevent the lazy loading of relationships. Parent timestamps. When a model defines a belongs to or belongs to any relationship to another model, such as a comment, which belongs to a post, it belongs, it is sometimes helpful to update the parent's timestamp when the child model is updated. For example, when a comment model is updated, you may want to automatically touch the updated

  89. at timestamp of the owning post so that it is set to the current date and time. To accomplish this, you may add a touches property to your child model containing the names of the relationships that should have their updated at timestamps updated when the child model is updated. Eloquent collections. If eloquent methods, all eloquent methods that return more than

  90. one model result will return instances of the Illumina Eloquent Collection class, including results retrieved by the Git method or accessed via a relationship. The Eloquent Collection object extends to Laravel's base collection, so it naturally inherits dozens of methods used to fluently work with the underlying array of eloquent models. Be sure to review the Laravel Collection documentation to learn all about these helpful methods. All collections

  91. also serve as iterators, allowing you to loop over them as if they were simple PHP arrays. However, as previously mentioned, collections are much more powerful than arrays and expose a variety of map-produced operations that may be chained using an intuitive interface. For example, we may remove all inactive models and then gather the first name for each remaining user. Available methods. All eloquent collections extend the base layerable collection object.

  92. Therefore, they inherit all the powerful methods provided by the base collection class. Append, contains, diff, accept, find, fresh, intersect, load, load missing, model keys, make visible, make hidden, only, set visible, set hidden. Append method they used to indicate an attribute should be appended for every model in the

  93. the collection, contains, diff, accept, find, fresh, intersect, load, load missing, model keys, make visible, make hidden, only, set visible, set hidden, to query, unique. Custom collections. If you would like to use a custom collection object when interacting with a given model, you may define a new collection method on your model.

  94. Once you have defined a new collection method, you will receive an instance of your custom collection anytime Eloquent would normally return a collection instance. If you would like to use a custom collection for every model in your application, you should define the new collection method on a base model.

  95. serialization. This is out of order. Okay, there we go. When building APIs using Laravel, you often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in the serialized representation of your models. Serializing to arrays. To convert a model and

  96. and its loaded relationships to an array, you should use the toArray method. This method is recursive, so all attributes and all relations, including the relations of relations, will be converted to arrays. To convert a model to JSON, you should use the toJSON method. Like toArray, the JSON method is recursive, so all attributes and relations will be converted to JSON. You may also specify any JSON encoding options that are supported by PHP. Relationships. When an eloquent model is converted to JSON, its loaded relationships

  97. will automatically be included as attributes on the JSON object. Alternatively, you may hide, you may use the visible property to define an allow list of attributes that should be included in your model's array and JSON representation. All attributes that are not present in the visible array will be hidden when the model is converted to an array of JSON. Appending values to JSON. Occasionally, when converting models to JSON or arrays, you may wish

  98. to add attributes that do not have a corresponding column in your database. To do so, first define an accessor for the value. If you would like the accessor to always be appended to your model's array and JSON representations, you may add the attribute name to the appends

  99. property of your model. Note that attribute names are typically referenced using their snake case or serialized representation even though the accessor's PHP method is defined using camel case. Once the attribute has been added to the appends list, it will be included in both the models array and JSON representations. Attributes in the appends array will also respect the visible and hidden settings configured on the model. Appending at runtime. At runtime, you may instruct a model instance to append additional attributes

  100. using the append method, or you may use the set appends method to override the entire array of appended properties for a given model instance. Customizing the default date format. You may customize the default serialization format for overriding the serialize date method. This method does not affect how your dates

  101. are formatted for storage in the database, customizing the date format per attribute. You may customize the serialization format of individual Eloquent date attributes by specifying the date format in the model's cast declarations. Eloquent Factories Introduction. When testing your application or seeding your database, you may need to insert a few records into your database. Instead of manually specifying the value of each column, Laravel allows you to define

  102. a set of default attributes for each of your eloquent models using model factories. To see an example of how to write a factory, take a look at the database factories userfactory.php file in your application. This factory is included with all new Laravel applications and contains the following factory definition. Public function definition, return, name,

  103. fake name, email, fake unique safe email, email verified at now, password, remember Dota. As you can see in their most basic form, factories are classes that extend Laravel's base factory class and define a definition method. The definition method returns the default set of attribute values that should be applied when creating a model, that should be applied when creating a model using the factory. Via the

  104. the fake helper, factories have access to the faker.php library, which allows you to conveniently generate various kinds of random data for testing and seeding. You can change your application's faker locale by updating the faker locale option in your configapp.php configuration file. Defining model factories. To create a factory, execute the make factory artisan command. The new factory will class will be placed in your factories directory. Once you have defined your factories, you may use the static factory method to provide

  105. to your models by the hasFactory trait in order to instantiate a factory instance for that model. State manipulation methods allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your database factory's user factory factory might contain a suspended state method that modifies one of its default attribute values. State transformation methods typically call the state method provided by Laravel's

  106. base factory class. The state method accepts a closure which will receive the array of raw attributes defined for the factory and should return an array of attributes to modify. Factory callbacks. Factory callbacks are registered using the after making and after creating methods and allow you to perform additional tasks after making or creating a model. You

  107. register these callbacks by defining a configure method on your factory class. Once you have defined your factories, you may use the static factory method provided to your models by the factories has factory trait in order to instantiate a factory instance for that model. If you would like to override some of the default values of your models, you may pass an array of values to the make method. Only the specified attributes will be replaced while the rest of the attributes remain set

  108. to their default values as specified by the factory. Alternatively, the state method may be called directly on the factory instance to perform an inline state transformation. Sometimes you may wish to alternate the value of a given model attribute for each created model. You may accomplish this by defining a state transformation as a sequence. For example, you may wish to alternate the value of an admin column between Y and N for

  109. each created user. Using magic methods. For convenience, you may use Laravel's magic factory relationship methods to define belongs to relationships. For example, the following example will use a convention to determine that the three posts should belong to the user relationship on the post model. So post factory, count, user, for user, name, Jessica to arch create.

  110. Polymorphic relationships may also be created using factories. Polymorphic morph many relationships are created in the same way as typical has many relationships. For example, if an atModel's post model has a morph many relationship with an atModel's comment model morph to relationships. Magic methods may not be used to create morph to relationships. Instead, the for method must be used directly and the name of the relationship must be explicitly provided. For example, imagine that the comment model

  111. has a commentable method that defines a morph to relationship. In this situation, you may create three comments that belong to a single post by using the for method directly. Polymorphic many-to-many relationships. Polymorphic many-to-many relationships may be created just like non-polymorphic many-to-many relationships. Of course, the magic has method may also be used create polymorphic many-to-many relationships. To define a relationship within your model

  112. factory, you will typically assign a new factory instance to the foreign key of their relationship. This is normally done for the inverse relationships such as belongs to and morph to relationships. For example, if you would like to create a new user when creating a post, you may do the following. So return, user ID, user factory, title, fake title, content, fake paragraph.

  113. Recycling an existing model for relationships. If you have models that share a common relationship with another model, you may use the recycle method to ensure a single instance of the related model is recycled for all the relationships created by the factory. For example, imagine if you have an airline, flight and ticket models where the ticket belongs to an airline and a flight, and the flight also belongs to an airline. When creating tickets, you will probably want the same airline from both the ticket and the flight, so you may pass an

  114. airline instance to the recycle method. You may find the recycle method particularly useful if you have models belonging to a common user or team. Ticket Factory, recycle airlines, create. Testing. Getting started. Introduction. Laravel is built with testing in mind. In fact, support for testing with PEST and PHP unit is included out of the box and a phpunit.xml

  115. is already set up for your application. The framework also shifts with convenient helper methods that allow you to expressively test your applications. By default, your application's test directory contains two directories, feature and unit. Unit tests are tests that focus on a very small isolated portion of your code. In fact, most unit tests probably focus on a single method. Tests within your unit test directory do not boot your learnable application and therefore are unable to access your application's database or other framework services. Feature requests,

  116. feature tests may test the larger portion of your code, including how several objects interact with each other or even a full HTTP request to a JSON endpoint. Generally, most of your tests should be feature tests. These types of tests provide the most confidence that your system as a whole is functioning as intended. An example test.php file is provided in both the feature and unit directories after installing a new Laravel application, execute the vendor bin test or vendor bin php unit or php

  117. artisan test commands to run your tests. Environment. When running tests, Laravel will automatically set set the configuration environment to testing because of the environment variables defined in the phpUnit.xml. In addition, you may create a .env.testing file in the root of your project. This file will be used instead of the .env file when running PEST and phpUnit tests or executing artisan commands with the env equals testing option.

  118. Create a new test class using the makeTestArtisan command. By default, tests will be placed in the test features directory. As mentioned previously, once you've written tests, you may run them using PEST or PHP unit. In addition to the PEST or PHP unit commands, you may use the test artisan command to run your tests. The artisan test runner provides verbose test reports in order to ease development and debugging.

  119. Any arguments that can be passed to PEST or your PHP unit commands may also be passed to the artisan test command. By default, Laravel and PEST PHPUnit execute your test sequentially within a single process. However, you may greatly reduce the amount of time it takes to run your test by running tests simultaneously across multiple processes. As long as you've configured a primary database connection, Laravel automatically handles

  120. creating and migrating a test database for each parallel process that is running your tests. Occasionally, you may need to prepare certain resources used by your application's tests so that they may be safely used by multiple test processes. Using the parallel testing facade, you may specify code to be executed on the set up and tear down of a process or test case. The given closures receive the token and test case variables that contain

  121. the process token and the current test case respectively. So public function boot, parallel testing, set up process, set up test case, tear down test case, tear down process. I'll take a quick break.

  122. Thank you.

  123. so

  124. I'm going to put a little bit of a knife in the middle.

  125. I'm going to go ahead and put it in the middle of the room.

  126. Thank you.

  127. I'm going to make a little bit more of a little bit more.

  128. Thank you.

  129. I'm going to go ahead and put it in the middle of the room.

  130. Thank you.

  131. so

  132. Thank you.

  133. so

  134. Thank you.

  135. Alright, home stretch of testing.

  136. Pages. Sometimes tests require several complicated actions to be performed in sequence. This can make your tests harder to read and understand. Dusk pages allow you to define expressive actions that may then be performed on a given page via a single method. Pages also allow you to define shortcuts to common selectors for your application or for a single page. Generating pages. To generate a page object, execute the Dusk Page Artisan command. All

  137. All page objects will be placed in your application's tests browser pages directory. PHP Artisan Dusk page login. By default pages have three methods, URL, assert, and elements. We will discuss the URL and assert methods now. The elements method will be discussed in more detail below. The URL method should return the path of the URL that represents the page. Dusk will use this URL when navigating to the page in the browser. So public function URL return login. The assert method.

  138. method may make any assertions necessary to verify that the browser is actually on the given page. It is not actually necessary to place anything within this method, however you are free to make these assertions if you wish. These assertions will be run automatically when navigating to the page. Navigating to pages. Once the page has been defined, you may navigate to it using the visit method. Sometimes you may already be on a given page and need to load the page selectors and methods into the current test context. This is common when pressing a button

  139. and being redirected to a given page without explicitly navigating to it. In this situation, you may use the on method to load the page. Browser visit dashboard, so click link, create playlist on new create playlist. Shorthand selectors. The elements method within page classes allows you to define quick, easy to remember shortcuts for any CSS selector on your page. For example, let's define a shortcut for the email input field of the application's login page. Once the shortcut

  140. has been defined, you may use the shorthand selector anywhere you would typically use a full CSS selector. Global shorthand selectors. After installing Dusk, a base page class will be placed in your test browser pages directory. This class contains a site elements method, which may be used to define global shorthand selectors. This should be available on every

  141. page throughout your application. Page methods. In addition to the default methods defined on pages, you may define additional methods which may be used throughout your tests. For example, let's imagine we are building a music management application. A common action for

  142. one page of the application might be to create a playlist. Instead of rewriting the logic to create a playlist in each test, you may define a create playlist method on a page class. Once the method has been defined, you may use it within any test that utilizes the page. The browser instance will automatically pass the first argument to custom page methods. Generating components. To generate a component, execute the dusk component artisan command.

  143. components are placed in the tests browser components directory. As shown above, a date picker is an example of a component that might exist throughout your application on a variety of pages. It can become cumbersome to manually write the browser extension automatic, the browser automation logic to select a date and dozens of tests throughout your test suite. Instead, we can define a desk component to represent the date picker, allowing us to

  144. encapsulate that log in with that logic within the component. This is a full kind of like a dust component code block using components. Once the component has been redefined, we can easily select a date within the date picker from any test. And if the logic necessary to select a date changes, we only need to update the component itself. Continuous integration.

  145. To run tests on Heroku CI, add the following Google Chrome build pack and script to your Heroku app.json file. To run your test tests on Travis CI, use the following Travis.yaml configuration. Since Travis CI is not a graphical environment, we will need to take some extra steps in order to launch a Chrome browser. In addition, we will use PHP Artisan serve to launch PHP's built-in web server. GitHub Actions.

  146. GitHub's, if you're using GitHub Actions to run your desk test, you may use the following configuration file as a starting point. Like Travis CI, we will use PHP Artisan's serve command to launch PHP's built-in web server. Using Chipper CI to run your desk test, you may use the following configuration file as a starting point. We will use PHP's built-in web server to run Laravel as we listen for your requests. To learn more about running dust tests on Chipper CI, including how to use databases,

  147. consult the official Chipper CI documentation. Database Testing Introduction. Laravel provides a variety of helpful tools and assertions to make it easier to test your database-driven applications. In addition, Laravel Model Factories and CEDRs make it painless to create test database records using your application eloquent models and relationships. We'll discuss all these powerful features in the following documentation. Resetting the

  148. database after each test. Before proceeding much further, let's discuss how to reset your database after each of your tests so that your data from a previous test does not interfere with subsequent tests. Laravel's included refresh database trait will take care of this for you. Simply use this trait on your test class. So use refresh database, uses refresh

  149. database class. The illuminate testing refresh database trait does not migrate your database if your schema is up to date. Instead it will only execute the test within a database transaction. Therefore any records added to the database by your test cases that do not use this trait may still exist in the database. If you would like to totally reset the database you may

  150. use the Illuminate Foundation Testing Database Migrations or Foundation Testing Database Truncation traits instead. However, both of these options are significantly slower than the Refresh Database trait. When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a set of default attributes for each of your eloquent models using model factories. To learn more about

  151. creating and utilizing model factories to create models, please consult the complete model factory documentation. Once you have defined a model factory, you may utilize the factory from within your test to create models. Running seeders. If you would like to use database seeders to populate your database during a future test, you may invoke the seed method. By default, the seed method will execute

  152. database seeder which should execute all of your other seeders. Alternatively, you pass a specific seeder class name to the seed method. Alternatively, you may also instruct Laravel to automatically seed the database before each test that uses the refresh database trait. You may accomplish this by defining a seed property on your base test class. When the seed property is true, the test will run the

  153. database seeders database seeder class before each test that uses the refresh database trait. However, you may specify specific seeder that should be executed by defining a seeder property on your test class. Available assertions. Blair will provide several database assertions for your PEST or PHP unit feature tests. We'll discuss each of these assertions below. Assert that a table in the database contains the given number of records. Assert database has that the table in the database contains records matching the given

  154. key value query constraints. Assert database missing, that a table in the database does not contain records matching the given key value query constraints. Assert soft deleted, method may be used to assert a given eloquent model has been soft deleted. Assert not soft deleted method may be used to assert a given eloquent model hasn't been soft deleted. Assert model exists, asserts that a model, a given model exists in the database. Assert model

  155. missing. Assert that a given model does not exist in the database. Expects database query count. The expects database query count method may be invoked at the beginning of your test to specify the total number of database queries that you expect to be running during the test. If the actual number of executed queries does not exactly match this expectation, the test will fail. Mocking. Introduction. When testing Laravel applications, you may wish to mock certain

  156. aspects of your application so that they are not actually executed during a given test. For example, when testing a controller that dispatches an event, you may wish to mock the event listener so that they are not actually executed during the test. This allows you to only test the controller's HTTP response without worrying about the execution of the event listener since the event listeners can be tested in their own test case. Laravel provides helpful methods for mocking events, jobs, and other facades out of the box.

  157. These helper primarily provide a convenience layer over mockery so you don't have to manually make complicated mockery method calls. When mocking an object that is going to be injected into your application via Laravel service container, you will need to bind your mocked instance into the container as an instance binding. This will instruct the container to use your mocked instance of the object instead of constructing the object itself. In order to make this more convenient, you may use the mock method that is provided by

  158. by Laravel's base test case class. For example, the following example is equivalent to the example above. You may use the partial mock method when you only need to mock a few methods of an object. The methods that are not mocked will be executed normally when called. So mock this partial mock service class function, mock interface, mock should receive process once. Similarly, if you want to spy on an object, Laravel's base test class offers a spy method

  159. as a convenient wrapper around the mockery spy method. Spies are similar to mocks. However, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed. So spy this spy service class, or spy should have received process. Mocking facades. Unlike traditional static method calls, facades include real-time facades, maybe mocked. This provides a great advantage

  160. traditional static methods and grants you the same testing, it's the same testability that you would want if you were using traditional dependency injection. When testing, you may often want to mock a call to a Laravel facade that occurs in one of your controllers. For example, consider the following controller action. So in your controller, public function index, index value cache git key. We can mock the call to the cache facade by using the should

  161. receive method, which will return an instance of a mockery mock. Since facades are actually resolved and managed by the layer of a service container, they have much more testability than a typical static class. For example, let's mock our call to the cache facades git method. So test git index function cache should receive git once with key and return response this git users. Facade Spies.

  162. If you would like to spy on a facade, you may call the spy method on the corresponding facade. Spies are similar to mocks. However, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the mock is executed. So use Illuminate support facades, cache. Test values have to be stored in cache function, cache spy, response, this, and get the search

  163. status. Interacting with time. When testing, you may occasionally need to modify the time returned by helper, such as now or carbon now. Thankfully, Laravel's base feature test class includes helpers that allow you to manipulate current time. So test this travel five milliseconds, this travel five seconds, travel into the past with negative 5, travel to an explicit time, so now sub-hours return back to the present

  164. time. You may also provide a closure to the various time travel methods. The closure will be invoked with time frozen at the specified time. Once the closure has executed, time will resume as normal. The freeze time method may be used to freeze the current time. Similarly, the freeze second method will freeze the current time but at the start of the current second.

  165. So this freeze time, this freeze second. As you would expect, all of the methods discussed above are primarily useful for testing time sensitive application behavior, such as locking inactive posts on a discussion forum. For example, use app models thread, test, form threads lock after one week of inactivity, factory create this travel one week. Expect to be true. This assert true thread is locked by an activity."

  166. That concludes the Laravel documentation for everything that comes out of the box. We didn't do any of the packages documentation. Mostly because that's, it's not something that comes, like their their pat their their about first party package so i would say that those are

  167. second documentation but i'm also tired and my voice hurts but um i learned a lot and uh overall the documentation is something that i think you should read at least once straight through probably not in one sitting but you should probably at least read all the things that i

  168. just read tonight because I did learn a lot. One of the things I think that Laravel does that you might not know if you don't read the documentation is there's so many things that it makes happen for you behind the scenes, but the documentation shows this is the reason why all of this magic happens.

  169. Even as simple as the ORM where you have the DB facade that kind of sets up, hey, here's how to interact with the DB, but you also have an ORM with an Eloquent to make even that part easier. And then a lot of it is just making a lot of magic happen within the documentation. There's a lot of terse.

  170. That's one word that I love seeing a lot in the documentation. There's a lot of... Basically, I understood PHP a little bit more after reading the documentation because you learn the phrasing for specific things. What is a dependency injection? What is a function and a callback? What is an attribute versus a method?

  171. But yeah, overall, I enjoyed it. I probably won't do it again anytime soon, at least all in one sitting. But you should read the documentation. You should read Laravel's documentation specifically. And hopefully you all have a good night, good morning, good wherever you are in the world. I'll be going to get some sleep for a little bit. So, see you soon.

just you here