YouTubestream· May 27, 2024· 1:34:34· 572 views on YouTube
React at a moment you like. The best moments light up here.
[Music]
for [Music]
for [Music]
all right let's get back into it
so eloquent o RM introduction laravel includes eloquent and object relational mater that makes it enjoyable to interact 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 live in the app slm
models directory and extend the aluminate 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- m option you may generate various other types of classes when generating a models such as factories seedar policies controllers and form requests in addition these options may
be combined to create multiple classes at once
so generate a model and a flight Factory class flight Cedar class flight controller class you can generate resource class and form request classes a flight policy class you can generate uh migration Factory Cedar and controller uh model migration Factory Cedar 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 convenient overview of all the models 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 key conventions so class F extense 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 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 flight's table while an air traffic controller model um would store records in a air traffic controllers table if your model's corresponding
database table does not fit this convention you may manually specify the model's table Name by defining a table property on the model so 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 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 the eloquent will automatically cast the primary key to an integer if you wish 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 property primary Keys eloquent primary uh requires each model to have at least one uniquely identifying ID that can serve as its primary key key composite primary keys are not supported by eloquent models however you are free to add additional multicolumn and unique indexes to your database tables in addition to the table's uniquely identifying primary key uu ID and UL IDs instead of using
Auto incrementing integers as your eloquent model's primary Keys you may choose to use U IDs instead uu IDs are universally unique alpha numeric identifiers that are 36 characters long so if you would like to use a model to use a a if you would like a model to use a uid key instead of an auto auto incrementing integer key you may use the eloquent concerns has uuid's trait on the model of course you should ensure
that the model has a uu ID equivalent primary key column has you use has uu IDs by default the has uu IDs trait will generate ordered uu IDs for your models these uu IDs are more efficient for indexed database storage because they can be sorted uh sorted Lex lexic graphically you can override The UU ID generation
process for a given model by defining a new unique ID method on the model in addition you may specify which column should receive uu IDs by defining a unique IDs method on the model if you wish you may choose to utilize UL IDs instead of U IDs UL IDs are similar to UU IDs however they are only 26 characters in length like ordered U uu IDs UL IDs are lexographic
lexicographically sortable but for efficient database indexing to utilize UL IDs you should use the concerns has IDs trait on your model you should also ensure that the model has a ulid equivalent primary key column time stamps by default eloquent EXP 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 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 a or
Json if you need to customize the names of the columns used to store the timestamps you may Define created at and updated at constants on your model if you would like to perform model operations without the model having its updated at timestamp modified you may operate on the model with an 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 values 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 larel offers several
methods that allow you to configure eloquence behavior and strictness in a variety 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 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 pres 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 larel to throw an exception when attempting to fill an unfillable attri attribute by invoking the prevent silently discarding attributes method this can help prevent unexpected errors during local development when attempting to set an attribute that has not been added to the model's fillable array once you have created a model and it's 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 all method will retrieve all of the records from the models Associated database table the eloquent all 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 effective 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 lels based support collection class which provides a variety of helpful methods for interacting with data collection for example the reject 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 lille's base collection class the eloquent collection class provides a few extra methods that are specifically intended for interacting with collections of eloquin models since all of lel's collections Implement php's iterable interfaces you may Loop over collections as if they were an array for each flights say flight Echo flight name chunking results your application may run out of memory if you attempt to load tens of thousands of eloquent re records
via the all or git methods instead of using these methods the chunk method may be used to process large numbers of models more efficiently the chunk 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 of time the chunk method will provide significantly reduced memory usage when working with a large number of models the first argument passed to the chunk method is the number of Records you wish to receive per chunk
the closure passes 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 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 con 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 corly into a call back as is the lazy method returns a flattened uh lazy collection of eloquent models which lets you interact with the results as a single stream if you are filtering the results of the lazy method
based on a Col 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 to the lazy method the cursor 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 this functionalities for each flight wear 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 layer able 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 in memory at a time it will still eventually run out of memory this is due to php's 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 arrived at column which indicates when the flight arrived at the
destination using the subquery functionality available to the query Builder select and AD 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 to sort all destinations based on where the 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 wear methods instead of returning a collection of models these methods turn a single model instance sometimes you may wish to perform some other action if no results are found the find or and first or 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 find or fail and first or fail methods will retrieve the first result of the query however if no result is
found and illuminated 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 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 eloquent models uh you may also use the
count sum Max and other other aggregate methods provided by the LEL query Builder as you might expect these methods return a scalar value instead of an eloquent model instance inserts oh 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 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 requests 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 when the save method is called so there's 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 assignment vulnerabilities by default the save method may also be used to update mod 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 at Tim stamp will automatically be updated so there is no need to manually set its
values 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 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 examining attribute changes
eloquent provides the is dirty is clean and was changed methods to examine the internal state of your model and determine how its attributes have changed from when the model was originally retrieved the is dirty method determines if an if any of the model's attributes have been changed since the model was retrieved you may pass a specific aim of an array or attributes to the is dirty method to determine if any of the attributes are dirty the is clean method will determine if an attribute has remained unchanged since
the model was retrieved this method also accepts an optional attribute uh argument the was changed changed method determines if any attributes were changed when the model was last saved within the current request life cycle if needed you may pass an attribute name to see if a particular attribute was changed the get original 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 of particular attributes Mass assignment 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 method however before using the create method you'll 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 a mass assignment vulnerability occurs when a user passes an unexpected hdp request field and that field changes the column in your database that you did not expect for example 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 here 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 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 for security laral 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 unguard your model you should take special care to always handcraft the arrays passed to
eloquence 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 however during local de development it can lead to confusion as to why model changes are not taking effect if you wish you may instruct Lille 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 applications app service provider class upsets eloquence upsert method may be used to update or create records in a single Atomic operation 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 you may call the truncate method to delete all the models Associated database records the trunc a operation will also reset any auto incrementing IDs on the models Associated table in the example above flight trunk G 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 their single primary key the destroy method will accept multiple primary Keys an array of primary keys 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 is 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 attribute set on the model indicated the T 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 should also add the deleted at column to your database table the LEL 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 set to will be set to the current date and time however the model's database record will be left in the table when querying a model that
uses soft Elites the time the soft deleted models will automatically be uh excluded from all query results to determine if a given model instance has been soft deleted you may use the trashed [Applause] method restoring soft deleted models sometimes you may wish to undelete a softw deleted deleted model to restore a soft 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 and 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 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 excluded from query results however you may Force the leaded models to be included in the queries results by calling the with trashed method on the query so flight with trashed where count ID git the with trashed method may also be called when building a relationship
query retrieving only softed lead 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 uh eloquent prunable or eloquent Mass prunable trait to the models you would like to Peri 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 that are no longer
needed so public function prunable return static where created at is less than or equal to now with some month when Market models 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 prunable model you should schedule the model prun Artisan command in your applications routes console PHP file you are free to choose the appropriate intervie interval at which this command should [Applause] run behind the scenes the model prune command will automatically detect prunable models within your applications at models directory if your models are
in a different location you may use the-- 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-- 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 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 ret reved before deletion thus making uh thus making the pring process much more
efficient once the relationship is defined you may access the user's role using the rolles 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 condition conditions onto the query defining the inverse of a relationship to define the inverse of a many to many relationship you should Define a method on a 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 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 where pivot not n where pivot between where pivot null and where pivot not null methods when defining the relationship ordering queries via intermediate table columns you can order the query results returned by belongs to many relationship queries using the order by pivot method in the following example we retrieve all the latest badges for the user so this belongs to many badge class where rank is gold or
ordered 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 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 models should extend the relations pivot class while custom polymorphic
many to many pivot models should extend the relations morph pivot class for example we may defin a role model which uses a custom role user pivot model why when defining the role user model you should extend the uh eloquent relations pivot class custom pivot models and incrementing IDs if you have defined a many to many relationship it 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: one polymorphic a one:1 polymorphic relationship is similar to a typical
one:1 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 onetoone 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 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 examine 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 for example to retrieve the image for a post we can access the
image Dynamic relationship property that's 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 2 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 depending on which type of model owns the [Applause] image constraining eager loads sometimes you may wish to eager load a relationship but also specify additional query relationship 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 constraining eager loading of morph 2 relationships you may if you are eager loading a morph 2 relationship eloquent will run multiple queries to fetch each type of rela model you may add additional constraints to each of these queries using the morph 2 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 been retrieved for example this may be useful if you need to dynamically decide whether to load related models nested eager loading and morph 2 if you would like to load a morph 2 relationship as well as nesa 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 2 relationship as its first
argument and an array of model relationship pairs as its second argument as previously discussed eager loading relationships can offer uh often provide significant performance benefits to your application therefore if you would like you may instruct a Lille to always prevent the lazy loading of relationships Parent Time stamps when a model defines a belongs to or belongs to many relationship to another model such as a comment which belongs to a post it belongs it is sometimes helpful to update the parent timestamp when the
child model is updated for example when a comment model is updated uh you may want to automatically touch the updated 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 one model result will return instances of the illuminate eloquent collection class including results retrieved by the git method or accessed via a relationship the eloquent collection object extends lel'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 larel collection documentation to learn all
about these helpful methods all collections 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 producer 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 basic
larable collection object 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 a pend meth to be used to int uh
indicate an attribute should be appended for every model in the collection contains diff accept find freshh intersect load load missing model Keys make visible make Hidden only set visible set hidden two 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 once you have defined a new collection method you will receive an instance of your custom collection anytime eloquent would normally return an uh 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 eloquent serialization this is out of order okay there we go when building apis using larl you will 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 two arrays to convert a model and its loaded relationships to an array you should use the two array method this method is recursive so all attributes and all relations including the relations of relations will be converted to a arrays to convert a model to Json you should use the two Json method like two array the Json method is recursive so all attributes and relations will be converted to Json it may also specify any Json encoding options that are supported by [Applause]
PHP relationships when an eloquent model is converted to Json its loaded relationships 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 models 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 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 property of your model note that attribute names are typically referenced using their snake case or serialized representation even though the accessor PHP method is defined using camel case once the attribute has been added to the appens list it will be included uded in both the models array and Json representations attributes in the append
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 using the append method or you may use the set appens 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 serialized date method this method does not affect how your dates 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 models cast declarations eloquent factories introduction when testing your
application or seating your database you may need to insert a few records into your database instead of manually specifying the value of each column larvo allows you to define a set of Def 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 usera factory. PHP file in your application this factories include with all new L applications and contains the following Factory definition
public function definition return name fake name email fake unique safe email email verify that now password remember token as you can see in their most basic form factories are classes that extend lel'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 this should be applied when creating a model using the factory via the fake helper uh factories have access to the faker PHP Library which allows you to conveniently generate various kinds of random data for testing and seating you can change your application's Faker local by updating the faker loal option in your config app.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 your provided to your models by the has Factory trait in order to instantiate a factory instance for that model State manipulation uh methods allow you to Define discrete modifications that can be applied to your model factories in any combination for example your database factories 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 lille's 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 all
right Factory callbacks are registered using the after making and after creating methods and allow you to perform additional tasks tasks after making or creating a model you should register these callbacks by finding 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 with while the rest of the attributes remain set to their default values as specified by the factor 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 each created user using magic methods for convenience you may use lel's magic factory relationship methods to Define belongs to relationships for example the following example will use uh 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 Archer create polymorphic relationships may also be created using factories polymorphic morph manyu relationships are created in the same way as typical has manyu relationships for example if an app models post model has a morph menu relationship with an app models comment
model morph to relationships magic methods may not be used to create morph two relationships instead the four method must be used directly and the name of the relationship must be explicitly provided for example imagine that the comment model has a commentable method that defines a morph 2 relationship in this situation you may create three comments that belong to a single post by using the four 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 to create to polymorphic many to many relationships to define a relationship with your within your model Factory you will assign typically assign a new Factory instance to the foreign key of their relationship this is normally done for the inverse relationship 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 um so return user ID user Factory title fake title content fake paragraph 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 theet 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 for both the ticket and the flight so you may pass an 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 uh ticket Factory recycle Airlines cre testing getting started introduction
larel 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 is already set up for your application the framework also ships 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 Lal application and therefore are unable to access your application's database or other framework Services feature requests feature tests May test a larger portion of your code including how several objects interact with each other or even a full HTP request to ajon on 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 Lille application execute the vendor bin pest or vendor bin PHP unit or PHP Artisan test commands to run your tests environment when running tests laral will automatically set the configuration environment to testing because of the Environ variables defined in the phpunit.xml in addition you may create aemv do
testing file in the root of your project this file will be used instead of the DMV file when running Pest and PHP unit tests or executing Artisan commands with the equals testing option create a new test class use the make test Artisan command by default test 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 EAS development and debugging any arguments that can be passed to pest or PHP unit commands may also be passed to The Artisan test command by default Lille and pest PHP
unit 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 Lille automatically handles creating and migrating a test test database for each parallel process that is running your tests occasionally you may need to prepare certain resources used by your application test 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 setup and tear down of a process or test case the given closures receive the token and test case variables that contain 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 take a quick break
[Music]
all right home stretch of testing 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 page objects will be placed in your applications 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 the assert method may play may make in 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 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 and being redirected to a given page with 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 applications login page once the shortcut 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 page throughout your application page methods I think we're in the one stretch this much left 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 one page of the application uh 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 P the page the browser instance will automatic pass the first argument to custom page methods generating components to generate a component execute the dusk
component Artis command new 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 dusk component to represent the DAT picker
allowing us to encapsulate that login with that logic within the component um this is a full kind of like uh 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 and date changes we only need to update the component itself
continuous integration uh to run tests on Heroku CI add the following Google Chrome build pack and script to your Heroku app. Json file to run your dust test on Travis C use the following travis. yo configuration since Travis CI is non 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 phps built-in web server GitHub actions github's we you're yearsing GitHub actions to run your dust test you may use the following configuration file as a starting point like Travis CI we will use PHP Artis serve command to launch php's built-in web server using chipper C 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 Lille as we
listen for your requests to learn more about running dust tests on chipper C including how to use databases consult the official chipper C mentation database testing introduction larabel provides a variety of helpful tools and assertions to make it easier to test your database driven applications in addition laral model factories and Cedars 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 database after each test before proceeding much further let's discuss how to reset your database after after each of your tests so that D your data from a previous test does not interfere with subsequent tests laravel's included uh refresh database trait will take care of this for you simply use this trait on your test class
so uh use refresh database uses refresh 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 trans action 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 uh to if you would
like to totally reset the database you may 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 specif Define the value of each column when you create this test data laral allows you to define a set of default attributes for
each of your eloquent models using model factories to learn more about creating and utilizing model factories to create models please consult the complete model Factory documentation once youve defined a a model Factory you may utilize the factory from within your test to create models running seeders if you would like to use database database Cedar to populate uh your database during a feature test you may invoke the seed
method by default the seed method will execute the database Cedar which should execute all of your other seedar alternatively you pass a specific Cedar class name to the seed method alternatively you may also instruct Layel to automatically see 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 database Cedar's database Cedar class before each test that uses the refresh database trait however you may specify specific Cedar that should be executed by defining a cedar property on your test class available assertions Blair will provide several database assertions for your pest or PHP unit future tests we'll discuss each of these assertions below assert that a table in the database
contains the given number of Records a certaint database has that the table in the database contains records matching the given 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 a certain model exists
asserts that a Model A given model exists in the database assert model missing assert that a given model does not exist in the dat 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 ma this match this expectation the tests will fail
mocking introduction when testing laral applications you may wish to mock certain 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 they are not actually executed during the test this allows you to only test the controllers HTTP response without worrying about the execution of the event listeners 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 these helper primarily provide a convenience layer over mockery so you do not have to manually make compated mockery method calls when mocking an object this is going that is going to be injected into your application via lville 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 lille's based 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 are not mocked will be executed normally when called so mock this partial mock service class function mock
interface mock should receive process wants similarly if you want to spy on an object lille's base test class offers a spy method as a convenient wrapper around the mockery spy method spies are similar to mocks however spies record 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 uh method calls facades include realtime facades may be mocked this provides a great advantage over traditional static methods and grants you the same uh testing get you the same testability that you would want if you are using traditional dependency injection when testing you may often want to mock a call to a larvo side that occurs in one
of your controllers for example consider the following controller action uh so in your controller public function index value cach G key we can mock the call to the cash facade by using the should receive method which will return an instance of a mockery mock since facades are actually resolved and managed by the layer service container they have much more testability than a typical static class for example let's mock our call to the
cash facad git method so test G index fun cash should receive g once with key and return response this git users facade spies if you would like to spy on a facade you may call the Spy method on the corresponding 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 uh so use illuminate support facades cach uh test values are to be stored in cach function cash spy response this get search status interacting with time when testing you may occasionally need to modify the time returned by helpers such
as now or carbon now thankfully lille's based future test class includes helpers that allow you to manipulate the current time so test this travel 5 milliseconds this travel 5 Seconds uh travel into the past with NE five travel to an explicit time so now Sub hours return back to the present time you may also provide a closure to the various time travel methods the
closure will be invoked with Time Frozen at the spec spe 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 so free this freeze time this freeze second as you would expect all the methods discussed above are primarily useful for testing
time sensitive application Behavior such as locking inactive posts on a discussion forum uh for example use app models thread test Forum threads after one week of inactivity thread Factory create this travel one week expect to be true this is search true thread is locked by an
activity that concludes the larel documentation um for everything that comes out of the box we didn't do any of the uh packages documentation uh mostly because that's it's not something that comes like they're they pack they larel first party package so I would say that those are second documentation but I'm also tired
in my voice HTS 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 just read tonight because um I I did I did learn a lot one of the things I think that larel
does that you might not know if you don't read the documentation is there's so many things that it uh makes happen for you behind the scenes but theot documentation shows this is the reason why all of this magic happens even as simple as the OM 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 OM within eloquent to make even that part easier um and then a lot of it is just making a lot of magic happen within the documentation there's a lot of uh tur that's one word that I love seeing a lot in the
documentation there's a lot of um uh basically I I understood PHP a little bit more after reading the documentation because you you learn the phrasing for specific things like what what is a dependency injection uh what is you know a function and a call back what is an attribute versus you know a a
a a a method um but yeah overall I enjoyed it uh I probably won't do it again anytime soon at least all in one sitting but you should read the documentation you should read lille's documentation specifically and hopefully you all have a good night good morning good wherever you are in the world um I'll be going to get some sleep for a little bit so see you soon