This text serves as a comprehensive guide to understanding and building web applications using the Laravel PHP framework. It explores key aspects such as project structure, request lifecycles, configuration, routing, debugging, controllers, views with Blade templating, database migrations, Eloquent ORM, relationships, factories, and seeders. The material provides hands-on examples and step-by-step instructions. Practical demonstrations of common tasks such as creating routes, controllers, models, database operations, component creation, and pagination are included. The goal is to equip developers with the knowledge and skills to create dynamic and maintainable web applications with Laravel.
Laravel Project Deep Dive Study Guide
Quiz
- What is the purpose of the public folder in a Laravel project? The public folder is the single web-accessible directory. It contains the index.php file, which serves as the entry point for all requests to the application, and other assets like CSS, JavaScript, and images.
- Why is it important not to commit the .env file to a Git repository? The .env file contains sensitive information such as database credentials, API keys, and other configuration details. Committing it could expose this information to unauthorized users.
- Explain the Laravel request lifecycle. The request starts at public/index.php, which loads the autoloader and bootstraps the application. The request is then passed to the router, which identifies and executes the appropriate controller action, potentially involving middleware and rendering views, before sending a response back to the user.
- How can you customize configuration options that are not available in the .env file? Configuration files are located in the config folder. If a specific option is not available in the .env file, you can modify the corresponding configuration file within the config folder or use the php artisan config:publish command to make additional configuration files available.
- What is the difference between the dump() and dd() debugging functions in Laravel? The dump() function prints variable information without halting code execution, allowing the script to continue. The dd() function (dump and die) prints variable information and immediately stops the execution of the script.
- List the six primary HTTP request methods and their typical uses.GET: Retrieve information.
- POST: Create new data.
- PUT: Update existing data (replaces the entire resource).
- PATCH: Update existing data (partially modifies the resource).
- DELETE: Delete data.
- OPTIONS: Retrieve communication options for a resource.
- How do you define a route with a required parameter in Laravel? You define a route with a required parameter by enclosing the parameter name within curly braces in the URI (/product/{id}). The parameter value is then passed as an argument to the route’s associated function.
- Explain the purpose of the where method when defining routes in Laravel. The where method is used to add constraints to route parameters, ensuring that they match a specific pattern, like being numeric (whereNumber(‘id’)) or containing only alphabetic characters (whereAlpha(‘username’)).
- What are Blade directives, and how do they simplify template development? Blade directives are special keywords prefixed with @ symbols, providing a shorthand way to perform common tasks in Blade templates, such as conditional statements, loops, and including subviews. They are compiled into plain PHP code.
- Explain the purpose of route naming in Laravel, and how do you generate URLs using named routes? Route naming allows you to refer to routes by their name rather than their URI. You can generate URLs using the route() helper function, passing the route’s name as an argument (route(‘routeName’)).
Quiz Answer Key
- The public folder is the single web-accessible directory. It contains the index.php file, which serves as the entry point for all requests to the application, and other assets like CSS, JavaScript, and images.
- The .env file contains sensitive information such as database credentials, API keys, and other configuration details. Committing it could expose this information to unauthorized users.
- The request starts at public/index.php, which loads the autoloader and bootstraps the application. The request is then passed to the router, which identifies and executes the appropriate controller action, potentially involving middleware and rendering views, before sending a response back to the user.
- Configuration files are located in the config folder. If a specific option is not available in the .env file, you can modify the corresponding configuration file within the config folder or use the php artisan config:publish command to make additional configuration files available.
- The dump() function prints variable information without halting code execution, allowing the script to continue. The dd() function (dump and die) prints variable information and immediately stops the execution of the script.
- GET: Retrieve information.
- POST: Create new data.
- PUT: Update existing data (replaces the entire resource).
- PATCH: Update existing data (partially modifies the resource).
- DELETE: Delete data.
- OPTIONS: Retrieve communication options for a resource.
- You define a route with a required parameter by enclosing the parameter name within curly braces in the URI (/product/{id}). The parameter value is then passed as an argument to the route’s associated function.
- The where method is used to add constraints to route parameters, ensuring that they match a specific pattern, like being numeric (whereNumber(‘id’)) or containing only alphabetic characters (whereAlpha(‘username’)).
- Blade directives are special keywords prefixed with @ symbols, providing a shorthand way to perform common tasks in Blade templates, such as conditional statements, loops, and including subviews. They are compiled into plain PHP code.
- Route naming allows you to refer to routes by their name rather than their URI. You can generate URLs using the route() helper function, passing the route’s name as an argument (route(‘routeName’)).
Essay Questions
- Discuss the significance of the .env file in Laravel development, detailing its role in managing application configuration and the security implications of mishandling it. Explain best practices for managing environment variables in a collaborative development environment.
- Describe the Laravel request lifecycle in detail, from the initial request to the final response. Explain the roles of key components such as the router, middleware, controllers, and views, and how they interact to process a request.
- Explain how the Laravel Blade templating engine facilitates the creation of dynamic and reusable user interfaces. Discuss the advantages of using Blade directives for common tasks like conditional rendering, looping, and including subviews, and provide examples of how these directives simplify template development.
- Discuss the role and implementation of model factories and seeders in Laravel. Explain how they are used to generate realistic data for testing and development, and provide a detailed example of creating a factory with relationships to other models.
- Describe how Laravel’s Eloquent ORM simplifies database interactions and management. Discuss different types of relationships including one-to-one, one-to-many, and many-to-many. Explain best practices for working with Eloquent models, including defining relationships, using scopes, and performing CRUD operations efficiently.
Glossary of Key Terms
- Artisan: Laravel’s command-line interface (CLI) used for various development tasks like generating files, running migrations, and clearing cache.
- Blade: Laravel’s templating engine that allows developers to use directives and simple syntax to create dynamic views.
- Composer: A dependency manager for PHP, used to manage project dependencies like Laravel packages.
- .env file: A configuration file in Laravel that stores environment-specific settings such as database credentials and API keys.
- Eloquent: Laravel’s ORM (Object-Relational Mapper) that provides a simple and enjoyable way to interact with databases.
- Facade: A static interface to classes available in the application’s service container, providing a convenient way to access Laravel’s features.
- Factory: A class that generates fake data for seeding databases or creating test data.
- Migration: A PHP file that defines database table schema changes, allowing for easy database version control.
- Middleware: Code that executes before or after a request is handled by the application, used for tasks like authentication, logging, and request modification.
- ORM (Object-Relational Mapper): A technique that lets you query and manipulate data from a database using an object-oriented paradigm.
- Route: A definition in Laravel that maps a specific URI to a controller action or closure.
- Seeder: A class that populates the database with initial data using model factories or custom data.
- Service Container: A powerful tool for managing class dependencies and performing dependency injection in Laravel.
- Trait: A mechanism for code reuse in PHP, allowing developers to inject methods and properties into classes without inheritance.
- View: A PHP file containing HTML and Blade directives used to display data in a Laravel application.
Laravel Fundamentals: A Concise Overview
Okay, here’s a detailed briefing document summarizing the key themes and ideas from the provided text excerpt.
Briefing Document: Laravel Fundamentals
Overview:
This document summarizes key aspects of Laravel development as described in the provided text. It covers project structure, routing, debugging, request lifecycle, configuration, database interaction, ORM (Eloquent), templating (Blade), and response generation. The text serves as a practical guide, demonstrating code examples and artisan commands alongside explanations.
I. Project Structure & Core Concepts
- Directory Structure: The document outlines the standard Laravel project directory structure.
- app: Contains the core application logic, including controllers, models, etc. The text notes it can house user-uploaded files.
- bootstrap: Contains the app.php file, which bootstraps the application.
- config: Holds configuration files. “Most of the configuration options regarding LL is available in file.”
- database: Contains factories, migrations, and seeds for database management. “the database folder contains factories migrations and sits this will also contain database.sql file if your database driver is set to sq light.”
- public: The web-accessible directory, containing index.php (the entry point). “public folder is single web accessible folder index PHP right here is the entry script and the request starts from this index PHP.”
- resources: Contains assets like CSS, JavaScript, and views. Views are Blade templates.
- routes: Defines application routes (web, API, console). “RS folder contains the main rots for our application whether those are web based roads or console based roads.”
- storage: Stores generated files, user uploads, cached views, sessions, and logs.
- tests: Contains application tests.
- vendor: Contains third-party packages (Composer dependencies).
- Environment Configuration: .env file is crucial for environment-specific settings (database credentials, API keys, etc.). It should not be committed to Git. .env.example serves as a template. “enf do example file is the simple example file of you should never comit and push file in your git repository because it might contain sensitive data instead you’re going to comment and push. example file which should not contain sensitive data.”
II. Request Lifecycle
- The request starts at public/index.php.
- index.php includes vendor/autoload.php, then creates the application.
- Configuration files are loaded, and service providers are initiated. “The application itself loads configuration files and initiates service providers.”
- Service Providers: Prepare and configure the application (registering services, event listeners, middleware, and routes). “Service providers in Lal prepare and configure the application handling tasks like registering Services event listeners middle wear and Roots.”
- Router: Takes the request, finds the corresponding route, and executes the associated function. “the request is passed to router the router takes the request finds the corresponding function to execute and executes that.”
- Middleware: Can execute code before the request reaches the action and before the response is sent back to the user.
- Controller: Handles the request logic and can render a view. “the controller will send the response back to the user or if the middle we is registered the response will be passed to Middle we first and then returned to the user the controller action might also optionally render The View.”
III. Routing
- Basic Routing: Defines routes in routes/web.php.
- Example: Route::get(‘/about’, function () { return view(‘about’); });
- HTTP Methods: Laravel supports common HTTP methods: GET, POST, PUT, PATCH, DELETE, OPTIONS.
- Redirect Routes: Route::redirect(‘/old-url’, ‘/new-url’, 301); (301 is a permanent redirect). “we call the redirect method the first argument in this method is the rout to which we are going to listen to and the second argument is where the user should be redirected by default this redirect happens with status code 302 but we can also provide a third argument which is going to be the status code.”
- View Routes: Route::view(‘/contact’, ‘contact’, [‘phone’ => ‘123-456-7890’]); Directly renders a view. “the following code will listen to SL contact road and it will immediately try to render a view called Contact.”
- Route Parameters:Required: Route::get(‘/product/{id}’, function ($id) { … }); “Road parameters needs to be inside curly braces.”
- Optional: Route::get(‘/product/{category?}’, function ($category = null) { … }); “to make this optional we’re going to provide question mark before this closing curly brace.”
- Route Constraints: Restricting route parameters using where() method.
- Route::get(‘/product/{id}’, function ($id) { … })->where(‘id’, ‘[0-9]+’); id must be numeric. “we number accepts an argument and we’re going to provide a parameter so in this case I’m going to provide it and that’s it.”
- Route::get(‘/user/{username}’, function ($username) { … })->where(‘username’, ‘[a-zA-Z]+’); username must be alphabetic. “the following Road definition will match the following URLs whenever the ID only contains numeric values it is going to match but it is not going to match anything that does not contain numeric values now.”
- Custom Regex: Route::get(‘/user/{username}’, function ($username) { … })->where([‘lang’ => ‘[a-z]{2}’, ‘id’ => ‘[0-9]{4,}’]); More complex validation. “the length needs to be exactly two characters any symbol from A to Z and let’s use two character annotation however the ID needs to be digits let’s make sure it is a digit and also we need to make sure that it is at least four characters length.”
- Route Naming: Route::get(‘/about’, function () { … })->name(‘about’); Used for generating URLs. route(‘about’) will return the /about URL. “Whenever we access slab about URL we see the following content this is how we Define the TRU now let’s see what other request methods are available in LL there are totally six request methods available get post put patch delete and option get is mostly used to get the information post is to create the information put is to update the information and Patch is also for to update the information delete is to delete the information and options is to get more information about the specific root in LL.”
- Route Prefixes: Route::prefix(‘admin’)->group(function () { Route::get(‘/users’, function () { … }); }); Groups routes under a common prefix.
- Controller Namespaces: Route::controller(CarController::class)->group(function () { … }); Groups routes using the same controller.
- Single Action Controllers: Controllers with a single __invoke method. “to generate single action controller we’re going to execute the following commment PHP artisan make controller we’re going to provide the controller name like show car controller for example and then we’re going to provide a flag D- invocable.”
- Resource Controllers: Provide a standard way to handle CRUD operations for a resource. Route::resource(‘products’, ProductController::class); “In LEL a controller is a special type of controller that provides a convenient way to handle typical crowd operations for a resource such as a database table.”
IV. Debugging
- dump($variable): Prints information about a variable. “dump is a Lal built-in function which prints every information about the given variable and it prints pretty nicely.”
- dd($variable): Prints information and stops code execution. “DD which actually prints the variable and stops code execution.”
V. Configuration
- Configuration options are primarily set in the .env file.
- config() helper function accesses configuration values. Example: config(‘app.name’).
- Configuration files reside in the config directory.
- Publishing Configuration Files: php artisan config:publish [config_file] – copies configuration files from the vendor directory to the config directory for customization.
VI. Templating with Blade
- Blade Templates: Located in resources/views. Use .blade.php extension.
- Variable Output: {{ $variable }} Automatically escaped to prevent XSS. {!! $variable !!} Unescaped output.
- Blade Directives: Keywords prefixed with @ (e.g., @if, @foreach). “every directive starts with eight symbol for example there is a for each directive.”
- Escaping Blade Directives: Used @ symbol two times in order to correctly display @foreach or @if
- Verbatim Directive: @verbatim … @endverbatim Prevents Blade from processing the content within the block.
- Shared Data: View::share(‘key’, ‘value’); Makes data available to all views.
- Conditional Classes/Styles: @class([‘class-name’ => $condition]), @style([‘property’ => ‘value’ => $condition])
- Including Subviews: @include(‘path.to.view’, [‘data’ => $data])@includeIf: Includes only if the view exists.
- @includeWhen: Includes based on a condition.
- @includeUnless: Includes unless a condition is met.
- @includeFirst: Includes the first existing view from a list.
- Looping with @each: @each(‘view.name’, $array, ‘variable’) Renders a view for each item in an array.
- Raw PHP: @php … @endphp Executes raw PHP code within a Blade template. @use directive imports classes.
- Layouts:@extends(‘layouts.app’): Specifies the parent layout.
- @section(‘title’) … @endsection: Defines a section.
- @yield(‘title’): Placeholder in the layout for a section.
- @include(‘partials.header’): Includes a partial view.
- Stacks: Manage the pushing of named CSS or JavaScript to a master layout.
VII. Database & Eloquent ORM
- Database Configuration: Configured in config/database.php and driven by .env variables.
- SQLite: Default database is SQLite, using database/database.sqlite.
- Migrations: Used to define database schema changes.
- Eloquent Models: Represent database tables. Located in the app/Models directory. “In lal’s eloquent omm relationships Define how different database tables are related to each other.”
- Model Relationships:hasOne()
- hasMany()
- belongsTo()
- belongsToMany()
- Mass Assignment: Protecting attributes from mass assignment vulnerabilities. Use $fillable (whitelist) or $guarded (blacklist) properties on the model. “By default, LEL protects against mass assignment vulnerabilities unless you explicitly permit it. This safety mechanism prevents unintended modifications to your application’s data by limiting which attributes can be modified.”
- Disabling Timestamps: $timestamps = false; on a model disables automatic created_at and updated_at management.
- Retrieving Data:Model::all(): Retrieves all records.
- Model::find($id): Retrieves a record by its primary key.
- Model::where(‘column’, ‘value’)->get(): Retrieves records matching a condition.
- Model::first(): Retrieves the first record matching a condition.
- Inserting Data:Model::create([‘column’ => ‘value’]): Creates a new record. “Model: create attributes which will insert the data.”
- $model = new Model(); $model->column = ‘value’; $model->save();
- Updating Data:$model = Model::find($id); $model->column = ‘new_value’; $model->save();
- Model::where(‘column’, ‘value’)->update([‘column’ => ‘new_value’])
- Deleting Data:$model = Model::find($id); $model->delete();
- Model::where(‘column’, ‘value’)->delete();
- Soft Deletes: Using the SoftDeletes trait to mark records as deleted instead of permanently removing them.
- Model Factories: Used to generate fake data for testing and seeding. “factory stating LEL is a way to define specific variations of data when using modu factories states allow you to Define different sets of attributes for the model and making it easy to create various types of data without duplicating the code.”
- Model States: Allow to define different sets of attributes for the model and making it easy to create various types of data without duplicating the code
- Model After Making: the method is executed when we call make.
- Model After Creating: the method is executed when we call create.
- Database Seeding: Seed the database with initial data.
- Paginating results: the data will be displayed per page.
VIII. Responses
- Returning data to the user: We can return array which will be converted into JSON.
- Explicitly returning json: The return result will explicitly be a JSON.
- Returning Views: Using the helper function and controlling the status code.
- Redirecting the User: There are several ways to implement redirect in Laravel.
- The root method accepts a root name.
- Providing car object with the id parameter will be automatically rendered.
- Redirecting an external URL: using redirect away.
Key Takeaways:
- Laravel provides a structured framework for web development, emphasizing convention over configuration.
- Eloquent ORM simplifies database interactions.
- Blade templating offers a powerful and expressive way to create views.
- Artisan commands streamline common development tasks.
- The .env file and configuration system are essential for managing environment-specific settings.
Laravel Application Development: Core Concepts and FAQs
FAQ on Laravel Application Structure, Routing, Configuration, Debugging, ORM (Eloquent), Factories, Migrations, Controllers and Responses
Q1: What is the function of each key directory in a Laravel project?
- app/: Contains the core logic of your application, including models, controllers, service providers, and other custom classes. Uploaded files by the user can also be stored here.
- config/: Stores all of your application’s configuration files. These files define settings for things like database connections, mail servers, and application behavior. If you want to customize configuration options which are not available in .env file, you can find the configuration files here. Feel free to delete the default configuration files if you don’t plan to modify them as the default files exist in the Vendor folder in Laravel core.
- database/: Contains your database migrations, factories, and seeders. This also includes the database.sqlite file if you’re using SQLite.
- public/: The web server’s document root. It contains the index.php file (the entry point for all requests), as well as assets like CSS, JavaScript, and images. Only files and folders within this directory are publicly accessible.
- resources/: Contains your application’s views (Blade templates), CSS, and JavaScript files.
- routes/: Defines all the routes for your application, including web routes (web.php), API routes (api.php), and console routes (console.php).
- storage/: Stores generated files, user uploads, cached data, sessions, logs and other application-specific files. Contains subdirectories like app/ (for user uploads), framework/ (for cache, sessions, and views), and logs/ (for log files).
- tests/: Contains your application’s automated tests.
- vendor/: Contains all the third-party packages installed via Composer.
Q2: How does the Laravel request lifecycle work?
The Laravel request lifecycle can be summarized as follows:
- Request Entry: The request hits the public/index.php file.
- Bootstrapping: index.php includes vendor/autoload.php and bootstraps the Laravel application.
- Application Loading: The application loads configuration files and initiates service providers. Service providers prepare and configure the application, registering services, event listeners, middleware, and routes.
- Routing: The router takes the request and matches it to a defined route.
- Middleware Execution: Any middleware associated with the route is executed. Middleware can perform actions before the request reaches the controller (e.g., authentication, logging) and can even block the request.
- Controller Action: The matched route’s controller action is executed.
- Response Generation: The controller action may render a view or return data.
- Middleware (Post-Response): If middleware is registered, the response is passed through it before being sent to the user.
- Response to User: The final response (HTML, JSON, etc.) is sent back to the user’s browser.
Q3: How can I configure application settings in Laravel, and what is the role of the .env file?
Laravel’s configuration is primarily managed through configuration files located in the config/ directory. These files are typically populated with values from environment variables defined in the .env file.
The .env file stores sensitive or environment-specific settings like database credentials, API keys, and application debugging mode. It is crucial to never commit the .env file to your Git repository. Instead, commit the .env.example file, which contains sample values.
To access configuration values, use the env() helper function or the config() helper function.
If you want to customize configuration options which are not available in .env file, you can find the configuration files under config/.
Q4: How can I create custom routes in Laravel, and what request methods are available?
You define routes in the files within the routes/ directory. The most common file is routes/web.php for web routes. To create a new route, open the appropriate file and use the Route facade. For example:
use Illuminate\Support\Facades\Route;
Route::get(‘/about’, function () {
return view(‘about’);
});
This code defines a GET route for the /about URL that renders the about view.
Laravel supports the following request methods:
- GET: Used to retrieve data.
- POST: Used to create data.
- PUT: Used to update an existing resource.
- PATCH: Used to partially update an existing resource.
- DELETE: Used to delete a resource.
- OPTIONS: Used to retrieve the communication options available for a resource.
You can define routes that respond to multiple methods using Route::match([‘GET’, ‘POST’], ‘/path’, …) or routes that match any method with Route::any(‘/path’, …)
You can define a redirect type of route in Laravel by calling the redirect method. The first argument is the route to which you are going to listen to and the second argument is where the user should be redirected.
Q5: How can I debug my Laravel application, and what are some useful debugging functions?
Laravel offers several debugging tools:
- dump(): Prints the variable’s contents with detailed information. It does not halt code execution.
- dd(): “Dump and Die.” Prints the variable’s contents and stops further code execution.
Configuration: You can set the APP_DEBUG environment variable to true in your .env file to enable detailed error reporting.
Laravel Logs: Laravel’s built in logging system writes errors, warnings, and other information to log files in the storage/logs directory. You can use this directory as well.
Q6: What are Laravel Blade templates, and how can I pass data to them?
Blade is Laravel’s templating engine. Blade templates use the .blade.php extension and allow you to embed PHP code within HTML using special directives (prefixed with @). To display variables, use double curly braces {{ $variable }}.
You can pass data to views using the following methods in your controller:
- Associative Array: Pass an associative array as the second argument to the view() function:
- return view(‘my_view’, [‘name’ => ‘John’, ‘age’ => 30]);
- with() Method: Chain the with() method to the view() function:
- return view(‘my_view’)->with(‘name’, ‘John’)->with(‘age’, 30);
You can also share data globally with all Blade files using the View facade in a service provider’s boot method:
use Illuminate\Support\Facades\View;
View::share(‘year’, date(‘Y’));
This makes the year variable available in every view. You can use functions and classes with namespaces in Blade files to output certain things.
Q7: What are Laravel Blade directives, and how are they used?
Blade directives are special keywords (prefixed with @) that simplify common tasks in your templates. Some common directives include:
- @if, @elseif, @else, @endif: Conditional statements.
- @foreach, @for, @while: Looping constructs.
- @include: Includes a sub-view into the current view.
- @yield, @section: Used for template inheritance to define sections of content that can be overridden in child templates.
- @extends: Specifies the parent template that a child template inherits from.
- @auth, @guest: Check user authentication status.
- @csrf: Generates a hidden CSRF token for form submissions.
- @class: Conditionally applies CSS classes to an HTML element.
- @verbatim: Prevents Blade from compiling code within its block, useful for JavaScript frameworks that also use curly braces.
- @php, @endphp: Defines a block of raw PHP code.
- @use: Import a class into the Blade template.
Q8: How does Laravel’s Eloquent ORM work, and how can I define relationships between models?
Eloquent is Laravel’s ORM (Object-Relational Mapper). It provides an object-oriented way to interact with your database. Each database table typically has a corresponding “Model” class that represents it.
To define a model, create a new class that extends Illuminate\Database\Eloquent\Model. For example:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
// …
}
Eloquent automatically determines the table name based on the model name (e.g., Car model corresponds to the cars table).
Eloquent supports various types of relationships:
- HasOne: Defines a one-to-one relationship.
- HasMany: Defines a one-to-many relationship.
- BelongsTo: Defines a reverse one-to-many relationship.
- BelongsToMany: Defines a many-to-many relationship.
- MorphTo: Defines a polymorphic relationship.
Example (one-to-many):
// In the Car model:
public function images()
{
return $this->hasMany(CarImage::class);
}
// In the CarImage model:
public function car()
{
return $this->belongsTo(Car::class);
}
These relationships allow you to easily retrieve related data. For example: $car->images would return all images associated with a specific car. To prevent mass assignment vulnerabilities, define the $fillable property in your models, specifying which attributes can be mass-assigned.
Laravel Configuration: Settings and Customization
Configuration files in Laravel contain various settings for your application, and they are a key aspect of customizing its behavior.
Key points regarding configuration files:
- Location Configuration files are stored in the config folder.
- Purpose These files manage various aspects of your application, such as the application name, language, database credentials, session driver, and mailer settings.
- .env file Most configuration options are stored in the .env file. This file contains sensitive data and should not be committed to your Git repository. Instead, commit the .env.example file, which contains sample data.
- Accessing Configuration Values You can access configuration values using the config() helper function, providing the configuration name as an argument (e.g., config(‘app.name’)).
- Overriding Configuration Values If you need to customize configuration options that are not available in the .env file, you can modify the corresponding files in the config folder. If you don’t plan to modify a configuration file, you can delete it. Laravel will use the default values from the core.
- Publishing Configuration Files You can publish configuration files that are not available by default in the config folder using the php artisan config:publish command.
- Caching Configuration Files Once your Laravel project is deployed to production, it is recommended to execute the command PHP Artisan route:cache. This generates a cached version of your Laravel routes. If you want to clear this cache, you can do so by running PHP Artisan route:clear.
Laravel Routing Essentials
Laravel routing is a flexible system for defining how your application responds to client requests.
Key aspects of Laravel routes:
- Definition Routes are typically defined in the routes directory, with web.php for web routes and api.php for API routes.
- Basic Routing A basic route accepts a URI and a closure.
- Route::get(‘/uri’, function () {
- return ‘Hello, World!’;
- });
- Available Methods Routes can be defined for various HTTP methods: GET, POST, PUT, PATCH, DELETE, and OPTIONS.
- Route Parameters Routes can accept parameters. Required parameters are enclosed in curly braces {}.
- Route::get(‘/product/{id}’, function ($id) {
- return ‘Product ID: ‘ . $id;
- });
- Optional Parameters To make a route parameter optional, a ? can be added after the parameter name.
- Regular Expression Constraints Parameters can be constrained using regular expressions with the where method.
- Route::get(‘/product/{id}’, function ($id) {
- // …
- })->where(‘id’, ‘+’);
- Named Routes Routes can be assigned names, allowing URL generation using the route() helper function.
- Route::get(‘/about’, function () {
- // …
- })->name(‘about’);
- $url = route(‘about’);
- Route Groups Route groups allow sharing route attributes, such as middleware or namespaces, across multiple routes. The prefix method can be used to add a common prefix to a group of routes.
- Fallback Routes A fallback route can be defined to handle unmatched URIs, typically displaying a 404 error page or custom message.
- Route::fallback(function () {
- return ‘Fallback’;
- });
- Controller Routing Routes can be associated with controller methods.
- Resource Controllers Resource controllers provide a conventional way to handle CRUD operations for a given resource. A resource route can be defined using Route::resource(‘products’, ProductController::class). This defines multiple routes for common actions like index, create, store, show, edit, update, and destroy. You can limit the included routes with only or exclude routes using except.
- Single Action Controllers Single action controllers contain a single __invoke method and can be directly associated with a route.
- Route Listing The php artisan route:list command displays a list of all registered routes. Additional flags, like -v, will show middleware. Flags such as –except-vendor and –only-vendor can filter routes.
- Route Caching The php artisan route:cache command creates a cached version of your routes, improving performance, especially for applications with many routes. Clear the cache with php artisan route:clear.
- Redirect Routes Redirect routes allow you to redirect one route to another.
- Route::redirect(‘/here’, ‘/there’, 301); //Redirect from /here to /there
- View Routes View routes directly return a view.
- Route::view(‘/contact’, ‘contact’, [‘phone’ => ‘555-555-5555’]);
Laravel Migrations: Database Schema Management and Version Control
Laravel migrations offer a way to manage and version control a database schema, acting as a versioned blueprint that allows definition of the structure of database tables (including columns and data types) in code. Migrations facilitate the easy creation, modification, and sharing of database changes within a team. When a migration is run, Laravel applies the changes to the database, ensuring consistency and simplifying the process of rolling back changes if necessary.
Key aspects of Laravel migrations:
- Location: Migrations are typically located in the database/migrations folder.
- Structure: Each migration file extends the Migration class and contains an anonymous class with two methods: up and down.
- The up method defines the changes to be applied to the database, such as creating or modifying tables. It uses Laravel’s schema builder to define schema changes.
- The down method reverts the changes made in the up method, providing a way to roll back the migration.
- Naming Convention: Migration filenames consist of a timestamp followed by a descriptive name. The timestamp ensures migrations are executed in the correct order.
- Creating Migrations: New migrations can be created using the php artisan make:migration command, followed by the migration filename (e.g., php artisan make:migration create_car_types_table). When creating a new table, it’s conventional to name the migration file create_your_table_name_table.
- Schema Builder: Laravel’s schema builder is used to define table structures within migrations.
- Schema::create(‘users’, function (Blueprint $table) {
- $table->id();
- $table->string(‘name’);
- $table->string(’email’)->unique();
- $table->timestamp(’email_verified_at’)->nullable();
- $table->string(‘password’);
- $table->rememberToken();
- $table->timestamps();
- });
- Foreign Keys: Migrations can define foreign keys to establish relationships between tables.
- $table->foreignId(‘maker_id’)->constrained(‘makers’);
- This creates a maker_id column and defines a foreign key constraint to the makers table.
- Data Types: Migrations support various data types for columns, such as string, integer, bigInteger, boolean, and longText.
- Nullable Columns: The nullable method can be used to specify that a column can accept null values.
- Timestamps: The timestamps method creates created_at and updated_at columns.
- Soft Deletes: To implement soft deletes, add a deleted_at column to the table and use the SoftDeletes trait in the corresponding model.
- $table->softDeletes();
- Migration Commands: Artisan provides several commands for managing migrations.
- php artisan migrate: Executes all pending migrations.
- php artisan migrate:fresh: Drops all tables and reruns all migrations.
- php artisan migrate:refresh: Resets and reruns all migrations.
- php artisan migrate:rollback: Rolls back the last batch of migrations. You can specify the number of steps to roll back using the –step option (e.g., php artisan migrate:rollback –step=3). You can also rollback to a specific batch using the –batch option.
- php artisan migrate:status: Shows the status of each migration.
- php artisan migrate:reset: Rollbacks all database migrations.
- Simulating Migrations: The –pretend option can be used with migration commands to preview the SQL statements that will be executed.
- Updating Existing Migrations: To add new columns to an existing table, you can modify the existing migration file or create a new one. After modifying a migration, you typically need to run php artisan migrate:fresh or php artisan migrate:refresh.
- Default Values: You can define default values for columns using the default method.
Laravel Eloquent ORM: Models, Relationships, and Factories
Eloquent is Laravel’s built-in Object-Relational Mapping (ORM) library, which allows developers to interact with databases using PHP objects instead of writing raw SQL queries. Each database table has a corresponding “model” that is used to interact with that specific table. Eloquent provides an intuitive active record implementation for working with databases, including methods for common CRUD (Create, Read, Update, and Delete) operations. It also supports relationships, allowing definition of and interaction with associations between different database tables. Eloquent simplifies data manipulation and retrieval, making database interactions more readable and maintainable.
Key aspects of Eloquent models:
- Location: Eloquent models are located under the app/Models directory and typically extend the Illuminate\Database\Eloquent\Model class.
- Model Generation: New model classes can be generated using the php artisan make:model command. For example, php artisan make:model FuelType will create a model file for the FuelType model. A migration and controller can also be generated alongside the model by using flags, such as php artisan make model fuel_type -m to generate a migration.
- Table Names: By default, Laravel considers the table name of the model to be a snake case, plural version of the class name. For example, if the model name is Car, Laravel will assume the table name is cars. You can customize the table name by defining a protected $table property on the model.
- protected $table = ‘car_fuel_types’;
- Primary Keys: By default, Laravel assumes the primary key of the table is a column named id. You can customize the primary key by overriding the protected $primaryKey property.
- Timestamps: By default, Eloquent expects created_at and updated_at columns to exist. These can be disabled by setting the $timestamps property to false.
- public $timestamps = false;
- Soft Deletes: If your database table has a deleted_at column, you can use the SoftDeletes trait in your model. When the delete method is called on the model instance, it will not be actually deleted from the database, but the deleted_at column will be set to the current timestamp.
- use SoftDeletes;
- Model Information: You can see information about the model by executing PHP Artisan model:show command followed by the model name.
- Mass Assignment: For security reasons, it is not allowed for the model to be filled with arbitrary data. You can specify which attributes can be mass-assigned by defining a $fillable array on the model. Only the columns included in the $fillable array can be populated using mass assignment techniques like the create method.
- protected $fillable = [‘maker_id’, ‘model_id’, ‘year’, ‘price’, ‘vin’, …];
- Eloquent ORM Relationships: Define how different database tables are related to each other. Eloquent supports relationship types such as one-to-one, one-to-many, many-to-many, and polymorphic relationships. Relationships allow easy retrieval and management of related data using methods on models.
- hasOne: Defines a one-to-one relationship.
- hasMany: Defines a one-to-many relationship.
- belongsTo: Defines a many-to-one relationship.
- belongsToMany: Defines a many-to-many relationship.
- Eloquent Factories: A tool to generate fake data for models. It makes it easy to create test and seed data. Factories define how a model should be created, including the default values for attributes. Using factories, you can quickly generate multiple instances of a model with realistic data, which is helpful for testing and database seeding.
Laravel Blade Templating Engine: Syntax, Directives, and Components
Blade is Laravel’s templating engine that allows you to write well-structured, dynamic web pages by mixing plain HTML with PHP code using a clean and simple syntax. Blade views are stored in the resources/views directory and have the .blade.php extension.
Key features and concepts of Blade views:
- Basic Syntax: To display data, you can enclose variables in double curly braces {{ $variable }}. This automatically escapes HTML entities to prevent XSS vulnerabilities. If you want to render unescaped data, use {!! $variable !!}.
- Blade Directives: Blade directives are special keywords prefixed with an @ symbol. Directives provide a shorthand notation for common PHP control structures, such as if statements, loops, and including subviews. Blade directives are converted into plain PHP code, which improves readability and maintainability.
- Conditional Directives: Blade provides directives for conditional statements, including @if, @elseif, @else, and @endif. There are also directives for @isset and @empty to check if a variable is set or empty, respectively. The @unless directive is the opposite of @if.
- @if (count($cars) > 1)
- <p>There is more than one car.</p>
- @elseif (count($cars) == 1)
- <p>There is exactly one car.</p>
- @else
- <p>There are no cars.</p>
- @endif
- Loop Directives: Blade includes directives for creating loops, such as @for, @foreach, @forelse, and @while. The @forelse directive combines a @foreach loop with an @empty directive, allowing you to specify content to display when the loop has no iterations.
- Comments: Blade comments are defined using {{– comment –}}. Unlike HTML comments, Blade comments are not visible in the page source.
- Template Inheritance: Blade allows you to define a base layout and extend it in other views. This is achieved using the @extends and @section directives.
- @extends: Specifies which layout a view should inherit.
- @extends(‘layouts.app’)
- @section and @yield: Sections define content that can be inserted into specific locations in the layout, marked by the @yield directive.
- // Layout file (resources/views/layouts/app.blade.php)
- <title>@yield(‘title’) – Car Selling Website</title>
- // View file (resources/views/home/index.blade.php)
- @extends(‘layouts.app’)
- @section(‘title’, ‘Home Page’)
- @section(‘content’)
- <h1>Homepage content goes here</h1>
- @endsection
- @show: The @show directive is used to both define and immediately display a section. @show is equivalent to calling @endsection and then @yield with the same section name.
- @parent: Used within a section to include the content of the parent section.
- @hasSection: Checks if a specific section has been defined.
- @sectionMissing: Checks if a specific section is missing.
- Including Subviews: Blade provides directives for including other view files within a view.
- @include: Includes a view, and you can pass data to the included view as an associative array.
- @include(‘shared.button’, [‘color’ => ‘brown’, ‘text’ => ‘Submit’])
- @includeIf: Includes a view if it exists.
- @includeWhen: Includes a view based on a condition.
- @each: Renders a view for each item in a collection.
- @each(‘car.view’, $cars, ‘car’)
- Components: Blade components are reusable pieces of user interface that can be included in blade views. They can be class-based or anonymous.
- Anonymous Components: Blade files located under a specific folder inside resources/views. They are included as HTML tags starting with x-.
- <x-card />
- Class-Based Components: Provide the possibility to override the default location of the Blade file.
- <x-search-form action=”search” method=”get” />
- Slots: Blade components can also utilize slots, providing designated areas within the component where content can be injected from the parent view.
- Other Directives:
- @verbatim: Ignores all Blade directives and expressions within the block.
- @json: Renders a PHP variable as JSON.
- @checked: Adds the checked attribute to an HTML input element if a given condition is true.
- @disabled: Adds the disabled attribute to an HTML element if a given condition is true.
- @selected: Adds the selected attribute to an HTML <option> element if a given condition is true.
- @required: Adds the required attribute to an HTML element if a given condition is true.
- @readonly: Adds the readonly attribute to an HTML input element if a given condition is true.
- @class: Conditionally adds CSS classes to an HTML element.
- @style: Conditionally adds inline styles to an HTML element.
The Original Text
I recently have released Lal for beginners course on my website the cool.com that course contains 37 modules 24 plus hours of content more than 300 well prepared well-edited HD videos written lessons quizzes and challenges deployment on custom domain on VPS server with GitHub actions certificate of completion and a lot more today I took first 19 modules of my premium course combine that into a single video and offering this to you for free on my YouTube channel the only thing I ask is like subscribe and provide a nice comment the video has a Time codes for pretty much every lesson if you want to skip around you can do this I have one very important and big announcement to make in this introduction section so please don’t skip that section and watch it till the end I tried to make the course Very beginner friendly so I didn’t not use any extra JS or css Frameworks during this course even the HTML CSS template which I created exclusively for this course is pure HTML and CSS and JavaScript template no extra Frameworks there we will just work with LL and blade templates and of course database and a lot of other things do you get my point right anyway I plan to update the course from time to time trying to make this literally the best Lal 4 beginners course out there and for this I need your feedback whether you’re watching this on YouTube channel or on my website C .c if you have anything in your mind you can write them under the comment section down below and I will do my best to read every comment and react accordingly on those comments if you are enrolled in this course you can provide your feedback on the Discord group as well the course also has 400 Pages written notes for pretty much every lesson from time to time as I update my course I will update that written notes as well on the course page or on my website you can find the newsletter subscription form if you want to get the course updates or PDF updates or releases about new courses please subscribe to the newsletter I promise you won’t be spammed you will be only notified with meaningful and useful information for you before we jump into the course two more things I want to mention first is that I’m right now working on one of the most exciting project I have ever built and this is going to be available on my YouTube channel for free and this is Lal react e-commerce website that course will use the latest Lal version react uh with inertia version two and service side rendering spatia roles and permissions package it’s going to have multiple vendors online payments and it’s going to have a lot of comprehensive e-commerce features such as product variants Dynamic Fields coupon codes and discounts watch list reviews and a lot more follow me on EX or Twitter because I share updates regarding this course from time to time and also don’t forget to subscribe to be the first one to be notified when the course is released and now here’s the exciting news I wanted to give a chance to every student who wants to enroll to my courses but cannot afford them so this is what I decided in every video I’m going to generate 100% coupon code for all the products that I have right now created on my website and right now there are three products Lal course for beginners which is what I’m talking about right now the offline written notes for this Lal course for beginners which is 400 page PDF file and laravel vue.js e-commerce website as soon as you find the coupon code you can use that coupon code to purchase all my three products and in this specific video there are two such coupon codes and though the location of these coupon codes are absolutely random so you see that this is 11 hours tutorial somewhere in this um tutorial there are two coupon codes using which you can purchase all three prod products that I have right now available in order to find the coupon code you need to watch the video or scheme the video find the location and as soon as you find the coupon code you can use that you can uh just go through the checkout process on my website you can put the coupon code there and purchase for free you can enroll for free it’s a 100% coupon code I want to highlight that uh but also send me a DM on X so please let me know once you find the coupon code because I want to announce this as soon as you somebody finds that on my Twitter account or ex because I want to let everyone know that the coupon codes are already found for this specific video so for this please follow me on Twitter as well and send me DM if you find the coupon code if you’re the lucky one to find that I’m I’m very happy for you um but yeah this is all I wanted to say and this happens on almost all the videos I release from now on so in every upcoming videos there will be at least one coupon code one is going to be kind of minimum but today because this is a special video for me um I decided to put two coupon codes yeah that’s what what I wanted to mention and now enjoy the video Welcome to my leral course for absolute beginers in this course we will learn all the fundamental topics of Lal and build fully functional car selling website where you can browse cars for sale filter by multiple criteria such as make model release yard price car type and so on you can see car details page with multiple images detailed description and features of the car in case you are interested buying the specific car you can view the owner’s full phone number if you want to sell your own car you can sign up or login with email and password or with social out such as Google or Facebook you can add your own car upload images and publish on the website at the end of the course I will also teach you how to host the project on custom domain in production environment just type in your browser grab a car doxyz and see the final version of the project at the end of each module you will also find quizzes and challenges to test your skills the course also includes written notes for almost all the topics that is explained in video content this course also has 3 hours testing section we’re going to get familiar writing test in LEL and write all the necessary and useful tests for our project by the end of this course you will be able to confidently build Lal projects with this complexity and host it on custom domain the course also comes with 30 days money back guarantee if you don’t like it we will refund your money back hello everyone my name is Zur also know known as the code holic I taught to hundreds of thousands of students what is PHP and how they can create fullstack applications with PHP and L I’m super excited to be your Mentor in this course and let’s get [Music] started this course is the perfect course for everyone whether you have zero experience with Lal or you know your way around round and you want to take your Lal skills to the next level since Lal is built on PHP it’s important you to have solid grasp of PHP and objectoriented programming don’t worry you don’t need to be an expert just comfortable enough to understand the basics you also need good handle of HTML and CSS since they are essential part of building websites knowing how to structure a page with HTML and style it with CSS is all what you need need lastly we will be working with databases a lot Reading Writing inserting updating the data so having a basic understanding of SQL databases will help a lot you should know what tables columns primary Keys foreign Keys data types are along with how to run queries write joints and perform basic insert update and delete operations again no need to be an expert just Basics will be enough now let’s have a look at the full demo of the project we are going to build in this course you can also check this on your own computer just type in the browser grab a car. XYZ this is already deployed on production environment when you open the homepage you’re going to see hero slider right here then search section and then latest edit cars in this hero section we see two main slides one is for potential buyers and second is for potential sellers this search form is just basic search form we can search by maker model state city type ER range price range and fuel type and when we click on search right here this is going to open dedicated search page and on the left side we have even more search criterias let me go back and check the homepage on the homepage we see 30 latest eded cars we can see car’s primary image its location its yard maker model and price the type and the fuel type as well when we click on the car it is going to open car details page right here we see all the images of this car and we can just activate the image by clicking on the thumbnail or we can navigate into the images through these arrows on the right side we see the price and all the details about this car we also have right here the seller information who is selling that specific car we can also see that this seller has 26 total cars open for selling right here we have the phone number if you as a potential buyer are interested to buy this specific car you can contact to this buyer um on this phone number however the phone number if you pay attention is not fully visible that is done on purpose we didn’t want the phone to be always fully visible because search engines will crawl our website and they will just grab grab the phone number and use it for spamming purposes instead if you are interested to see the full phone number you can click on this button this is going to make Ajax request to the server get the full phone number and display this right here so here we also have detailed description of the car and car specifications all the features the car U has supported if we scroll at the top we see right here heart icon this is to add the car into your watch list into your favorite cars right now I am not authenticated and if I click this watch list I get the following message please authenticate first to add cars into watch list okay let’s try to add this car into my favorite cars when I am authenticated now let’s test everything from the sellers perspective I’m going to click on sign up right here we have the very basic form with a name email phone and password we have also possibility to sign up with Google and Facebook let’s sign up with Google I’m going to click on this then I’m going to choose the account using which I want to sign up and I am actually already signed up and it opens this a new car page right now because I’m already authenticated let’s open the homepage I’m going to scroll down below and I’m going to add this car into my favorite cars right now I get the message car was added to watch list let’s click okay now right here I have my profile section so I can see my personal details like name email phone and I can change the password right here the email is disabled this is because I am authenticated as Google user and I cannot change email if I am authenticated as Google user if you are authenticated as regular user with email and password you can change your email let’s check my car section and at the moment my user doesn’t have any cars I can click right here to add new one but I’m interested in my favorite cars section inside which I have only one car at the moment let me go ahead and add a few more cars I’m interested into this one okay and into this one as well okay awesome now let’s click on my favorite cars and I see all three cars and the latest added car is at the top of the list okay I’m not interested in this one I’m just going to remove it I can reload the page and this is gone if I have a lot of cars added into my favorite cars list then right here I will see pagination now let me try to authenticate with a different user which has cars inside my car section and we can try to add new car from there I’m going to log out click on login I’m going to click on login right here okay and welcome back Ila Graham now let’s check my car section and I have right here a lot of cars and right here I also see this pagination okay let’s let me try to add new car click right here I’m going to choose Lexus RX ER we’re going to choose car type let’s provide some price here let’s provide the VIN code which must be exactly 17 characters so for justed testing purposes I’m just going to type right here one one one let’s provide the millage let’s provide the fuel type we’re going to choose the location we’re going to provide the address as well we’re going to provide address as well phone number and we’re going to choose the features the car has supported I’m going to take couple of features not all of them we’re going to provide right here some description let’s provide test description and if we want to publish the car and make it available for selling we’re going to provide the publish date right here we can also provide the publish date in the future and then the car will be visible on the website in the future but not now if we just want to create CS but not publish them you can just leave this publish date as empty right now I want the card to be displayed on the website so I’m going to choose today as publish date and before I click on the submit let’s add images as well that’s good let’s click on submit the car was added and we see right here this new car we can click on the homepage scroll down below and we see uh right here the new car has been added now let’s try to edit this car I’m going to click on my cars we can click on edit we can change anything what we want however if we want to manage images for the specific car we cannot do this from the screen we can click right here or we can click images button from here in the my cars page I’m going to click on images and right here we have couple of options we can delete the images we don’t want let’s say I don’t want this image so I’m going to tick this under the delete column and I’m going to click this update images and that image was actually deleted I can also change the ordering let’s say I want this image to be the first one so I’m going to give it position one and I’m going to give this position three I’m going to click on update images that was updated now this is the first one and if I check the homepage we’re going to see that this image now is the first image kind of thumbnail image of the car let’s go back into images if we decide that we want to add more images to that car we can click right here choose a few more right now we will have duplicated images but that’s not important and click on ADD images right now we have more images on this car let’s go on the homepage click on the car and we see all the images that we added for that specific car before we dive deep into larel I want to talk to you about something super important important and this is deployment now I know for many developers this seems something like they can put off for later stage but trust me learning how to deploy your project on production environment and make it accessible to the world is a GameChanger imagine this you have worked very hard created cool application with some cool and nice features and you want to put this project in portfolio and you want to demonstrate this to everyone how you’re going to do this of course you can write text descriptions you can also put some screenshots of the application in the portfolio but would not it be even better if you just deploy the project and put a demo link of the project in your portfolio having a demo link of your project is such a powerful tool now it is not just your words about the project it is a real actual functioning application that anyone can see when I personally look for some projects to use for my personal purposes I always look for projects which have demo links because one thing is what they say about the project how the screenshots look but the other thing is how it actually works when you make your hands on the project deploying the project on your own custom domain gives it professional look and touch as well it shows that you can take the project from start to finish and make it accessible to anyone and anywhere and this is exactly what we are going to do in this course we will be using GitHub actions for the project deployment which means less hustle for you once we set the project up your updates will be deployed immediately it is like a magic now speaking about hosting and deployment I personally use hostinger and they have been great so far I have been using their services for past three or four years and I’m very happy and confident that I can recommend it to you as well alongside with great advantages of the hostinger one of the greatest Advantage I personally like is that I have a single space from which I can purchase domains I can purchase shared hosting VPS hosting Cloud hosting I can manage DNS settings I can purchase business emails for my websites in my case this is going to be info@ grab card. XYZ um or support at grab a card. XYZ or both at the same time and hostinger also provides D protection with cloudware from their panel I don’t have to switch back and forth between multiple accounts one for domain second for hosting third for dust protection or DNS management everything is in a single place which is pretty cool for me and this saves a lot of time for me as well shared hosting is great for small projects and if the projects do not need any big customizations I can use shared hosting for a very low price which includes domain SSL certificates databases 100 website support and a lot more I do have YouTube videos where I deploy my Lal projects on shared hosting and I can tell you that this is is not bad practice but you should always keep in mind that shered hosting has shared Resources with others so that’s good for small projects but not for the big ones for medium to large size of projects I generally grab a VPS server and this is what I recommend also which comes with the latest pre-installed Lal application and set up everything the engine server the MySQL databas is the cloud panel to manage everything on your server and simply I can replace the existing prein Lal application with mine for this project we’re going to get VPS server and purchase the domain for as low as $2 all inside the hostinger they have all the tools you need to set the project up very easily and I will show you stepbystep guide how you can make your Lal project up and running on their platform for this course I partnered up with hostinger and they were kind enough to provide me the VPS server on which I’m going to host my project they also provided special link in discount coupon code for the students of this course or for pretty much anyone who wants to learn Lal go to the following URL hostinger.com learn Lal grab the VPS hosting you want and during checkout use a coupon code learn Lal to get extra 10% off so by the end of this course you will not only know how to create fully working Lal applications but also how to deploy this on custom domain on production environment make it accessible to to the world which is an awesome skill to have and it’s going to boost your confidence as well all right let’s get started lateral hands down is the most popular PHP framework out there used for almost everything starting from simple websites to apis crms e-commerce systems and just about any kind of web application you can think it was created by Taylor otwell in 2011 and right now is developed and maintained by an amazing team of passionate web developers laravel is all about clean and elegant syntax it provides a lot of tools to make building modern and robust web applications easier and more enjoyable LL offers ton of benefits so let’s take a look at few of these standout features it’s quick and simple to get started with but powerful enough to handle complex applications security is right in with features like xss protection and protection against SQL injection it delivers high performance right out of the box laravel’s rooting system is super flexible and Powerful eloquent orm makes working with a databases a breeze the syntax is clean simple and elegant making coding more enjoyable it follows the MVC architecture for better structure structure and organization LL comes with built-in support for testing which is a huge plus authentication and authorization are already baked into the framework caching is made easy for better performance it offers excellent error and exception handling the blade templating engine helps you build Dynamic frontend effortlessly task scheduling is seamless making automated tasks a breeze it has a robust QE system for managing heavy background jobs need to support multiple languages Lal got you covered with multilingual support maintenance and updates are super easy it keeps costs low while providing tons of value and let’s not forget huge laral community and ecosystem there is a package for just about anything you can think of these are just few benefits of using l the more time you spend in LL the better you will understand how powerful the framework is if you are here on this course willing to learn Lal I assume that you already have some experience in PHP and you quite probably have PHP working environment setup locally here are two major options in terms of Lal working environment setup if you are on Windows or on Ma Mech you can set up your laravel working environment using laravel herd laravel herd is a single program which combines PHP engine X web server node.js and composer if you buy a pro version of this package it is going to include MySQL radi and few other useful Services as well the second option to set up your PHP working environment is called zamp zamp is a package which contains PHP Apache web server MySQL and few other services if you choose zamp as a choice of your PHP environment you have to install composer and node.js separately which is a disadvantage compared to herd another disadvantage of zamp is that at the moment it doesn’t have the latest version of PHP supported in the future this might change and it might support the latest version of PHP but Lal herd already supports PHP 8.3 however the ADV Vantage of zamp is that it supports MySQL and comes with PHP my admin as well in case of her MySQL is in pro version so you cannot get it for free you can choose whichever you want herd or zamp if you’re on Linux you might install PHP apach your engine and MySQL as separate packages but we will not need MySQL engine or apachi locally installed for this course as we are going to use sqlite as a choice of the database and we are going to start the project with php’s built-in server but my choice for this course is going to be LEL herd just because it has the latest version of PHP 8.3 at the moment in case of Lal herd before you install your Lal project we should make one change in PHP in we are going to open a folder inside which PHP in file is located this in my case is located in my home directory under config folder heard being PHP and the version of the PHP in this folder there is PHP in file located and we’re going to open this using any editor you want we’re going to find variables order text and we’re going to remove this e and change this e gpcs into just gpcs we can close this file then we’re going to open any terminal and we’re going to execute her restart to take the changes of PHP speaking about the editor/ ID for Lal there are two major players PHP storm and vs code PHP storm is the paid product but is the best choice in my personal opinion for PHP it has integrated all the tools you need for laravel or PHP development it has 30 days free trial as well so I really recommend to try it vs code is free and open source but you need to install a couple of extensions to make it convenient for Lal development one of the extension is PHP allinone extension this contains all the basic things you need on PHP such as syntax highlighting Auto completion formatting and so on the next extension I recommend is LL blade Snippets I also recommend to install LL goto view leral extra intelligence and leral blade formater this extensions in my opinion are the most basic extensions you need to install in vs code to make it convenient to work with LL there are several ways to create Lal projects locally one of them is to install using composer comment we’re going to execute composer create d project ll/ Lal and we’re going to provide here your project name the second option is to install Lal installer and create new project with Lal installer keep in mind that internally it still uses composer to install Lal installer globally we’re going to execute composer Global require ll/ installer once this comment is finished we can create new Lal projects using Lal new and our project name the third option to create Lal project locally is using Lal herd if we go into side section we have a plus button right here when we click on this we have three options no starter kit leral Breeze and Jetstream we can choose whichever we want we’re going to click next we’re going to provide right here our project name we’re going to choose the testing framework we’re going to choose the Target location and we’re going to click next it is going to start creating project locally and once this is done we’re going to have up and running Lal project the Lal project has been created using Lal herd but I am going to delete this because this is not the way I want to create my Lal project maybe you are following this on zamp or you have a separate environment on Linux separate installation of PHP and everything so we’re going to create Lal project using terminal I’m going to navigate into desktop folder and I’m going to execute Lal new Lal course right here on the first question I have three options I’m going to hit the enter I’m going to choose the default one no starter kit and I’m going to hit enter right here as well now it asks us which database we want to use and I’m going to leave this default as this is the SQ light and this is exactly what I’m going to use hit the enter right here the project has been installed and here we have the instructions we can navigate into the project and we’re going to execute PHP Artisan serve but before I do this I want to open this project using my editor or ID the project is on my desktop as we created that I’m going to open brand new install PHP store and I’m going to click open right here we’re going to go to desktop and choose a lotel course we’re going to trust this project the project has been opened and now I’m going to bring up terminal integrated terminal of PHP storm you can open integrated terminal of vs code as well we are inside the LEL course project and we’re going to execute PHP Artisan serve now we’re going to open 1271 Port 8,000 in our browser and we’re going to see Lal application up and running in Lal in art design is a command line tool that helps you to perform various tasks related to your web application such as generating code managing migrations clearing cache and more here’s my project opened in PHP store and now I’m going to open Terminal in one terminal I have PHP Artisans running so I’m going to open second terminal in vs code you can open your terminal from the menu item terminal Al new terminal you can execute PHP Artis on serve right here and if you click the plus button it’s going to create second terminal and you can execute all the rest of the Artisan commments right here now let’s go back to PHP storm and I’m going to open this terminal on a full screen every Artisan command should be executed using PHP Artisan this is a common line tool and this command will be followed specific Artisan command such as about when we hit the enter this is going to give me the all information every information about our project such as application name Lal version PHP version information about caches and drivers let’s hold on for a second and understand how this works there is a file in our project which is called Artisan it doesn’t have any extension but actually this is a PHP file it is using the following class to pass the arguments in our console it is loading all the autoload files from vendor folder right here it is creating the Lal application and calling handle command passing the new argument input instance the rest happens inside this handle command and inside this application class to get the list of all available commments in our terminal we are going to execute PHP Artisan list we can scroll up and we see dozens of comments right here here some of the commments are inside the group such as cache DB event or make every comment right here has its own description what it does okay to see a list of commments in a specific group we’re going to execute PHP artisan make which is the name of the group help which means that I want to get all the commments inside make group or make name space when we hit the enter it’s going to give me all the commments available for the make name space to get information for a specific command such as make controller we’re going to execute the following commment PHP artisan make controller d-el we hit the enter and we’re going to see the description of the commment the usage how we can use it arguments as well as all the additional options with the description for each option so whenever you have a question how a specific command Works in Artisan you can always execute PHP Artisan that command D- [Music] help now let me give you a challenge I want you to execute an artisan command which will give you list of all the available commments in a q namespace pause the video right now execute that Artisan comment and then continue the video and see the [Music] answer okay to get a list of all commments in a q name space we’re going to execute PHP Artisan Q help we hit the enter and it’s going to give us all the available comments or the Q name space as well as the descriptions for each comment now I have another small challenge to you now let’s execute an artisan command which will give you all the information about migrate colum refresh commment okay I hope that was easy to get all the information about migrate refresh commment we’re going to execute PHP Artisan migrate colon refresh D- help we hit the enter and it’s going to give us the description the usage as well as all the options with their description regarding that specific comment now let’s explore directory structure of our lateral application there are several key folders in your Lal application inside which you are going to do most of your work one of them is the app folder by default it contains HTTP moduls and providers folder containing controllers models and a single provider but you can also create new folders manually inside the app folder such as enam for example and create new enams inside the enam folder and it’s going to be autoloaded or whenever you execute specific Artisan comments such as PHP artisan make job is going to create job folder for you inside app folder bootstop folder contains two main files a PHP and providers PHP a PHP file is one of the most important files inside which we can configure middle weers routing exceptions and few other useful things around our application providers PHP just contains a single provider you can add more providers inside this array config folder contains the major configuration files if you don’t plan to modify these configuration files you can delete them or if you want to create new configuration files you can also create them either by manually or by executing specific Artisan command the database folder contains factories migrations and sits this will also contain database.sql file if your database driver is set to sq light in our case we are using SQ light as our choice of database that’s why we see right here database SQ light this is the main database file for our project public folder is single web accessible folder index PHP right here is the entry script and the request starts from this index PHP so every file or folder which is available inside public folder is going to be accessible through the browser resources folder contains CSS JavaScript and Views RS folder contains the main rots for our application whether those are web based roads or console based roads if if we decide to create API roads we can have api.php for roads related to API storage is the folder that contains all the generated files inside app folder we can have uploaded files by the user inside the framework there are files and folders generated by the Lal framework itself such as cache sessions testing or views those views are cached views the locks folder contains all the log files generated by Lal framework test folder contains all the available tests vendor folder contains all the third party packages editor config file is necessary for IDE or editor file contains most of the configuration options around our application such as the application name application language database credentials session driver RIS client mailer SMTP credentials and so on enf do example file is the simple example file of you should never comit and push file in your git repository because it might contain sensitive data instead you’re going to comment and push. example file which should not contain sensitive data it should contain only sample data git attributes and git ignore are git related files we already talked about Artisan composer Json and composer log are composer related files package Json is for mpm dependencies PHP unit is for test read me is I think obvious and V config JS is the configuration file for V server now I want to create new route whenever I access slab URL in our application I want to see um some text some information about my project so let’s go to the project and we’re going to open Roots folder web PHP and we are going to create new root for slab for this we’re going to use root facade we’re going to listen on get method the URL is going to be about and we’re going to provide function right here from which we are going to return view in inside view we’re going to pass the actual view name in our case I’m going to create a view called about we need semicolon here semicolon here now if I try to access slab root is available but we don’t have view yet let’s go inside resources views and just like here we have welcome blade PHP I’m going to create another blade PHP file about. blade PHP file let’s hit the enter the blade file can contain plain HTML even plain HTML is okay we’re going to obviously talk more about blade in the future lessons but for now let’s just create H1 tag right here and I’m going to write hello welcome to my LEL course and let’s create another paragraph I’m going to just write low mum text now when I save this I go in the browser reload the page and we’re going to see hello welcome to my Lal course with some Laur msum text congratulations you have just created your first Lal [Music] route in leral application the request starts on public index PHP index PHP includes wender out toold PHP file then it creates application in bootup PHP the application itself loads configuration files and initiates service providers service providers in Lal prepare and configure the application handling tasks like registering Services event listeners middle wear and Roots they ensure both core and custom features are set up properly making the application ready to function efficiently then the request is passed to router the router takes the request finds the corresponding function to execute and executes that optionally there might be middle we registered on the road we will talk more about middle weers but in a nutshell the purpose of the middle we is to execute code before the request reaches to the action and maybe block the request after this the controller will send the response back to the user or if the middle we is registered the response will be passed to Middle we first and then returned to the user the controller action might also optionally render The View after which the response as a view will be sent to the browser in some cases the road might be configured in a way that it directly renders the view in which case the response might be directly sent to the user or if the middle we is available first the response will be passed back to Middle we and then back to user this is the Lal request life [Music] cycle most of the configuration options regarding LL is available in file here you can change the application name application time zone change the language change the database credentials session driver modify rist client information SMTP details AWS and so on they are are even more configuration Keys available which is not by default in the file if you want to customize configuration options which are not available inen file you can find the configuration files under config folder if you don’t plan to modify these configuration files feel free to delete them the default files exist in Vendor folder in laravel core and they will be used from core let’s open up PHP for example here we have the application name which is taken from file here we have the environment we have deug mode and so on now let’s open database PHP configuration file we have couple of options right here and most of the values are coming from file but here we have one of the option which is called migrations and here we have the table for example if you decide that you want to change the table name for migrations you should update that right here and if you don’t plan to modify any other configuration options in this database PHP feel free to delete every other option right here and only leave migrations with your own database table name in this case the default values for those other configuration options will be taken from vendor from laravel core but your modified configuration option will be taken accordingly so if I quickly delete all the options right here just below the migrations and above we can have database.php file as simple as that and of course modify the table name I’m going to undo this because this is not exactly what I want Let Me Close database PHP in a PHP and I’m going to open Terminal besides the configuration files that is available by default in the config folder there are other configuration files which is not available by default in the config folder but we can publish them and modify them to publish new configuration files we should execute the following Artisan commment PHP Artisan config publish when we hit the enter it’s going to give us a list of configuration files we want to publish most of the configuration files are familiar for us and is already available in the config folder such as app for example but by default broadcasting is not available in the config folder also course is not available in the config folder if I want to publish broadcasting configuration file I would just type right here broadcasting and hit the enter and the configuration file will be published or if you know exactly which configuration file you want to publish you can directly execute PHP artison config publish and the configuration file name for example course we hit the enter and we published course configuration file as well we can see those configuration files in our config folder broadcasting and course I just showed you how you can publish configuration files I don’t need them to be published so I’m going to delete [Music] them now let’s talk about couple of useful debugging functions in Lille we have the welcome page opened and let’s go and open roads web PHP file here we have two Roots defined and I’m going to make some changes right here I want to Define an associate creative array called person where we have this name and email and I want to print that person I’m going to use the following function called dump we’re going to provide the person right here we save this and let’s check in the browser and we’re going to see a person like this dump is a Lal built-in function which prints every information about the given variable and it prints pretty nicely if the associative array is too large you you can also collapse it and expand it and you can also see right here a comment from which file and which line that was printed there are two other debugging functions available one of them is called DD which actually prints the variable and stops code execution so if I reload right now we’re going to see only this dump and we don’t see welcome page anymore because right here the code execution was [Music] topped we have already defined a single Road in our application when we access slab about URL we see the following content this is how we Define the TRU now let’s see what other request methods are available in LL there are totally six request methods available get post put patch delete and option get is mostly used to get the information post is to create the information put is to update the information and Patch is also for to update the information delete is to delete the information and options is to get more information about the specific root in LL there is also a possibility to Define Roots which listen for multiple methods for example the following route will listen to get and post methods and the corresponding function will be executed for both methods in the following way we can also Define a root which matches to all request methods if we want to define a redirect type of rout in Lal Roots we can do this in the following way we call the redirect method the first argument in this method is the rout to which we are going to listen to and the second argument is where the user should be redirected by default this redirect happens with status code 302 but we can also provide a third argument which is going to be the status code in this case we are doing a redirect with status code 301 which is the identical of calling permanent redirect method in lateral there’s also possibility to Define view type of rules for example the following code will listen to SL contact road and it will immediately try to render a view called Contact so if we open our application we can even change the following Road definition in the following way we can change this get into view we have the road as a first argument and the second argument in our case should be the view name we already have view called about so this will be the equivalent of what we had previously and now if I open the browser and reload the page we’re going to see the same result optionally we can also provide third argument to the view method and pass the parameters for view in this case we are passing a single parameter called the phone to the contact view in the later lessons we’re going to see how we can get and how we can print those parameters inside the blade [Music] file now let’s understand how to define roots with required parameters let’s define a get root I’m going to listen to the following URL product slash and right here I want to have a variable Road parameter the road parameters needs to be inside curly braces so I’m going to Define curly braces and inside there I’m going to give it a name I’m going to call it ID so whenever the URL looks like this then some function should be executed so here I have the function and whenever the function is executed it means that the URL was matched so we are going to get that ID as a parameter of the function once we have this ready we can already return something from here for example product ID equals the parameter ID okay now let’s save this in open browser and let’s access the URL product slash1 when we hit the enter we see the following text that text is exactly what is returned from here we can type right here not only one uh we can type any arbitrary number obviously because this is a variable like 1 2 three or we can even have strings like test because we don’t have any restriction defined on the following root for the root parameter ID so our defined Road will match the following URLs any string after the product textt if it does not contain forward slash will be matched now let’s see slightly more complex example in this case I’m going to have three Road parameters let’s say that I want to access product review for the specific language so in this case the URL the first section of the URL contains the language code then we have the product as a hardcoded then we have the product ID then we have review text and the review ID so we have three variables and we can access those three variables inside this closure function we have length ID and reviews and the following Road will match the following URLs it’s going to match these three URLs just pause right now and pay attention the variables at the moment can contain any arbitrary text as soon as these variables do not contain forward slash because forward slash is is a special character in the URL in the later lessons we will understand how to add those restrictions so that link ID or review ID cannot be any arbitrary text now let’s learn how to define rades with optional parameters let me Define get Ro in this case I’m going to listen to the following URL product SL in here I’m going to define a category parameter category but to make this optional we’re going to provide question mark before this closing curly brace now let’s provide Associated function here let’s put a semicolon and inside this function we can obviously accept the category that’s going to be string category but because we Define that category right here optional this category might not be given to the fun function whenever it is not presented in the URL in order us to not have any kind of Errors we’re going to assign some default value to the category okay in this case I’m going to assign null to it otherwise you might have an error when you do don’t provide this category in the URL now I’m going to return something product for category equals the given category let’s save this now let’s open the browser and let’s try to access the following Road product slash and let’s provide the category let’s say cars I’m going to hit the enter and we’re going to see product for category cars however if we remove this section completely it’s going to still work however the category is going to be null that’s why we don’t see anything printed right here this is how you can Define the optional parameters and you can Define as many optional parameters as you want just make sure in the function us assign some default values to them otherwise if we simply remove these and reload in the browser we are going to see an error let’s undo this and I’m going to leave null right [Music] here now let’s define a road what we already had defined previously product slash ID and let’s just return a text it works and I’m going to return the ID as well as we already discussed if we provide any arbitrary text inside this ID variable it is going to work now let’s open our browser and let’s just provide product slash test we hit the enter and we see Works however our goal is to make it not working because we only want the ID to be number so if I type test we it should not work however if I type one two three any arbitrary number it should work how we’re going to do this inside this road whenever we Define this after this calling this get method we can chain another method in this case I’m going to use the method called we number we number accepts an argument and we’re going to provide a parameter so in this case I’m going to provide it and that’s it so we just Define that this rot should only work if the parameter ID is going to be number if I save this and reload in the browser we see it works however if I type test right here and hit the enter we see 404 the road was not matched that’s the whole idea now let’s see which URLs will be matched based on our road definition so the following Road definition will match the following URLs whenever the ID only contains numeric values it is going to match but it is not going to match anything that does not contain numeric values now now let’s see another example so we’re going to define the following Road where username needs to contain only Alpha Characters it cannot contain numbers or anything else it should only be Alpha characters from A to Z so it is going to match the following URLs but it’s not going to match the following URLs if the URL contains a numeric value okay let’s see another example in this case I want the username to be to contain alpha numeric characters numbers and letters is okay but anything else is not okay so in this case it is going to match the following URLs but it is not going to match the URLs which contains something else other than letter or number let’s see another example I want to Define road with multiple parameters we have language and we have ID so in this case language can only contain uppercase and lowercase letters in the ID needs to contain only digits the road will match the following URLs however it is not going to match the following URLs let’s see one last example in this case I’m going to Define list of allowed values so the language parameter can only be one of the provided values e n Ka a or i n in this case it is going to match the following URLs but it will not match the following [Music] URLs we can also apply custom regex validation logic to our root parameters for example we have three Roots defined let’s say that I want username to only contain lowercase letters not uppercase but only lowercase so in this case I’m going to Define right here here a we method I’m going to provide the parameter name in this case it is going to be username and then I’m going to provide the custom regex expression I’m going to define the following characters from A to Z and I’m using the plus sign which identifies that the following characters needs to be at least one so now if I save this and I’m going to open the browser and let’s try to access user slash Zur it is going to work and we see empty page we see empty page because we don’t return anything from here however if I use any uppercase characters inside here let’s say a is an uppercase I’m going to hit the enter I will see 404 because the rad was not matched in the same way we can Define custom reix validation Logic for other rootes so for example here I’m going to Define custom validation Logic for both parameters in which case I’m using an associative array syntax the length needs to be exactly two characters any symbol from A to Z and let’s use two character annotation however the ID needs to be digits let’s make sure it is a digit and also we need to make sure that it is at least four characters length so four comma and curly brace this is a syntax of r reix if you don’t know what is a regex how to work with it that is just out of scope of the following course but basically the following expression means that the ID needs to only contain digits but it should be also at least four characters now if I save this and let’s try to access in the browser we are going to have the following URL y/ product SL1 2 3 4 let’s hit the enter and it’s going to work and we see empty page because we don’t return anything from here however if we change this language code and make it three characters it is not going to work and we see 404 or if we return this into two characters let’s change this into Ka H but if we change this ID and make it three characters we’re going to still see 404 because according to the definition it should be at least four characters now let’s see the last example we are we Define the search let’s try to access the following URL search SL test if we hit the enter we see test right here because we are printing the search however if let’s say that my search keyword should contain slash if I try to provide for example 9 divided by 15 and I hit the enter it’s going to show me 404 because it tries to match the following URL and by default the Q parameter right here search does not consider SL character inside to make it consider SL character we’re going to use the following validation rule where search cury parameter contains any symbol and it should be at least one character so I’m going to save this and now if I reload this we’re going to see nine divided by 15 in lateral we can also Define names for each rot but what is the point of assigning name to a rot here we have Slab Road which renders about blade file and we have just slash root which renderers welcome now let’s imagine that we want to create a link to about page generally when we have a website we have the navigation and in the header we have the link to all the pages or most of the pages we might also have the link to the ab about page in the footer as well and maybe in the sidebar as well so a link to about page is used in let’s say three places and we want to change that URL so if we want to create let me create a variable called about page URL okay and we know that right now it is slab and whenever we use this about page URL it is going to be slab if we decide that we want to change the url from about into about us then we have to update all the places we have to update header we have to update footer and maybe if we have it in somewhere in the sidebar we have to update sidebar as well however if we associate name to every road and we can associate names in the following way name and then we just provide right here some string in this case it’s going to be logical if I call this about so we Associated name about to the about wrote and instead of having this hardcoded URL we can always generate the URLs with a name about page URL equals root and in this case we have to provide the root name in this case the root name is about now let’s have a look if I comment this out and if I print this about page URL let’s try to access homepage hit the enter we see a about page URL this is it however if we decide to change the url from about into about us if we save this and reload the page we are going to see updated URL so the generation of the URL should always happen based on on the road’s name that’s why it is always good practice to associate names to your [Music] roads now let’s define one more road which will have parameters product road with length and ID parameters I’m going to associate name product. view to the following quot now let’s generate URL based on the road name for the road which already has two parameters so first we’re going to Define this product URL with the road and provide the product name then we’re going to provide two parameters those are parameters which is required for the road Leng and ID we’re going to provide Leng to be whatever and ID to be whatever in this case e and one now let’s print this product URL but for this let’s remove what we have right here completely now I’m going to save this and let’s access in the browser I’m going to reload the page and we see the following URL now if I decide to change the format of the URL let’s say I want P slash language and then ID I save this I reload the page and this is how our URL looks like let me Define another rout and I’m going to call this user slash profile let’s create a simple function empty function right here and I’m going to give it also name to be profile now I’m going to Define another rout which I’m going to call current user and let’s say whenever current user is accessed I want to redirect user to the user profile page so in this case I want to do this redirect using the name so one way to do this is going to use a redirect function and provide root right here and provide the root name in our case this is going to be profile the second way will be to use to root function just providing root name we can comment this out and just like this whenever we try to access SLC current user URL it is going to redirect us to a road which has name profile in our case this is going to be it if we want to Define roads with the same prefix we can do this in the following way we can call the prefix on the road providing your desired prefix and then we’re going to call group method on this providing the function inside that function we can Define our roads in a regular way however the prefix admin will be used for every road defined in this function so in our case the following rout will be matched if the URL is admin users if I save this and if we check in our browser we can see users is not going to be matched but admin SL users will be matched normally in the same way we can Define the prefix for the root name we’re going to use root name and the value is going to be admin dot in our case we provide the group and inside this function we’re going to Define slash users root however I’m going to assign name to that road and this means that the URL is going to be matched with Slash users but the road name is going to be admin. users so if I save this any if we try to access slash users we are going to see these slash users however the road name is going to be admin. users typically when the road is not matched lateral will show 404 error for example let’s try to access SL contact we see 404 however we can define a fallback rout for every un Ed roads we can do this in the following way we’re going to call fallback providing function right here which will be executed every time road is not matched so if I return right here fallback save and reload in the browser we see fallback right here in this case you can render any view maybe you want to save that information somewhere but the idea is that you can match all unmatched URLs with the fallback method [Music] now let’s open Terminal and I want to execute a command and print all defined Road list for this we’re going to execute PHP Artisan Road list this will print six roads and two of them is defined by us slash and slout others are defined by a LEL application if we want to also display middle we for each Road we’re going to provide flag DV we hit the enter and it is printing the middle we as well for each road if we want to only print roads which is defined by us we can provide D Dash except Dash vendor flag we hit the enter and it’s going to print those two roads in a similar way if we want to Define roads which is defined only inside the vendor we can provide only- vendor we hit the enter and it’s going to print those four roads only if we want to Define all roads which are part of the API we can provide path equals API we hit the enter and in this case the application gives us an error that we don’t have any rows matching the given criteria which is actually correct we can even combine these flxs and for example print all the details about our roads we can print them except vendor and we can even provide path equals admin for example this is not going to print anything because the given path was not matched but I hope you get the idea once you deploy your Lal project on production it is recommended to execute the following command PHP Artisan wrot cach this will create cached version of your Lal roads is especially this is useful if your application has a lot of Roads the cache will help your application to match the road in a shorter time and this will increase the overall performance of your website however if you don’t want this cach anymore you can clear this always by executing PHP Artisan Road [Music] clear now let me give you a small challenge you should create a road which accepts two Road parameters these Road parameters must be numbers you should calculate the sum of these two parameters and print that sum pause right now spend some time to implement this then come back and see my [Music] solution all right now let’s Define the root we’re going to listen to the get method and let me call this sum and then we’re going to accept two parameters A and B you can call this whatever you want then we need to define the function however I’m going to also Define a validation Logic for these parameters we are number we are number and we can provide an array A and B both should be numbers then we’re going to accept right here float a and Float B finally we are going to return some of these two numbers a plus b let’s save this now let’s open the browser and try to access to the following rout sum one and two let’s hit the enter and we see three right here let’s increase the numbers 1 2 3 slash 4 5 6 let’s hit the enter and we see five seven and nine that works correctly controller is a class which is associated to one or more roads and is responsible for handling requests of that roads generally controller is a grouping of similar roads together for example product controller should contain only logic Associated to products but not anything else car controller should not contain logic which is not associated to cars we can create controller classes manually or we can execute Artisan commments doing this with Artisan Commons is more convenient and fast so this is how we’re going to do also PHP artisan make controller and we’re going to provide the name of the controller I’m going to call my controller car controller it is also convention that your controller classes should should end with controller suffix in our case it is car controller let’s hit the enter the output tells us that the new file was created under up HTTP controllers F folder called car controller okay we are going to open this up HTTP controllers car controller this is how car controller looks like by default now let’s create a road and associate action to that controller I’m going to define a function called index okay from this function I’m going to return hardcoded text index method from car controller let’s save this now I’m going to open roads file web.php and I’m going to associate that method what I just created to specific rout let’s define a rout and listen on SL car and provide the controller and the method the controller is going to be called car controller we’re going to provide class and the second argument of this array right here is going to be the method name the method is called index and just like this we provide the controller and the method instead of providing a closure function actually I’m going to change this into import so here we have just car controller but here is the import of our controller okay let’s save this and now let’s try to access this in our browser right here let’s change car hit the enter and we see index method from car controller if we have multiple methods defined in the car controller and we want to associate them to roads obviously we can duplicate this change the road right here and change the method however there’s a better version of it and we’re going to use grouping by the controller so in this case I’m going to use Road controller but I’m going to provide car controller right here car controller class this returns an object on which we can call group inside group we’re going to provide function and any root we’re going to Define inside this function will assume that the controller is the car controller so I’m going to take this rout put this right here but we don’t need the controller we only need the method name so this is how we can Define SL car we can duplicate this and we can have for example my cars right here which will have a different method associated like my cars or and so on you get the idea right so whenever we save this let’s check in the browser I’m going to reload this and the result does not change so it is still using this index method right here to render some text whenever the URL is matched in Lal we can also Define single action controllers if your controller grows and becomes very large it is recommended practice to split it up into multiple other controllers or create single action controllers single action controllers are controllers that are associated to a single route only to generate single action controller we’re going to execute the following commment PHP artisan make controller we’re going to provide the controller name like show car controller for example and then we’re going to provide a flag D- invocable that D- invocable flag makes the controller to be single action controller when we hit the enter we see that the controller was created let’s collapse this let’s go into controller section and we’re going to open this show car controller that controller is very similar to car controller however it has one additional method underscore uncore invoke that’s a special method and whenever we use that controller in the road that method can be executed however the usage of the controller should be also different now let’s go into web.php and I’m going to modify this slightly let me actually comment this out for now and I’m going to Define new controller new route slash carar on SL car we are going to apply show car controller class pay attention that I don’t provide the method anymore just like I we have provided previously I don’t provide method let’s change this using import so that we have showard controller without name space and we have the showard controller imported properly now if I save this let’s go actually in the showard controller and let’s return something like return uncore uncore invocable let’s save this now let’s go in the browser and reload the page and we see UND underscore invocable invocable controller is nothing else but addit invoke method to regular controller so in the same way what we can do is let me just delete this show car invocable controller completely then inside the car controller I’m going to create that function uncore uncore invoke let’s just return from here underscore uncore invoke we say this let’s open web PHP and here we are using show car controller and I’m going to change this into car controller now if I save this and reload in the browser we’re going to see uncore unor invoke which is coming from car controller however we have other regular method as well in our car controller and we can use this one as well let’s go into web and let me duplicate this and I’m going to change the url for one of them let’s give it different text inv vocable for example and right here on this car I’m going to provide the array we provide the controller and we provide the method as well so now I save this and if I just reload we’re going to see index method from car controller however if we provide invocable right here we’re going to see underscore uncore invoke before we start talking about resource controllers I’m going to delete just created car controller completely let’s delete the rotes as well in LEL a controller is a special type of controller that provides a convenient way to handle typical crowd operations for a resource such as a database table to generate resource controller using AR design we should execute the following command PHP artisan make controller we’re going to provide the name of the controller I’m going to call this product controller and then we’re going to provide a flag called D- resource once we hit the enter it’s going to generate this product controller let’s open this product controller and as you see there are predefined methods we have index create store show edit update and destroy there are seven default methods defined in the resource controller for typical crowd operations index is responsible to show a list of the resources create is responsible to show form for the resource using store we’re going to create the resource inside show we’re going to show a specific resource by the given ID inside edit we’re going to render the form for editing purpose for a specific resource ID in the update we’re going to update the resource by the ID and in the destroy we’re going to delete the resource by the ID now let’s open web.php and I’m going to Define Roots Associated to this product controller we can obviously Define Roots separately for each method what we have right here but there’s a oneliner in laravel which can do this thing rote Source we’re going to provide the name products for example and then we’re going to provide the controller name in our case this is going to be product controller class semicolon at the end and let me change this using import so we have product controller imported right here now if we try to access SL products it should execute the following route let me bring up the terminal and I’m going to execute PHP Artisan Road list this will print the list of the roads and let’s have a look so here we see the seven roads defined by us which corresponds to products Index this is an index method this is actually a root name and this is the method name so the root name for to create products is called products. store and it is mapped to the following Method products create is mapped to the following method and so on if we want to exclude a specific method from this definition we should provide right here accept method inside except we can provide array of methods we want to exclude for example I’m going to exclude destroy from this list let’s save this let’s bring up the terminal and I’m going to execute again PHP Artisan Road list now we don’t see products destroy method right here we only see six roads defined or if we want to only include specific roades in the Declaration we can provide only method as well inside only let’s say I’m going to provide index and I’m going to provide show I don’t want anything else from this product controller let’s bring up the terminal and I’m going to execute PHP Artisan Ro list and now we only see two roads defined from the product controller in the product controller as I mentioned we have seven methods but five of them is relevant for the API two of them is not relevant for the API for example the purpose of this create is to render the form as well as the purpose of this edit method is to render the edit form so these two methods are not relevant for the API if we want to Define resource for the API only we should do this in the following way instead of resource method right here we’re going to use API resource method once we Define this let’s bring up the terminal and I’m going to execute PHP Artisan R list hit the enter and now we have five methods defined we don’t have create method and we don’t have edit method right here let’s go even step farther and when we generate the controller if we want to generate it for the API meaning that if we don’t want create and edit methods to be presented in the controller we should execute the following Artisan command PHP artisan make controller we are going to obviously give it name car controller and then we’re going to provide d d API flag once we hit the enter it’s going to generate this car controller let’s open this very quickly and we see index store show update and Destroy we don’t see create and we don’t see edit as well then in the same way we can use this car controller right here to Define rules for the car controller we’re going to use API resource name we’re going to provide the resource name in our case we can call this cars and then we’re going to provide car controller right here let’s replace this with import as well we should see car controller imported right here however if we we want to Define product controller and car controller both at the same time as API resources we can use API resources name providing associative array where the key is the resource name and the value is the controller so we Define the car controller and we can provide as well products by specifying here product controller just like this we can delete this completely and now if we execute PHP Artisan Road list we are going to see API Roots defined for cars as well as defined for products in the later lessons we’re going to learn how to implement these methods actually and how to implement in general crowd operations how to render the data how to create the data how to delete the data as well okay now I don’t need this car controller and product controller yet so I’m going I’m going to delete them both and I’m going to also remove them from web.php [Music] now I have a challenge to you I want you to generate a controller with two methods sum and subtract Define roads SL sum and/ subtract which will be Associated to the controller corresponding methods both methods will accept two arguments and both arguments should be numbers when accessing slm Road it should print the sum of arguments and when accessing SL subtract method it should print the difference of these two numbers pause the video right now spend as much time as you think you need on this problem try to make it working and then come back and see my solution [Music] okay I hope you made it now let’s see my solution first of all I’m going to create controller let’s execute PHP artisan make controller math controller let’s hit the enter math controller was created now let’s open this and create two functions public function sum we’re going to except two arguments inside this function float a and Float B now let’s define second function subtract float a and Float B here we’re going to return some of these two numbers so we’re going to return A+ B and in the second function we are going to return Difference A minus B now let’s open web PHP and Define Roots root get on/ sum we’re going to accept two properties two parameters A and B and we’re going to associate the math controller sum method right here let’s put the semicolon and let’s replace this with import now let’s duplicate the and I’m going to call this subtract A and B and the method name will be subtract now we save this and we can check this in the browser let’s access sum sum five and 7 hit the enter we see 12 now let’s change the method name into subtract hit the enter and we see minus two and just like like this we made it working but if we change seven right here into something non numeric value such as a c and we hit the enter we are going to see an error subtract method argument B must be type of looat but string was given that’s because we need to validate the arguments of sum and subtract method so right here and right here we’re going to provide we number and we’re going to provide a comma B both A and B should be numbers so now if I save this and if we reload this in the browser we are going to see 404 because such type of URL is not defined in our RADS however if we change ABC into something which is numeric value which is number we hit the enter we see the result all right that was the challenge and we completed the challenge now I’m going to delete math controller and I’m going to also remove Roots defined in web [Music] PHP so far we have been creating and deleting controllers defining and removing Roots that’s because we have been learning and we did not need this code in our final car selling website now I’m going to start working on my car selling website and I’m going to define the controller which will stay in the project and I’m not going to delete this let’s open Terminal and I’m going to execute PHP artisan make controller and I’m going to call this home controller we hit the enter home controller was created now let’s go in the home controller and I’m going to create new function and I’m going to call this index and for now let’s just return index hardcoded string from here now let’s go into web PHP and I’m going to change this closure function into using home controller class and I’m going to render I’m going to use index method right here okay now I’m going to change this home controller fully qualified name into import so that we have import right here and we have much much shorter line right here let me associate name to this and I’m going to call this home as well now if we go in the index method we can return this hardcoded index or we can change this and return the welcome blade file as it was returned from this web PHP right here let me quickly undo this right here we be returning this view so now we change this into home controller okay awesome now let’s open the browser and in the browser nothing is changed we see lel’s welcome page however this welcome blade file is not exactly what I want so if we go under resources views we’re going to see about blade which is something we created and we have this welcome blade PHP as well so I’m going to completely delete this welcome blade PHP file PHP torm Finds Its usage in cached file so it asks me whether if I want to refactor or not I’m going to do refactor anyway it is a cached file so in this case what I’m going to do is just to return hardcoded index and in later lessons we’re going to start working on views and I’m going to create new view for the home controller index method and I’m going to use that new view right here but for now if I reload the homepage we’re going to see hardcoded index text [Music] views are files that are responsible for presentation logic in your LEL applications and are stored under resources views folder typically views are in format of Blade files blade is a Lal templating engine that helps you build HTML views efficiently it allows mixing HTML with PHP using Simple and Clean syntax blade supports template inheritance enabling you to define a base layout and extend it in other views it provides directives with different purposes for control flow blade also supports reusable components and Slots all blade views must have extension. blade. PHP we can create views by hand under resources views folder or we can execute the following Artisan commment PHP art is on make View and we’re going to give it a name the view name should be all in lowercase like index for example I’m going to hit the enter and index view was created under resources views index. play. PHP file if we open this we see this empty d right here with some comment now let me change this content and let’s write H1 and I’m going to write text hello from larel course I’m I’m going to save this now let’s go into controllers up HTTP controllers and I’m going to open Home controller and I’m going to change this return right here and instead I’m going to render View using view function and inside here I’m going to provide the view name which I just created now let’s open browser and I’m going to reload the page and we see hello from LEL course views can be deeply nested into sub folders under resources views folder for example under resources views I’m going to create a new folder called it home and I’m going to move my index blade PHP under home and now inside home controller when we try to render this view index we should change right here as well instead of rendering index which will not work anymore because there is no index. blade. PHP file under views folder instead it is available in the home folder we are going to render this in the following way home dot index the dot identifies subfolder so it is like a folder separator now if I save this and we check in the browser the result is unchanged this also works however if we want to create a View using artisan and directly put this in a subfolder we should execute the following comment in the view name we’re going to provide home. index as well so in this case it will throw an error because the view under home folder index view already exists but if you want to create for example home AB about we hit the enter and it’s going to create about. blade PHP under home folder obviously this is something what we don’t need at the moment so I’m going to delete this [Music] to render The View we used function called view there is a second method to render The View as well in this case we’re going to use view facade so I’m going to remove this and I’m going to use view facade which is coming from illuminate support facad so make sure you use the following facad following class we hit the enter that needs to be imported right here make sure it is imported if you’re using vs code and then we’re going to call method called make and here we’re going to provide the view name in our case this is going to be home. index so we save this and if we check in the browser the result is not going to change because we are doing the exact same thing however the view facade has couple of advantages for example right here we can provide another function called First and provide a list of View files for example first I can provide index IND and then I can provide home index well the first method will render the first available view so in this case if there is index blade file under views directly it will render it otherwise it will search under home. index so if we just copy this index plate PHP and put this under views and if we just change its content have hello from um views folder okay so I save this and if we reload in the browser we see hello from views folder now I’m going to again delete this index blade from views folder and it is going to pick up this index blade from home folder and the result will be hello from LEL course if we want to check if the view exists or not we can also use view exist function we provide for example home. index and if the view does not exist for some reason we can dump the following message view does not exist of course in this case the view will exist because there is home. index but if I change this into just index save this and we reload in the browser we see view does not exist I’m going to undo the change and return the code back when we were using view function just like this now let’s talk about how we can pass variables to views there are two ways to pass data to views one of them is to provide an associative array as a second argument of the view function and we can use this associative array when we are using view facade make function as well make method okay here I’m going to provide two Vari variables one I’m going to call it name and I’m going to provide my name and then I’m going to provide um surname which is going to be my surname awesome now we can access these two variables in the blade file let’s open blade file hello from blal course and I’m going to create a paragraph right here my name is and I’m going to print these two variables to print these two variables we’re going to use double curve braces and inside double curly braces we’re going to use PHP variable normally like dollar sign and the name the name is the variable we passed right here in the same way we can also output second variable called surname now if I save this Andre load in the browser we are going to see Hello from Lal course my name is Zur the second method to pass data to views is the following we can remove this associative array and we can provide additional variables inside The View using with method the first argument is the variable name name for example in our case and I’m going to provide zuro right here let’s move this with down and the second we can provide this with second times so here I’m going to provide surname is going to be my surname I’m going to save this reload the browser and the result does not change however if I comment out this line there is no surname declared in the blade file in the view file so it will throw an error now let’s uncomment this so that we don’t have any [Music] errors it is also possible to declare a global shared data and that data will be available in all blade files for this we’re going to open service provider up service provider which is inside up folder providers let’s open this and inside boot method we’re going to use view facade or this and we’re going to provide Shear method right here the key will be the variable name I’m going to call this ER and the value is going to be your value of the variable so let’s use a function date to create the current ER let’s put semicolon Right Here and Now the Y variable will be available in every blade file so if we open this index blade PHP and I’m going to create second paragraph right here y colon and then we can output y let’s save this reload the browser and we see y [Music] 2024 now let’s do a small challenge I want you to create a hello control roller with welcome method create welcome view as well using IGN and put it in the Hello subfolder from Hello controller welcome method render welcome view you just created pass your name and surname to The View and output in the blade file also Define the root SL hello so that when you access it it will output your name and surname now pause the video work on this spend as much time as you need on this then come back and see my [Music] solution okay now let’s see my solution first let’s open Terminal and I’m going to generate new controller in New View file PHP artisan make controller hello controller we hit the enter the controller was created now let’s create view PHP arst on make view well I’m going to create welcome view but I’m going to put this in the hello folder so hello. welcome this will create welcome view in the hello subfolder I’m going to hit the enter now look at this welcome blade PHP was created inside hello folder awesome now let’s create Hello controller from up HTTP controllers and let’s define welcome method from here we are going to render view called hello. welcome so this is the blade file we’re going to render and we’re going to pass two variables we’re going to pass name and we’re going to pass surname awesome now we have the controller we have the view created now let’s go let’s collapse everything let’s go under Roots web PHP and Define new root root get on slash hello we’re going to render hello controller method called Welcome let’s put a semicolon right here and we have these roots defined now let’s access this in the browser slash hello we hit the enter and we see empty our output let’s check hello controller this is because we don’t have anything defined in the hello welcome now let’s open resources views hello welcome blade it is an empty div and let’s change this and output these two variables let’s delete this comment and output name and surname we save this reload in the browser and we see my name and surname you should see your name and surname the data you passed from the hello controller like this now let’s clean up the code we created for the challenge let’s remove the root I’m going to also delete this hello folder completely including welcome blade PHP and I’m going to also delete hello controller cool we don’t need this in our final [Music] project besid the variables we are using in our blate files we can also use functions we can even use classes in their methods to Output certain things in the blade files let me actually remove these two lines now let’s use date function and print the current date so we already have this shared Global shared y variable which we printed previously but right now I’m going to use functions in Blade file to output something so we can use date function inside Cur braces just to Output the result the current ER in the same way we can do the following we can use Str Str to Upper function take our name and concatenate it with a surname and print it like this so if I save this right now and we check our browser we to access to the homepage we’re going to see the Y in my name and surname all in uppercase so in the same way way we can even use classes with name spaces to print something so for example I’m going to use St Str helper class and use the after method basically inside the following string we’re going to take anything that is after hello space so it should print world I’m going to save this reload in the browser and we see world right here we can also use application constants or we can use even Global constants like this all will work in your blade files and the result will be something like this now let’s open Home controller and I’m going to Define one more variable right here and I’m going to give it job name however the content will contain HTML Tags I’m going to use B tags and inside B Tags I’m going to write the developer now let’s open blade file and I’m going to Output right here my job this is going to be like this if I save this and we reload in the browser we’re going to see developer right here but the bags are printed well they are printed as you see so actually the developer is not inside bold whenever we output variables inside blade they are escaped in the the following way if we want to render it differently and if we want job to be inside bold instead of rendering boping and closing tags we should render it in the following way we are going to use let me remove this completely we’re going to use one curly brace and then we need double exclamation okay exclamation two times and inside here we can output job now if I save this and reload the page we’re going to see developer in bold let’s remove this and now let’s imagine that I want to print something like this in my browser the following expressions are very oftenly used in frontend applications such as vue.js if we want to print a variable in vue.js we need to do this in the following syntax in the following way let’s assume that I’m using a VI JS and I want to Output the following content if I save this and if I reload in the browser we are going to see an error right here right now blade is processing curly braces double curly braces and right now blade is trying to find a constant called the name and output it right here because we have these double curly opening and closing braces but let’s say that we want the output to be exactly like this what are we going to do in this case we’re going to put it symbol before these opening double curly braces this add symbol tells lateral blade not to process the following expression if I save this and if I reload right now I see the following output and this is exactly what I want okay and this output now later can be used by vue.js to render the name variable also in Blade there are directives every directive starts with eight symbol for example there is a for each directive okay let’s say that I want to Output a text starting with at at for each or at something if I do this if I save this and if I reload this I see it something however if I want to print 84 or 84 each this will throw an error because because we have a syntax err at the moment whenever blade sees 84 it assumes that we I want to iterate over something and it basically fails because I don’t provide all the arguments for this directive however my intention is just to print 84 in my browser so for this we’re going to use second times the at symbol 8 84 so if I save this and reload right now we see 84 in the browser and this is exactly what I wanted however imagine that just like we have here name and the same way let’s say that we have multiple such type of Expressions I’m going to copy and paste small amount of code where we have name age job hobbies and also we have this if directive which is also blade directive now if I save this and if I reload the first first one right here it’s going to fail because it will try to print the name of course we can go ahead and add eight symbols for all of them like this and it is going to work and we see the following result but doing this manually in five places to put this add symbol is not convenient there is better way to do this in leral Blade and it is called verba team directive so I mention that all directives in Blade start with at symbol so we’re going to use verba team directive for this and we need also end verba te directive down below so whenever there is something some content between opening verbatim and closing verbatim directives between here and between here Lal blade will not process these variables so these double curly Expressions will not be processed this if will not be processed and they will be outputed exactly as you see so if I save this and reload the page we don’t see any change so this is working as it should work however without this word button directives we are going to see an error we have syntax error and even if we fix this syntax error we we’re going to have a lot of Errors basically because we don’t have we don’t satisfy the blade requirements that’s why we need verb team Direct to Output it as we [Music] expect now I’m going to add one more variable into my home index view file let’s provide WID right here and I’m going to call these hobbies and in this case I’m going to provide an area let’s say my hobby is tennis and fishing it’s pretty different types of hobbies but I love both okay now let’s go into index blade PHP and I want to Output this array Hobbies as a Json array how to do this so for this I’m going to use JS helper class so I’m going to use double curly braces to output something and I’m going to use JS helper class this one illuminate support JS and I’m going to use from function for this and I’m going to provide the variable called Hobbies so this will actually output a Json let me save this and let’s go in the browser reload this and here we see Json parse and if we check this also in the page Source we see this Json Parts this from function encodes your variable into a proper Json format and if I want to create now a JavaScript variable which is the intention basically when you want to convert this into Json so we should create a script tag inside script tag obviously we need to Define a variable called hobbies for example and we can assign the following expression to Hobbies okay now I save this now we reload this and we see const Hobbies equals the following variable if we check this in the browser we obviously don’t see because we put this in script tag however if we bring up developer tools and if we go in the console we should see hob is global variable available and if we hit enter we see tennis and fishing hey if you are enjoying this tutorial so far maybe you want to check the entire course on my website the.com where you can find quizzes The Source Code of the project is available there you can find all the modules including the deployment section the T testing section which contains I think three hours of uh content regarding testing uh using pest framework and a lot more all right now let’s talk about what are laravel blade directives and how they are used blade directives are special keywords which is prefixed with Ed symbol used in laravel’s Blade templating engine to simplify common tasks like template inheritance conditional rendering iteration of data and more they convert these Shand notations into plain PHP code enhancing readability and maintainability of the code examples include if for conditionals for each for Loops extends for layout inheritance by obstructing these common patterns blade directives streamline template creation and reduce boiler plate code allowing developers to focus more on the content and logic of their views now we’re going to get familiar with the most common directives in LEL now let’s open resources views home index blade file and we are going to talk more about directives blade directives first of all let me remove this code from here and now I’m going to first talk about comments in Blade we can actually Define the comments we already are familiar with HTML comments which has the following syntax less than symbol exclamation Das Dash and there’s obviously the closing part of the comment so this creates a comment and in between these comments I can write some text now if I save this and we check in our browser we obviously don’t see anything if we check the page Source however we see the comment right here however there are cases when we don’t want the comment to be displayed in which case we’re going to use blade comments the difference between the HTML comment and the blade comment is that HTML comment is visible in the page Source however the blade comment is completely ignored by blade engine to define the blade comment we’re going to use double curly braces then we need Double Dash which is the opening of the comment then we write a comment single line comment for example and then we do Double Dash and double closing curly braces so this actually creates a comment and creating a multi-line comment is very similar we use double opening Cur braces Double Dash then we write multi-line comment and then Double Dash and double closing curly braces now if I save this and we reload the page we don’t see this comment right here we see additional empty lines from uh line five up to line 9ine but actually we don’t see the content which is the most important part for example if you have written some blade expressions for example outputting a name which you decided that you want to comment out you comment out this part completely and it will not be visible in the page Source now let me scroll down below and I’m going to talk more about the most basic blade directives let’s start with conditional directives if we want to write a condition in our blade file we can use it if directive it is the how every directive basically starts and if is the name of the directive so this is very similar to typical PHP if statement inside if we’re going to provide the condition for example if true then we can do something however every such type of Blade conditional blade directive needs its closing directive closing as well so in our case we’re going to provide end if with ADD symbol so whatever we write in between opening if and closing if directive this will be displayed for example this will be displayed now we save this we reload in the browser and we see this will be displayed of course if we write false here this will not be displayed I have prepared couple of slides which demonstrates the most basic directives and I’m just giving you quick overview what is possible when we actually start building the project our car selling website we will use these directives step by step in real application now let’s have a look so here we have an if directive if statement let’s imagine that we have cars array in our blade file so we check if the count of cars is more than one then we print there is more than one car however we also have possibility to write an else statement so if count of cars is more than zero there is at least one car in L’s case we write there are no cars and as I mentioned every if directive needs to have end if directive as well which which is going going to end that directive okay we can go even further and we can also have else if statements just like this is displayed right here if count of cars is more than one we’ll write something else if count of cars is exactly one we write there’s exactly one car in L’s case there are no Cars so that was all about if directive now let’s talk about unless which is actually the opposite of if directive so if you write unless false this actually will be displayed and this is the same as if true if we want to check if a variable exists if it’s a defined or not in our blade file we can use is set directive in the following way if cars variable is defined it will print is set inside paragraph otherwise it will not do anything in the same way we can use empty directive as well to check if the cars variable is empty or not these iset and empty directives are doing exactly as php’s native iset and empty functions we also have out and guest directives which is very relevant to Lal application using out directive we can check if the user is authenticated or not using guest we will check if the user is guest or not which is opposite of authentication we can also use switch directives in Blade here in this example we can check if the country is GE we display Georgia inside paragraph in L’s case we display unknown country of course we can add more cases and we can compare the country to addition country codes such as UK or us this is also very similar to Native PHP switch [Music] statement now let’s talk about four directive which is also very similar to Native PHP for Loop pay attention that every directives what we described so far has their ending directive as well for four it is end four in the similar way we have also four for each directive which gives us possibility to iterate over array in our blade template we also have one additional directive which is not available in Native PHP so this is called for else for else is very similar to for each however if the array is empty which we are trying to iterate then there is empty directive as well so in this case we iterate our cars and displaying the car model for each car however if the car’s array is empty in this case we are displaying they are are no cars and finally we have and for LS we also have while loop available in Blade which is exactly the same as php’s while [Music] loop now I want to talk about continue and break directives now let’s Imagine The Following in case we are iterating over numbers from 1 to 5 and we are displaying the number if I want to write a continue code one way to do this is the following I’m going to write an if statement if Nal 2 then I type continue which means that the following paragraph will not be printed whenever n equals 2 so n will be printed for 1 3 4 and five but not for two because we have continue code right here this is how we can use continue directive but there’s a second way which is much simpler we can replace this three line with just a single line providing the condition inside continue directive so in this case if the condition we are providing rate here equals true the continue will happen in this case and this is the equivalent of this pretty cool right so in the same way we also have break directive if we want to break when n equals four we can do this in the following way however the shorthand syntax will be like this from home controller we are passing hobes variable which is an array now I’m going to iterate over these arrays and print hobbies for this we’re going to use for each directive I’m going to iterate over Hobbies as let’s call the loop variable H and then I’m going to print H now I’m going to save this let’s check in the browser reload it and we see tennis and fishing now I want to talk about a special variable which is available inside loops and that is called Loop Loop if we try to Output this Loop variable it’s not going to work it’s not going to give us what we want because it is an instance of the class it is an object however I’m going to use DD to dump and die and this will print the loop variable and it’s going to stop the execution so we’re going to see what is this Loop variable it is an object and it has couple of properties it has iteration index remaining and so on and let me explain all of them step by step the iteration identifies which iteration the current Loop is used in and the iterations start with number one so we are dumping this Loop variable and stopping the code execution on the very first iteration so the iteration is one and basically we don’t allow every other iteration so what we can do is try to access the iteration through Loop iteration so if I comment out the stamp and if I comment out this H we save and reload we see there are two iterations the first iteration and second iteration okay now let me uncomment this DD because this is the most important thing so in the same way we have index and the index starts with zero we have remaining how many ele ments are remaining and there is exactly one remaining and so on and now let’s understand what each Loop property is actually doing so the index is the current Loop iteration which starts at zero the iteration is the current Loop iteration which starts at one there are remaining the iterations remaining in the loop we have count the total number of items in the array being iterated we have the first one and this simply returns true or false if this is the first iteration through the loop this returns whether this is the last iteration of the loop even returns whether this is the even iteration through the loop odd returns if this is the odd iteration of the loop depth Returns the level of the current Loop this is interesting if you have nested Loops one Loop into another the loop magic variable inside the outer loop will have a depth of one but the loop inside the nested Loop will have depth of Two And in the same way if you have third Loop inside the second Loop and if you have three Loops nested into each other the loop variable in the third Loop will have the depth of three and also Loop perant will return the p parent iterations Loop variable so if we are calling Loop parent on the first level of iteration like in our example if we try to print parent right here this will return null because there is no parent iteration right here however if I create a second iteration inside the first one and iterate something then Loop parent will will refer to the parent Loops Loop variable so the loop parent right here will be the same as using Loop right here of course right here we need n for each now let’s have a very quick look in the browser so we have Loop p in and let’s just print right here depth of it and I’m going to duplicate this and let’s print also Loop depth itself okay I can remove this because it’s going to throw an error now I’m going to save this and reload in the browser and look at this so we see a lot of 2121 2121 but what does this mean first of all we have two items inside hobbies and we are iterating these twice so totally there are four iterations okay so this code the line 22 and 23 will be executed four times all right so now the first output is the depth of this Loop second output is the depth of the parent Loop so this one has depth of two and the parent has depth of one and that’s why we see 2 one 2 one 2 one and 2 [Music] one now I’m going to leave this code right here but I’m going to comment this out not to pollute my output in the browser and we’re going to talk about conditional classes and styles so right now if we have a look in the browser we just see hello from Lal course which is exactly what I expect now if we go in the home controller I’m going to pass one additional variable and I’m going to call this country and in my case I’m going to provide GE right here now let’s go in the index blade let’s scroll down below and I’m going to create one div and conditionally I’m going to add some CSS classes to this so for this we can use directive called class so we use add symbol then we provide class right here and here we’re going to provide an associative array so here if I provide CSS class like my- css-class so this CSS class will be applied to the div in any case so let’s just generate lsum text so I save this I reload this we see Laur msum and if we check in the page Source we are going to see let’s reload the page uh okay down below we see this D which has CSS class my CSS class now let’s say that this class my CSS class must always be added to the div however conditionally I want to add another CSS class if the country code is GE so in this case I’m going to do the following Georgia CSS class should be added if country equals GE so now if I save this and reload we’re going to see Georgia right here because our country is actually equals to GE if we go in the home controller and change this country code into UK for example reload the page we don’t see Georgia CSS class eded right here in the same way we can add style attributes so right here on the same div I’m going to use style directive I’m going to pass an array and first I’m going to provide color to be green so this is something I want always to be added so if I save this right now and reload we’re going to see that color green was added and in the browser we’re going to also see that the actual color is green however now let’s add conditionally some styles for example background- color equals Canan should only be added if country equals g now if I save this and reload the background color will not be applied because country does not equal to G it equals to UK okay however if we change this into GE and reload we’re going to see that the background color was applied to it as well so the possibilities regarding this are endless you can provide as many elements right here inside these arrays as you want and you can provide any conditions right here you want to add or not add specific class or specific CSS properties to your HTML elements [Music] now let’s talk about how we can create and include sub views in our blade file I’m going to comment out this part I’m leaving this code so that you can refer it but when we move on the next section I’m going to remove all unnecessary piece of code and you can find them as a written form down below the lessons or you can download the source code at the end of each section and you will find these right there now let’s open resources views folder and inside views I’m going to create one folder called shared and inside shared I’m going to create a new blade file and I’m going to call this button blade PHP of course I could create this directly inside views but J just I’m showing you how you can also organize this and it is recommended to organize these partial blade files into subfolders now we have this button blade PHP which I’m going to do the following so inside here we’re going to have just a button and I’m going to Output two things I’m going to Output text and I’m going to also add background color to the button so for this I’m going to use style Direct itive and just like this background- color and I assume that we will have right here um variable called color okay awesome now let’s go into index blade and I want to include that button right here so for this we’re going to use include directive and we’re going to provide the location of the blade file so so if we would create the button blade PHP directly inside resources views we could include it in the following way button but because we created this under shared folder we need to include this shared dot button in the following way all right now if I save this and we reload in the browser we’re going to see an error because we don’t pass two variables color and text but we try to use these variables right here and this will throw an error to pass the variables we can provide the second argument as an associative array to this include directive in this case we’re going to provide color to be brown for example and we’re going to provide text to be submit now I save this now let’s open the browser reload the page and we see button so we see the button it has text submit and it has background color brown now let’s change this background color into something like yellow save and reload and now we see yellow button if we try to include a view which doesn’t exist let’s say shared search form in browser we’re going to see in error view shared search form not found however if we don’t want the error to be thrown instead of include we can use include if directive so the following directive will check if shared search form exists it is going to include that otherwise simply it will not do anything and also it will not throw an error there is also a directive include when the first argument is the condition the second argument is the the file the blade file to include and the third argument are the parameters given to that blade file include when will include the given blade file only if the first condition equals true or if the first condition is trable so in our example if the search keyword exists it is going to include shared do search results blade file however if the search keyword does not exist it is not going to include that there also exists include unless which is the opposite of include when include unless will only include shared. search results if the first parameter of this include unless equals false so in our example these two lines are equivalent there also exists include first directive which accepts an array of plate files and it will include the first available blade file so if there is admin button it is going to include that otherwise it will try to include button blade PHP first let me change this search form into button and make sure we have everything working as expected no errors and now I’m going to talk about how we can include sub views inside loop let’s imagine the casee that I want to iterate over something let’s say I want to iterate over cars as car and for each car I want to include a separate view file past the car and render each car in its own view file so how I can do this I’m going to use include directory right here provide the view name and I’m going to call this let’s assume that we already have this car. view file and I’m going to pass car right here so if we create car view. blade PHP file this will accept car for every car however we can do something similar in just one line and for this there exists each directive in Blade each accepts first it’s going to accept the view name in in our case we’re going to pass car. view we’re going to pass then the array which needs to be iterated cars in our case and then we pass the string variable name which will be passed to car view and each element from this cars array will be passed to car view with that given name car in our case so LEL will iterate over cars and for each car it’s going to render car view passing the car variable so these two piece of code what I have just selected are identical and additionally there’s four parameter also available uh which is assumed to be a blade view file which will be rendered if the cars array is empty so in our case we can provide car. empty let me quickly demonstrate this to you I’m going to declare a variable called cars but I’m going to just assign numbers to it let let’s assume this is an array okay so this is an actual array but in reality the array of cars will be array of objects but right now we just declared it to be numbers so car will be a single number and then we need to create car. viw file so if we go under resources views I’m going to create right here a file carv. blade PHP awesome so here let me create a paragraph and I’m going to Output car variable now if we check in the browser we see the following so 1 2 3 4 5 and then again we see 1 2 3 4 5 that’s because we are doing the same thing twice right here and right here however if we make this cars array empty the first one will not do anything the third one will throw an error because it will try to to render car. empty blade file which does not exist let’s have a look here we go car empty not found however if we create empty. blade file inside car folder then that will be [Music] rendered all right let me first comment out this part and then I’m going to talk about how we can use row PHP in our blade files for for example if I want to declare a variable the traditional way is going to use traditional PHP tags opening PHP tag and closing PHP tag and inside there we can declare a variable however there exists PHP directive and we use this in the following way we open with PHP directive and close with end PHP and in between we can declare variables we can create functions or we can do anything in the same way if we want to import a specific class in our file the traditional approach would be to create traditional PHP tags use and the class name however there exists use directive as well which gives us possibility to provide right here the fully qualified class name so these two piece of code is [Music] identical now it’s time for another challenge I want you to create a sub view alert blade PHP you can put this in a sub folder if you want which will take two variables message and color and use them in Blade file use style directive to add color to the alert element include that view in another blade file and pass these two variables there are many interpretations of this challenge but the main idea is that you create a second blade file include it in another blade file and you provide variables pause right now think a little bit about this create your own solution your own version of this Challenge and then come back and see my [Music] solution all right let’s see my solution how I would do this first we need to create alert blade PHP file and I’m going to do this in inside the shared folder because this is kind of reusable shared component PHP artisan make view let’s put this in the shared folder alert let’s hit the enter and it created alert blade PHP file okay let’s open this file let’s go into resources views shared and I’m going to open this alert blade PHP file so I’m going to leave this div and I’m going to assume that to two variables will be passed to it color and message and I’m going to use this color variable right here to give some style to the alert element but for style I’m going to use style directive as it is required let’s provide background- color to be whatever color has been provided however inside the alert I’m going to use message variable to actually output the message now let’s go into index blade PHP file and I’m going to include that alert include provide shared. alert and let’s provide two variables message is the first and let’s provide some message for example your account was created and let’s provide second variable called color let’s move this on a new line like this okay the color will be green and just like this we have created and included the component now if we open the browser reload the page we’re going to see your account was created alert so I can reuse this alert now multiple times I can provide a different text right here I can provide different color like red for example reload the page and we see this same blade file included two times with different text and different colors of course if we want to create like really real world type of alert component we need the text color as well and couple of other things but you get the idea we can always assume that inside alert we provide the basic styles for example color will be always white and we will also always have pting to be 15 pix let’s do like this reload the page and now we see that the color is always White and the there’s always some pading and we can provide additional CSS properties right here but the main idea is that we have variables and we output those variables now we’re going to move forward and start building the layout of our website but before we do this I want to delete all the content we created only for learning purposes such as I’m going to delete this alert blade PHP and button blade PHP so I’m going to delete the shared folder completely and if we open this home index plate as well we have a lot of content right here so I’m going to completely delete almost everything from here and from the home controller as well we can remove all these variables given to home index and just like this we have now clean project and we are going to work on index blade to actually render the content of our website the website we are working on now let’s create the main layout file using Artisan PHP artisan make View and I’m going to put that layout file under layouts folder and I’m going to call this file app so it’s going to be up blade PHP under layouts folder so this is created now let’s go under resources views layouts and let’s open this up blade PHP I’m going to remove everything and I’m going to generate boilerplate HTML code so we have the standard HTML structure you can generate this code by just typing exclamation mark in your PHP stor or vs code and hit the tab okay awesome now let’s start using blade directives right here the title is a document which I don’t want to be documented I want it to be something Dynamic okay so here I’m going to use yel directive and I’m going to provide right here name so that’s going to be section name so I’m going to type title right here so I want to Output the content for Section title and I’m going to right here provide extra hardcoded text like car sell L website you can put the name of the website whatever you call it okay or you can even leave this empty and just only have this title so the choice is up to you the most interesting part is that right here we are trying to Output the section with name title okay so I’m defining the layout and the layout needs header so I’m going to Define header right here and we can just type a hardcoded text like um your header so this is just your header okay so I’m going to Define footer as well and that’s going to be your footer and in between the header and footer we’re going to obviously have the main content again I’m going to use a yeld directive and I’m going to Output a section with the name content so I have the very very basic layout ready now let’s go into index blade PHP file and I’m going to try to use this layout let’s delete everything and we want to extend the layout we want to use this app blade PHP file in our index blade how can I do this extends except the blade view file name our blade file is located under a layouts folder and it is called app just like this we are extending our app blade PHP so even if I leave this right now as it is and I don’t do anything and if we check in the browser we see your header and your footer and if we check the page Source we see this very very basic HTML so we don’t see anything right here we don’t see anything in between header and footer but the basic layout is already rendered because of these extents but because we are extending we want to actually extend it and add additional things to this layouts up for example I want to define a section with the name title and we can provide right here any text for the title like home page for example I save this I reload the page and we see homepage right here because we defined the section right here title and that section title was outputed in the layout our definition that text now is outputed in layout awesome we also try to Output right here section called content now let’s define this section section however there are two ways to Define content for the section one way is to provide two parameters right here the first one is going to be the section name the second is going to be the value for the section so I want to Define much larger text than just a single line so we have possibility for this we just provide the section name and then we use end section and whatever we put inside in between the section and end section that’s going to be considered as a content for this section so in our case I will just type homage content goes here and let’s fix the typ hole and maybe we can put this inside H1 awesome now I save this I reload the page and we see in between header and footer we see this H1 of course you can put HTML of any complexity any html text as much as larger HTML as you want you reload and you’re going to see the whole HTML okay awesome and now if we check in the browser we see homepage content goes here in between header and footer okay we have the layout ready but we want to improve this layout for example if we look at the HTML link property we see en right here so we have language English defined always but what if our application is in different language let’s say Spanish I want this language to be dynamic based on the applications language also we see right here car selling website which is actually kind of title of our website but we already have this title written in file if we go under en and open this we see application name right here we can call this whatever we want for example we can call this car selling website or let’s just call this Carell okay so this is the application name and I want to Output the application name right here how can I do these things first let’s go into link and I’m going to Output right here the current application name I’m going to access this through up function this returns an application and then I can call get local method on that so if I save this right now and if we check in the browser Source we see if in right here so our current application language is actually in English if we go right here and change the application local into es for example then we reload we’re going to see es right here which is exactly what we want however the language codes can be in different format for example it can be escore uppercase es for example so we don’t want underscore written in our language program property so it’s a recommended practice to call St Str replace to search underscore in the language replace it with a dash and output only this information so now if I our language code is escore es the output will be es- es which is relevant for the link property okay this is one thing what we want to do I’m going to reverse this B into en next we want to Output the application name right here for this we can use config function in the config function we need to provide the configuration name and the configuration name is called app. name all right so where does this come from if we go into config folder open up PHP scroll at the very top we see application name which is taken from Ian okay from Ian whatever is the app name it is taken and inserted in the application name that’s why we are taking up name right here however we can fall back this to something else like LEL of course the fallback will never happen because we have that name defined right here in the and we also have fallback right here so application name will be always something but again this fallback doesn’t hurt it so it’s a good practice to have basically it is a method to prevent attack from Another Side to your website so it’s good practice to Define and we will need this as well so the name is going to be csrf Dash token and we’re going to provide the content for this token as well the content needs to be a result of the function we are going to Output csrf token function result now if I save this and if we reload we see right here csrf token metat tag and we see the content so this is unique string which regenerates once in a while and it is only valid for your website so if other websites will try to send information to your website without this csrf they will not be able to do this again we will talk more about csrf in the upcoming lessons and here we see the language as we talked and here we see the application name if I open p. file and change this application name for example if we call this car selling we save we reload we see application name changes right here as well make sure you download and open the HTML CSS project that has been provided under this video when you open this using vs code make sure to install live server extension as well we will need this to open this HTML project in in the browser so let’s open index HTML file and we can click go live button right here this will start the live server and we can browse and view this website in the browser here’s the website and how it looks like and now I want to take the layout from this HTML template and put this in our LEL project I’m going to copy everything from this index HTML let’s open our project and I’m going to insert this content just below the stock type HTML I don’t want to delete this HTML for now I’m just putting this at the very top I can put in create multiple new lines and let’s put this right here so this is a very long 800 line HTML content and we have to identify what is part of the layout right here and what is part of the actual view because this is an index page and index page contains not only layout but it actually contains the cars as well now let’s identify what is part of the layout and what is part of the content so if we start from this top so this is all part of the layout including the links including this header so this is also part of the layout let’s collapse this then we have this home slider this home slider is already part of the homepage so I’m going to take this out cut it and let’s put this inside index blade PHP inside content right here okay I’m going to paste it good now we have this main tag inside which we have a couple of sections we have to find a car form we have new cars section and that’s basically it so we need to take this entire main tag and put it in the index blade right here awesome let’s go into up blade again we can remove this extra new lines and then this is part of the footer and that is part of the layout so everything what we see right now is part of the layout now what we need to do is to Output the language right here output the proper CSF token output the application name as well let’s do this down below we have this old HTML so I’m going to copy this HTML tag let’s scroll at the top and put this right here next we also have csrf token I’m going to take this let’s scroll up and just below the title tag I’m going to put this here and finally we have this title so I’m going to get this and put this right here okay and in between the header and footer we need to also output using yel we need to Output content just like we had in the previous version okay now we don’t need this previous version so we are going to remove it completely let’s remove this extra new lines as well cool now we have this HTML ready however it’s not going to display nicely because we don’t have Javascript file and we also don’t have our main CSS file in our project but before we proceed let’s have a look on our website so we see bunch of content okay so we see this hero text and we see uh the search form and we see cars without any Styles because the CSS file is missing and if we check also the page Source we are going to see this entire HTML content including this header and home slider and all those cars okay this is pretty awesome now let’s inspect this and let’s have a look where the CSS and JavaScript files are coming from so if we reload the page we are going to see that it has CSS up CSS missing JS upjs missing and couple of images as well what we need to do is take those CSS image and JS files and put them in our project now I’m going to open this using Explorer File Explorer so right click on folder reveal in file explorer this opens the file explorer and here we see CSS image and JS I’m going to select all of them and I’m going to copy them and let’s go into our project and we need to put them under public folder we will improve this later but for now we’re going to put this in the public folder again I’m going to right click inside the public folder in PHP storm there’s open in Explorer in vs code it is reveal in Explorer I’m going to open this in Explorer here it see here is the public folder and I’m going to paste it right here now we have the CSS image and JS in the public folder I can close this they will be available right here as well and now let’s recheck it in the browser reload the page and we don’t see any errors in the console let’s close the console and we see I need to zoom out slightly and we see the homepage it is very identical to the HTML file what we just saw so because we successfully moved the layout part and the homepage part in our project if we have a look at the HT HML CSS template and navigate between Pages we see that the header is the same so the following page at new HTML has the exact same layout as the homepage we also have car details page and this one also has the exact same layout however if we go into signup page we don’t see this header anymore so this page has a different layout and this page has the same layout as the login page so if we think a little bit we can identify that we have two different types of layouts in our project the one which is related to the pay website like the homepage car details a new car and so on and the others which is for sign up which is for login or maybe for password resit so we actually have to create two different layouts let’s open the HTML CSS project and I’m going to open login HTML file and I want to compare these two files index HTML and login HTML so we already saw index HTML so it has all the links and uh the header right here as well which I’m going to collapse right now however in the login HTML we have all the CSS files we have these links but we don’t have this header then we directly have this main section so if we observe a little bit we can identify that everything what is above this body opening tag inside login HTML and inside index HTML is actually the same also in the index HTML we have this footer down below which is at the moment empty but on the real websites we obviously have some sort of footer right on loging HTML we don’t have this footer if we scroll down below we directly see this script tag which in index HTML only comes after the footer so if we select right now I’m going to select the content this content is not available in login HTML and if I delete this for just temporarily we can identify that now this looks very similar to login HTML so this is the content inside login HTML we can delete this and these two HTML files are almost identical except that we have additional CSS class to the body inside login HTML so I want to create now one layout which will be a basic layout only contain CSS in JavaScript files it will not contain this header tag and then the second layout will have this header tag let’s open our project I’m going to bring up the terminal and I’m going to execute PHP artisan make view layouts. clean I’m going to call this layout clean layout let’s hit the enter the file was created let’s go under resources views layouts and let’s open this clean blade PHP now let’s open up blade PHP and I’m going to copy the part which should be part of the clean blade PHP everything starting from the stock type HTML down below the opening body tag so I’m going to copy this part or cut this part remove it from up blade PHP and I’m going to delete everything from clean blade and I’m going to paste this right here now let’s open up blade PHP again I’m going to leave this header I’m going to leave the content and footer and I’m going to take this part which should be part of the clean layout as well so let’s go into clean layout and down below I’m going to paste this okay now we have this clean blade PHP which has this uh outputting of the language csrf and the application name as well and right here right here in this place we want to Output the its nested layout child layout content so in our case case that should be up blade PHP content so that content should go inside here right in this place so for this I’m going to use Yi and I want to Output child content so I’m going to call this section child content now let’s go into up blade PHP and first we have to extend the clean layout so we use extend directive layouts. clean awesome next we have this header and we can leave this then we have we have to define the child content section because right here the clean layout expects child content section let’s go into up blade and I’m going to Define section child content and in between the child content opening and section in between the child content opening and closing directives I’m going to Output the actual content as well however this header and footer should go somewhere as well right so they should be inside this child content as well so I’m going to take this header and put it in the child content take this footer and put it in the child content as well now let’s remove this extra new lines let’s save it and before we check the result in the browser let’s understand the flow again index blade which is the homepage extends the up layout this is the up layout it extends the clean layout this is the clean layout clean layout outputs child content right here and it also outputs um title right here as well so in up blade we Define the child content with a header we outputed the content which will come from its child view index play PHP so this content right here will be taken and inserted here in the following place and this content will be taken and inserted here in the following place and finally when we access index Blade the homepage we should see the correct result let’s save this and let’s check in the browser I’m going to reload the page and we see the same result let’s check the page Source let’s scroll at the very top and here we see the title we see language we see the header as well and down below we see somewhere probably footer as well if we open uplate PHP we see that the header tag is about 70 lines of code of course we can leave this right here but it is also good practice to move that into its own blade file so I’m going to cut this I’m going to open the terminal and I’m going to execute PHP artisan make View and I’m going to create under layouts I’m going to create another folder called partials and inside there I’m going to create header view file so the view under layouts partials header blade was created let’s go let’s open this I’m going to replace the content with the header tag and inside Apple blade I’m going to include layouts arals header blade file now we see that we only have seven lines of code in up plade which is how it’s supposed to be if our footer gets very large we can put this in its own partial file as well so we save this if we check clean blade as well uh this only contains the CSS and JavaScript files nothing else the header obviously contains only header which is exactly how it’s supposed to be and we have perfect setup of our layout let’s check the resle just to make sure that we don’t break anything we still see the header right here the reason why we created clean layout is that it is used inside login sign up or password reset pages so we have to create signup page and login pages and we have to use this clean layout right there let me create signup controller by executing PHP artison make controller sign up controller we hit the enter the controller was created let’s go under up HTTP controllers we have the signup controller and I’m going to create right here at the moment I’m going to create only one function create which should render the form so we’re going to return view okay um I want to render the view from a specific folder called out out sign up so this is the view I want to render let’s open Terminal again and let’s create new view PHP artisan make view out. signup we hit the enter the view was created let’s go resources views out sign up blade now let’s open the HTML project and let’s open sign up HTML okay let’s scroll down below and find the content section we identified what is layout and what is part of the page so here we see the main is part of the page again we have to take care of this page sign up class maybe but let’s take this main tag because this is what contains the actual form let’s go in our PHP storm and I’m going to delete everything and I’m going to paste right here this main tag okay good now we have this um sign up blade PHP but that needs to extend clean layout okay just like we are extending layout up on homepage and we Define the title and the content we have to extend the clean layout and Define the title and child content because the clean layout is using child content so let’s open signup blade let’s collapse this Main and we are going to extend from layouts. clean let’s define section title with signup title and let’s define section chart content and we obviously need end section as well okay awesome now let’s open web.php from Roots folder roots web.php and we have to Define new root for sign up root get sign up and we’re going to use sign up controller class create method let’s let’s replace this fully qualified name with import so that we have signup controller imported right here and just like this we can already have a look and see the result let’s provide sign up right here hit the enter and we see the sign up page which is pretty cool if we have a look in the HTML template we can see that the body has page signup CSS class this is something which is missing in our case so if we check our website we see the sign up page but if we inspect this check the body we don’t see the CSS class however if we check right here we see that it has this page signup class which adds additional ping top and bottom so we want this ability to add this page sign up CSS class to inside clean layout and it’s pretty easy much easier than you think so we extend these layouts clean right here and we also have possibility to Prov additional parameters right here for example we can provide CSS class which needs to be page Dash sign up now if we go in the clean layout we can use this right here we can do like a check if the CSS class exists or not or we can assume that it always exists and we can simply output CSS class if I save this right now and reload on the page we’re going to see page sign up CSS class was successfully added to body so in our example if we want to be 100% safe and make sure we don’t try to Output a variable which is not even defined we can do something like this we can use is set directive for this which we already mentioned in previous lessons we provide CSS class if that is defined we output it and we need end is set as well and just like this the result will not change we will still have this page output we also have additional extra white spaces in front of the class after the class which can be removed if we remove these white spaces right here awesome now we don’t have that however if we try to if we just forget to provide that CSS class and remove this completely it will not throw an error it simply will not use that class however as you see we see empty class attribute right here which we can also prevent if we go right here and if we move that class only if the CSS class is defined and we move that double quotes right here as well so now pay attention so the following content will only be rendered if the CSS class is defined now I save this reload and we don’t even see this CSS empty attribute but now if we go in the sign up and revert this back we save and reload we see this CSS class [Music] added now I have a challenge to you and I want you to promise yourself that you will do your best to implement this challenge only by yourself and you can check obviously my solution if you need but do your best to do this on your own and the challenge is the following it’s pretty simple in my opinion because we already did something similar in the same way like we created sign up page I want you to create a login controller new login route and copy the login form content from the HTML CSS project template project into your LEL project and create a login page on/ login URL so whenever we try to access SL login it should render the following login form coming from the Lal application pause the video right now span time and then come back and see my [Music] solution all right I hope you made it and now here’s my solution let’s first open HTML CSS project and let’s open login HTML we are going to copy this main tag which is the main form now let’s open our project and I’m going to create the controller and view file PHP artisan make controller login controller hit the enter PHP artisan make view out. login we hit the enter so the controller was created view was created now I’m going to hit double shift on my keyboard which gives me possibility to access through all my files you can hit contrl in p in vs code to do something similar so I’m going to open login controller file then I’m going to create the function create from here I want to render a view al. login now let’s open the view file which should be inside out slash login which we just created okay awesome I’m going to delete this div and I’m going to paste this main div what I just copied from the HTML CSS project I want to extend this from layouts. clean I want to Define section title login and I want to Define section child content let’s collapse this div and here we need end section as well let’s remove this extra new line and right here in this layout clean I want to provide the CSS class page- login oops we need key right here as well CSS class will be page- login now let’s open web.php and I’m going to duplicate this line and I’m going to Define login rout which should use login controller let’s replace this with import we have login controller imported right here and we need to use the method called create now we save this let’s check in our browser reload the page and we see login page we see one error which is coming from JavaScript it it is not that important we can close this and uh the main thing is that if the CSS class is available so let’s check this page login we see that so our login form coming from LL exactly looks like the login form coming from the HTML CSS project [Music] there are several more useful cases when working with Section related directives let’s open the layout up blade PHP here we have the empty footer tag now let’s assume that inside this footer tag we want to Output footer links for this we would use yel directive and let’s call this section footer links whenever that footer link section is defined the links will be outputed right here in this footer now let’s open index blade PHP which is the homepage and inside this content I want to define a section let’s define section Hooter links we obviously need end section and here I’m going to Define two links I’m going to Define link three and Link four and you will know right now in a few seconds why I defined link three and Link four and where is link one and Link two okay I’m going to save this and when we reload the browser we’re going to see link three and Link four at the very bottom left corner of the screen we can check this in the page Source we can zoom in and here inside the footer we see link three and Link four now let’s assume that we want this link one and Link two to be for every page now we provided this link three and Link four for homepage only if we go to another page those links three and four will not be there now I want to Define link one and two for every page okay so in this case I’m going to change this yel into the following so let me remove this completely so here we need to define a section footer links okay but instead of calling right here end section we want to call show directive so whatever we put right here in this case we’re going to put link one and Link two so the section will be defined but it will be also outputed so this is pretty much equivalent of calling end section right here and then calling yel with footer links so this is pretty much the same as a having show right here and of course this is much better so now if I save this and reload in the browser we still see link three and Link four why do we see this and Where’s link one and Link two if we don’t Define this section at all in index blade and I’m going to comment this out we are going to see link one and Link two in footer because we didn’t Define it and it took the default values whenever we Define that our content made an override of these two links however what we want is the combination of Link one two three and four how to do this for this we are going to use right here a directive called parent and we can use this parent in any place we can use it here we can use it here or we can use it here so it’s up to you where you want to use it in this case we’re going to put at the very beginning of the section and now this print will take the content of the parent section the parent section in our case is this so link one two and then three and four will be defined and will be printed in our browser and you see the [Music] result there are several more direct which are definitely worth mentioning one of them is his section his section directive checks if a specific section is defined or not and let’s see this on our example I’m going to remove this default content right here and let’s say that I’m just yielding footer links right here so if we open the homepage reload this we’re going to see link three and four because this is how we Define in index blade cool but if you don’t don’t Define these footer links I’m going to delete this completely then the footer empty tag is still rendered and let’s say that we want to avoid this if the footer links are not defined we don’t want the footer tag to be defined or it to be empty so how to do this let’s go into up blade and before yiing we are going to check if footer links section exists it if it is defined if that section exists then we’re going to use at the end we need to finish this with end if directive and inside the head section and end if we can put this footer so if the footer link section is defined we Define the we create this footer and output the footer links but if it is not defined we don’t even show this footer tag okay this is awesome now if we reload the page in the page Source we don’t see the footer tag at all however if we open index blade and uncomment these footer links we save we reload we are going to see footer with the links the next directive worth mentioning is section missing using this directive we check if a specific section is missing or not in our case if the navigation section does not exist then inside D with class pool right we render the default navigation using checked directive we can add checked attribute to input type checkbox or input type radio the check directive accepts a Boolean expression if the Boolean expression is false then checked attribute will not be added to the checkbox or radio button however if the Boolean expression is true then checked attribute will be added and finally it will be rendered with checked attribute in HTML in the same way there exists disabled attribute if it is a false the disabled attribute will not be added if it’s true it will be added in the same way there exists readon which will add or not add readon attributes to HTML input elements in the same way there exists required attribute which will add or not add required attribute and there also exists selected directive which will add or not add selected HTML attribute to option tag on the example what we see right now we are iterating over yards and whichever is the current y we are adding selected attribute to that option so in our case 2024 this is the current time when I’m recording this course to option with value 2024 will get this selected attribute the other options will not get that in LEL components are reusable piece of user inter interface that can be included in your blade views they encapsulate HTML markup Styles and logic into a single unit making it easier to manage and reuse code components can accept data as attributes and can include slots for more flexible content insertion lell provides two types of components class-based components and Anonymous components now let’s learn how to create Anonymous components first Anonymous components components are blade files located under specific folder inside resources views I’m going to create a new folder called components inside components I’m going to create a new blade file called card blade PHP this is a blade file and inside here I’m going to create a div and let’s give it a class card inside here I I’m just going to write a lurm Ipson text at the moment so this is a component because it leaves under a specific folder inside views now let’s see how I can use that component in another blade file let’s open Home index blade PHP and let’s try to use it right here at the top of the content section components can be included as HTML tags every component tag starts with ex dish so in our case ex dish card will be the component we want to include the components can be self closing text like this or it can have a separate closing tag like this so we have card component created and we have included this right here let me change this into self closing version now if I save this and if we ch check the browser here is lurum text which is coming from component if I duplicate this component couple of times I will see this lsum text repeated couple of times as well components can leave in sub folders as well for example if I copy this card blade and I’m going to move this into a subfolder of the components let’s create a subfolder and I’m going to call this let’s call this admin folder for example if we have a separate card component for admin I’m going to move this right there and I’m going to change the text right here and I’m going to call this admin card component now I save this let’s open index plate PHP and I’m going to use this admin component in the following way x- admin do card and then we have sell closing or we can have a separate closing tag so in this case the admin defines the folder and card is obviously the component name we can have deeply nested components we can create another folder inside admin and call it for example bootstrap and we would be able to render the card component from the bootstrap folder in the following way admin bootstrap card but every component starts with ex and dash of course this component doesn’t exist so it will show an error so so let’s just remove this bootstrap I would save this and if we check in the browser we will see right here admin card component to create the component using Artisan we should execute the following comment PHP artisan make component then we would provide the component name card and we can provide an optional flag D- view which will generate Anonymous components we are talking right now about Anonymous components we will talk about class components in the next lessons and using the following way we can create new component because we already have card component available this will not work and this will throw an error so let’s just change this and call it button when you are creating Anonymous component it really doesn’t matter how you name your component with uppercase b or lowercase B it’s still going to create blade file with all letters lowercase if we hit the enter the component created successfully we can check inside views components we see button blade PHP if we open this we see right here deal with a comment and we can change this into button with submit text for example we open index blade and we can include this in the following way x button now we save it we reload and here’s the button component if we want to create a button component inside admin folder we will do it in the following way admin. button let me remove any unnecessary files like this button blade I’m going to delete this I’m going to delete the admin folder also from the components so we know that we can put the components in a subfolders that’s clear we have this card blade and we are using inside index blade PHP P however we have this x button and X admin card as well which I’m going to also remove here we are using X Card component three times and if we check in the browser we see three times the same content would not it be great if we would have the possibility to customize the content every time we are using the excard component that is possible through component slots a component slot is a placeholder where you can insert custom content when you use the component it allows you to pass different pieces of content into predefined sections of a component making the component flexible and reusable there are two types of slots default slots and named slots now let’s see an example of default slot I’m going to open the card blade component and I’m going to remove this LM iom text and I’m going to use preserved variable variable called slot I’m outputting that variable inside in between the opening and closing html text now I’m going to open this index blade and I’m going to change how I’m using the EX card instead of using with self closing tag I’m going to have a separate closing tag right here and in between I’m going to write some content like card content one and now I’m going to duplicate this two more times and we’re going to have card content two and card content three now let’s delete these self closing versions now I save this and if we reload in the browser now we see card content one card content two and card content three that happens through slots whatever we put in between X card opening and closing text that will be taken and rendered instead of this slot variable right here now let’s talk about named slots there can be only one default slot however there might be multiple named slots now let’s update our card component into like this I’m going to create two HTML elements card header and card Booter inside card header I’m going to use use a variable called title and inside cart footer I’m going to use a variable called footer awesome so those variables by default do not exist and if we try to reload the page we are going to see an error undefined variable title which is obvious now let’s go how we use this excard component and I’m going to Define named slot to provide content for named slot we should use ex slot tag so I’m going to use ex Dash slot okay then we can provide the name of the slot so I’m going to give it title and then card title one so in the same way I’m going to Define X slot with name footer card Hooter one now I’m going to comment out or maybe completely remove these other cards and I have this single card with title name and footer name for slots this name given right here title and the footer name given here will be converted into a variable’s title and footer right here so if I reload the page we will not see error anymore instead we see card Title One content and card footer one instead of providing name attribute right here there is another version to provide content for title slot I’m going to delete this name and we can do in the following way x- slot colon title and x- Slot colum footer let’s delete the name here as well so whatever we provide next to this column right here that’s going to be converted into to a variable in our component okay if I don’t provide title and if I provide title two for example we will probably see an error on title because there is no title however we are trying to print that now this works exactly as it should work if we want to check if the default lot is empty or not we can do this in the following way the slot provides a method called is empty and we can check if the slot is empty empty then we can render some content else we can render the slot actually and just like this if we don’t provide anything any information in the default slot let me remove this completely then it will render the message please provide some content right here however if we provide this card content one reload the page we will see this card content one now let’s create class-based component PHP artisan make component let’s call this search form and pay attention right here that I start the naming with uppercase C and then I have F also uppercase so we have to name our class-based components with Pascal case every first letter of the word word needs to be an uppercase and we also don’t need to provide Das view we hit the enter and it created the component pay attention that the component was created under up view components search form so this command created two files one is under up view component search form and second is under resources views components search dish form okay cool now what is the purpose of this class class-based components give you a possibility to override the default location of the blade file by changing The Following part right here so inside render it is rendering component search form which we can change easily if we don’t want that place also if you have very complex logic of selecting data that you want to render in your component you can put this in the construct ctor right here we can also Define public methods right here let’s define test return something which can be used then inside the component in the following way dollar sign test and parenthesis so this test right here is available as a variable but because it is a function then we use the parenthesis right here now let’s open index blade and let’s include this search form component maybe next to the card I’m going to use x dash search- form okay so we save this and now we check in the browser and we see something and that something is coming from here from this method test now let’s open index blade PHP and I’m going to find the actual place where we have have this search form so this is the home slider I’m going to collapse it inside main we have this find a car form so I’m going to get this completely go inside search form and replace it right here and then in the index blade I’m going to use this ex search form like this now if I save and reload down below we see this search form which is coming from the component if I go in the component and delete everything this form will be gun as you see it is not there anymore this is pretty handy because right here in this search form we will need to have options for um maker maybe for model for States and all that information can be selected inside search form which will be available inside the component any public property or public method what we describe in the search form will be automatically available as a variable inside search form blade PHP we have the following search form class based component which has its own Associated blade file now let’s assume that whenever we use this search form component from here we’re going to pass action and method then we’re going to take this action and Method and we’re going to Output those two variables right here this can give us possibility to provide different actions inside the search form when we use the component from different places okay how we can pass those attributes and render them let’s open search form PHP and right here in the Constructor I’m going to accept two properties public string action and public string Method All right we Define those properties and they are both of them are required right now if I reload the page we’re going to see an error required string action so we have them required but we don’t pass them from here now let’s provide action equals something and Method equals something something now if I reload the page the error will be gone so we pass those two attributes we accept them right here but we don’t use inside the blade file now let’s replace the following part of the code and output these two variables action and Method Keep in mind that any Global variables any Global properties inside the component class and the global methods are directly available in the blade B that’s why because we have this action and Method defined as public properties we can directly access them under search form blade file now if I save and reload we don’t see any error and if we check the page Source if we search for form we’re going to see action is search and method is get and just like this we provided those two properties right here we can change it and just leave DH SLS and we can change this into post if we want preload the page and we’re going to see it like this however if we don’t want these properties to be required we can provide some default values for example search and get now this gives us possibility to not provide none of the properties or we can provide only one and for the second one it’s going to take the default values but let’s leave it like this reload the page and it’s going to take take the default Valu search and get and we don’t see any errors because we have provided default values for these [Music] properties now let’s open card blade PHP which is anonymous component and see how we can pass attributes to Anonymous components let’s open index blade and right here we are using this EX card Anonymous component let’s provide color equals red for example and in the anonymous component blade file we can already access the variable named color so whatever attribute we’re giving right here that attribute will be created as a variable in the blade file so let’s just output here color we save and we reload and right here we’re going to see red okay this is what we provided obviously we can provide any number of attributes right here and for all of them the variable will be created however there exists a specific dedicated directive to define the properties of the anonymous component and the directive is called props so we provide array right here and inside the array we’re going to Define what properties we’re accepting inside this Anonymous component so I’m going to accept color and I’m going to accept BG color right here okay so I expect these two properties to be passed to the uh Anonymous component however now you might have a question what’s the purpose of defining the props if we can just directly provide the color or PG color right here and we can accept them right here in the following place and we can display them that’s a good question there are couple of reasons one of the reason is that when we Define those props we have an explicit view of what properties are defined and are used inside this component that component might be multiple lines dozens of lines and we Define those props at the top on it’s a recommended practice to Define them on the very first line of the component okay and when we have a look on the very first line of the component we immediately see what properties this component accepts that’s the one thing and the second reason why this is a good practice is that we can provide default values for example on the BG color I’m going to provide the default value to be white and whenever the B color is not provided is not passed it’s going to be white so now let’s use this color and BG color right here card Dash text Dash and let’s use color variable here and then I’m going to add a second class card BG and let’s use BG color variable here now if we save and reload and I’m going to check the page Source let’s search for card and here we see that card text red card BG white the card text red is given because we are providing a color righted here and BG white is because we don’t provide BG color from here but we have the default value for BG color however we can obviously provide BG color here to be blue for example we save we reload and we see blue right here when we provide directives we can provide the attribute names with camel case notation like it is defined right here in the props or we can provide the T notation as well BG Das lowercase C color so this will also work we reload we still see blue right here however if we just provide full without without Dash but the C is lowercase still this will be a different variable and if we reload in the browser we are going to see white because right here we are using BG color with camel case naming and we don’t provide anything with camel case naming so that’s why it is taking the default value for the B color okay so far so good what if we want to provide variables right here let me Define two variables using PHP directive so one of them will be color let’s give it red and the second will be B color let’s give it blue so I want to use these two variables right here so we can use directly dollar color here and dollar BG color however those text will be evaluated as hardcoded texts not as very variables if we want them to be evaluated as variables and the values to be passed inside the attributes we’re going to use column in front of the attribute name so if we save it like this and reload the page we’re going to see now card text red and card BG blue this is exactly how we want and there is a shorthand version of the following line so I’m going to duplicate this line and I’m going to comment it out and we can have have a shorthand version whenever the variable name which we are passing matches the attribute name exactly we can do it in the following way so we can remove the value and we can use the dollar sign here and this is equivalent of this code and in the same way we can do for B color we can remove this part and now the following line is equivalent of this line which is pretty cool so if you want to use this shorthand version that’s good however if you have a different named variables like C right here and PG right here obviously you cannot do like this then you have to provide C right here and BG right here okay let me quickly undo this because we have now the same naming of our variables and now let’s test this in the browser reload the page we see right here and blue right here [Music] in components we have access to predefined variables called atributes so this is an object and we need to print this using Dum and let’s have a look what this variable looks like let’s reload the page and we see this is component attribute and beg so which has attributes property right here and it is empty array at the moment however if if I comment out this part save and reload we’re going to see that the inside attributes now we have two elements so one is color red and second is B color so the whole idea of the compute component attribute bag is that it contains all the attributes we provide whenever we use that component and it is excluding those properties which is defined using props directive so in our case we provide two properties right here color and V color but we don’t have props defined anymore we commented that out so it is taking all given attributes from here and inside attributes we have that all of them so if we provide right here language for example L equals n we save we reload now we’re going to see three attributes and languages inside there as well however if I now uncomment this code and we Define color and B color so then color and B color will be excluded from here so let’s reload we see only one attribute this is language for those attributes which is defined right here it is creating the LEL blade is creating separate variables for them however what is not defined using props it goes inside attributes and that is very good because we can use that attributes actually and we can output it right here in the following way let me remove this time so I save I reload we’re going to check inside the page source and right here we see link so the two string method of these attributes object is implemented in a way that it outputs the attributes properly as they should be outputed we can also provide test right here to equals something we save we reload and we see language and test output it right here so this is pretty cool now instead of test let me provide right here class and I’m going to add additional class let’s say card- rounded so this CSS class actually doesn’t exist I haven’t created any kind of styling for this specific class but that is not the main thing the main thing is how that CSS class will be added to the element so if we save this right now and reload in the browser look at this we have something something strange we have class card rounded and then we have another class so this card rounded is coming from the attributes if we go right here we are outputting everything from the attributes and class is inside that attributes however we have that second class right here which is what we have defined right here so in our case what we want is to merge the classes defined right here to the classes what will be provided to that element so this is how we can do this so instead of outputting attribute separately and outputting right here class separately on attributes we can use method called class this class accepts string and that should be the classes what we want to Define inside here so I’m going to take out these classes I’m going to delete this class attribute and let’s put them right here okay however pay attention that we need variables inside here let me use double quotes so we are going to use color variable here let’s delete these curly braces because we have a string here okay also so we have this card then CeX with color and cartex with BG so these are the classes which will be merged to class attribute given to this element so the card rounded will be merged to this one and then all the attributes will be outputed now if I save and reload we’re going to see we have language as well but we have all the classes merged into a single attribute so this is pretty cool in my opinion attributes object also has method called merge we can chain class method and merge method together but the purpose of this merge method is to merge the given attributes to the default ones we provide right here so for example if we don’t provide a language attribute right here let’s say that we want the default value on the card the Lang language attribute to have Ka which is the language code for Georgia so we’re going to provide right here inside the merge associative array where the key is the attribute name and the value is the default value k a right now we are providing language attribute so it is going to render the English however if I remove this save and we check this in the browser we’re going to see the language will be Ka so using the following approach you can Define the default attributes which will always be merged with the attributes given to your component if you use the following syntax this merge obviously can be used before the class method or after the class method it really does not matter the main thing is that it merges the attributes defined right here to the one given to the component here we are using card component and we have two slots defined title and footer now let’s assume that I want to add additional attributes to title or footer HTML Texs so let’s provide right here class for example and I’m going to give it card header blue now let’s assume that I want the following CSS class to be added to an HTML tag which renders the card header if we go in the card component we’re going to see that we have right here card header inside which we render the title so how we are going to take this class given to that slot inside here so the title basically is a variable which outputs the slot content in our case it outputs this card title one but actually it is an object and if we simply print using dump what is title we are going to see the following result so it it is component slot which has its content and it also has attributes and this attributes is instance of the exact same class we used previously right here the attributes okay so now what we can do is to access attributes title attributes and we can use that title attributes right here instead of this class so we can use title attributes we can provide class method right here in the same way we are doing exactly right here and we can provide card header CSS class now let’s move this down format it nicely let’s remove this dump and let’s just leave title as we had previously now when we save and reload if we check we see card header and card header blue this is exactly what we wanted of course if you need you can also use merge method on this title attributes in the same way we are using right [Music] here by default there are some keywords reserved for blades internal use in order to render components the following keywords cannot be defined as public Properties or method names with in the component for example if we try to Define right here method with a named data which should not be defined and then if we try to use that method in the blade file call the method and try to print the result in the browser we are going to see the following error argument number two data must be type of array string given something which is not very clear but this is because we made an override of existing data method which should not be done so whenever you come across error similar to this just check what are the reserved keywords and make sure that you don’t have any public Properties or methods defined with these [Music] names inline component is a component which does not have its Associated blade PHP file and the HTML content is returned from the components class render method directly now let’s execute the following Artisan command PHP artisan make component test component and we’re going to provide the flag D- inline we hit the enter the component was created let’s open the test component and here we have this render method from which we are returning HTML so inside this HTML every blade directive is supported we can use right here predefined variable called attributes we can also use slot right here the default slot or name slot any directives any blade can be written right here inside the string now since we have that defined let’s open index blade and let’s try right here to use this test component we’re going to use it in the following way X test component it’s pretty identical how we are using in general I’m going to provide some content inside there and I’m going to also add CSS class now because we are outputting all the attributes right here we are outputting the default slot we should see this rendered now let’s check this in the browser we reload the page and we see lurm ipsum right here and if we check in the page Source we are going to see the card right here as well so the CSS classes or any attributes we are going to add right here will be outputed on the HTML element on this T right there it is not very common to create and use inline components without blade files but still I wanted to show to you that so that you know that this is available we already have defined layouts and layouts are defined using template inheritance now it’s time to refactor our code and we are going to generate components and create rebuild our layouts using components let’s bring up the terminal and we’re going to create two components PHP artisan make component I’m going to call the first one up layout hit the enter and the second one is going to be base layout so the up layout will be the layout which will be for the homepage for example and the base layout will be the same as the clean layout What the clean layout does just I think the B layout describes it better that’s why I simply decided to call it base layout awesome so we have those two component classes now when we generated these components actually it generated two files for each component we have under up view components we have up layout and base layout but for each component for each class we have also View files up um up layout blade and BAS layout blade so what I’m going to do is just delete these components okay so we don’t need these blade files but we need to use these two blade files up blade and clean blade okay I’m going to also rename this clean blade and call it base blade let’s do refractor and now let’s open up layout and here is the components up layout blade file specified which I’m going to change into layouts up so this is the location of the blade file or the corresponding component let’s open base layout and I’m going to do something similar layouts base okay so we have the component classes ready we gave the correct names to the blade files now we are going to work inside these blade files so let’s open up blade PHP and Bas blade PHP so there are two approaches the first approach is to copy everything from this Bas blade PHP put this inside up blade but add this footer and this header okay so this is going to be the same however as we agreed when we implemented these this using template inheritance because our head tag is completely identical in Bas layout and in up layout we are extending the up layout from the Bas layout okay which previously was called clean layout but now let’s change this so I’m going to delete everything from this up plade or maybe I shouldn’t delete everything I’m going to take out this part and instead of using this extends directive we are going to use now component notation our base uh layout component is called X base layout okay because this is the class name Bas layout and we use components with ex prefix awesome so this is the base layout now let’s paste this include of headers instead of yel content we don’t want yel instead we’re going to use slots okay so here I’m going to use slot the default slot for the photo links we can leave the section we can obviously change this into name slot again but for now let’s just leave these footer links as a section awesome let’s open also index blade PHP from which we are extending the app layout so we should change this I’m going to take out everything what is inside this section content so let’s take this part completely out uh and I’m going to delete everything except these footer links I’m going to leave this for now because I want to put this in a proper place and here in this um index plate I’m using up layout so let me paste this everything here I’m going to also take these footer links and put this in the Uplay out inside it okay awesome now let’s have a look in the browser what happens what what was changed so we don’t see actually anything right now but if we check in the page Source what do we see we see body we see script right here but between opening body and script there’s nothing so if we go in the base plate PHP that is because uh we don’t have any kind of slot right here so we are yelding we are outputting the child content but now the base layout is used as the component right here in the up layout and everything what we see right here will be slot so inside base blade we are going to Output slot the default slot now we save we reload the browser and we see something the homepage actually was recovered and in the footer we also see these four links so two of them is coming from this up blade PHP and the other two link three and four is coming from this index blade PHP okay so so far so good now let’s take care of the login page because the homepage is done we recovered it nice maybe we have we have to adjust couple of things but uh we will do this so now inside the login we have this undefined variable slot because when we open login blade PHP we are using this pay layout as um normal blade file with extend in but we should use this as a component not with extend so I’m going to take out everything thing this main tag let’s delete everything um actually uh we need to delete everything but we have to then later pass this page login as well as the title okay let’s still it everything X base layout and let’s put this main tag inside there now we save we reload the page and the login page was recovered however the CSS class is not added age log l in as well as the title is not given as we want so if we check the page source for login URL or even for home we see there is no title right here uh and then we have this pipe in car selling which is the general name of the website now if we go in base blade PHP we see that we are still yielding title right here okay so this is what I want to change in the base blade we need two variables we need the title and we need the body CSS class and we should we should accept those as attributes as properties of the component so let’s define them right here props we have body class and I’m going to give its default value empty string and we need title as well and I’m going to give it also empty string now right here I want to Output title okay and if we scroll down below right here I want to Output body class we can call this obviously CSS class but we might want to add some CSS class to HTML tag as well for some reason so let’s call this body class now instead of is set we have to change this because it’s going to be always a set is set will always return true instead of is said we can just do if body class exists then then we output the body class inside the class attribute and finally we need end if okay great now we save this we reload the page the resle doesn’t change because we don’t provide these two attributes if we go in the blade login blade PHP now we can provide them right here title is login and body class equals h- login we save we reload the page now here we see login and here we see page login class now if we reload the page we see pading was added to the form around it and also right here we see the login title this is so cool so awesome let’s go on the homepage and we need to do uh the handling of the title right here as well so let’s go into up blade now we know that our base blade accepts two attributes body class and title let’s go in the up blade and we’re going to accept title right here so Props title we can give it default value empty string then whatever title is given to the up blade we are going to pass it to the base layout so because we’re going to pass title as a variable we’re going to use colum right here title equals and then V variable title or the shorthand notation will be dollar sign right here and remove this completely because the attribute name what is defined in the paas layout matches the variable name right here so we save this we reload this and we have to provide the title obviously it doesn’t work because we have to provide this title from the index blade now our app layout also accepts title if we go in the index blade right here we can provide title home page save and reload and here we see homepage uh written so our index blade is passing title attribute to up layout up layout takes that and passes it to Bas layout Bas layout takes the title and renders it right here base layout also takes the body class and if it is available if something was given it is adding it in um in theory if we need to provide body class from up blade as well to the base layout we can also do this as well from here we have to just provide body class equals something we save we reload the page and if we check the page Source we are going to see something right here but obviously we don’t need this so I’m going to Simply remove that all right now let’s define these footer links as a named slot and remove this section and use slots um for the footer links as well so right here inside the footer I am going to uh do the following so so we need these two links link one and Link two let’s remove the section completely okay so we need these two links but we have to Output right here the variable which going to be the name slot let’s call this variable footer links okay however what should happen if this is not defined so in this case uh so let me first leave this let’s do like this footer links and then if we go in the index blade if you scroll down below here is the section we have to change this and we have to use um X slot footer links like this great now let’s take these two links link three and Link four and put this inside let’s remove this section completely now let’s save this and let’s have a look in the browser we reload we don’t see any error which is good and down below we see link three link four then link one and Link two however we want it vice versa so here we have the footer links but we should put these down below right here awesome we reload and now we see correct ordering link 1 2 3 and four however we will have an error if we don’t want to Define these footer links for specific page like if I comment this out and I reload load the page we see an error that we try to Output footer links which which is undefined so in this case we have two options one is that we can check if the footer links is set we can output it only in this case or we can Define this under props so footer links will be an empty string by default now if I save and reload we see nothing simply we uh we have at the bottom link one and Link two but for link three and link four it doesn’t uh print anything it doesn’t print even error now if I uncomment this part the footer links again save and reload we see link three and Link four as well now one last thing what I’m going to do is to change this layouts partials header and create this component as well and use it right here as a component let’s expand the project and here we have these views layouts partials header blade so there are two options how we can do this first is to create class for the component like we created up layout and base layout so if we create for example header um header component and we change the view location for the header component and specify under layouts uh partials right here this is how we can do this is one option second option is to move this header blade into components maybe inside components we can create a folder called layouts and we can move this header right there which is something I prefer I don’t want to create a separate class for the nav bar or any partial U component what I’m going to have in my project so what I’m going to do is to create layouts folder here and then move move this header right there inside layouts components layouts now this partials folder is empty right here which we can delete and in the layouts we have this header blade PHP now if we go into up blade PHP we can change and use this in the following way X layouts do header so this is the component oops it should not be like this so X layout Dot header so this is the component and how we can use that let’s remove this line let’s leave it and let’s reload the page and have a look so layout header it should be layouts header in plural form reload the page and now we see header recovered and now we have everything the whole application is using components the complete layout uh because this doesn’t need any content in between we can change this into self closing tag as well well and this is how we can have [Music] it now it’s time for a small Challenge in a similar way how we transformed login blade PHP from using template inheritance into using component you have to change sign up page in the same way right now if we check sign up page in the browser we see something like this so we have an undefined variable slot and we have to adjust this and we have to make this working in the same way as login page is working okay pause right now spend as much time as you need and then come back and see my [Music] solution okay so here’s my solution let’s open sign up blade PHP and I’m going to delete everything right here and we are going to use x base layout component so the end the closing tag should go right here and we have to provide title to be sign up and we have to provide body class to be sign up page we save and we reload and we see page right there however the CSS class is not applied probably because it should be page- signup and not sign up page and just like this the sign up page is already [Music] working I also have Second Challenge to you in this case we’re going to create new component if we pay attention to login page and sign up page we see they are very similar to each other so we have this logo ipsum right here we have this Google and Facebook we have links right here and if we go on the login page so we see again logo here Google and Facebook and the form part goes right here okay so now I want you to create two components for Google and for Facebook because these buttons are duplicated if we scroll down below we’re going to find this is the Google button and this is the Facebook button okay let’s create a component and use them in the signup play PHP as well as in the login play [Music] PHP okay here is my solution let’s bring up the terminal and I’m going to execute PHP artisan make component Google button and we’re going to provide D- view we don’t want the component class to be generated we only want view file we hit the enter the component create and in the same way I’m going to generate bbfb button so we hit the enter the component created successfully now let’s open Google button blade and we’re going to open Phoebe button blade or FB button blade so in the sign up blade I’m going to grab this button for Facebook and we’re going to put this right here and we’re going to grab this button of Google and put this right here okay so then let’s go right here and we are going to use now the component X Google button and we can use self closing tag right here and xfb button and again we can use self closing take approach and let’s copy these two buttons right now open blade PHP scroll down below and replace these two buttons with these two lines we save and we reload and the result is not changed we still see Google and Facebook buttons and if we go in the sign up page we still see them right here in the future when we actually Implement register or login with Google and Facebook if we need we can add additional props right here we can also add additional props right now for the text or for the image we can also add slots you know all that kind of thing things already you can Implement your own version of Facebook or Google buttons with different props so it’s now up to you right now I’m going to leave this as it is we created reusable component already which is used in two places and this is very [Music] cool I have one last challenge to you we see that sign up blade PHP and login blade PHP are very similar to each other we already observed now I want you to create another layout similar to how we have up layout I want you to create guest layout which will extend from this base layout and you’re going to put all the code which is common for sign up blade PHP as well as login blade PHP inside the new layout so if you pay attention right now the logo right here the car image uh the link right here the link text changes and you can create a named slot for this and the form content obviously changes and you can create default slot for this but other than this form content and this link right here everything stays the same so if we go on the login page we can see we still see logo here we still see car we still see these um Facebook and Google buttons only part is this form and inputs and button in the link right here this is a little bit complicated challenge so I want you to spend as much time as necessary so you might need half an hour 5 minutes or 1 hour the main thing is that you should implement this by yourself okay after spending some time on this if you haven’t implemented or if you have implemented come back and see my solution [Music] okay awesome now let’s see my solution how I would do this first I’m going to create the component PHP artisan make component and let’s call this guest layout awesome so the component was created and the new component file was also created under components guest layout blade I’m going to move this guest layout blade into layouts folder and I’m going to also change rename it and it’s going to be only guest blade PHP now let’s open guest layout PHP class and right here I’m going to change the view layouts guest awesome now let’s open layouts guest blade and we’re going to extend from base layout X base layout however the base layout needs two properties properties it needs title and it needs body class so let’s accept those two properties right here props title let’s assign default Val mty string and body class empty string as well so now we provide title here and we provide body class here with dollar sign so we provide these two variables inside this base layout we need to put something which is common for the login blade as well as the sign up blade now let me copy one of the views content the entire content so let’s get this and let’s put this right here okay so we are already using this base layout so we can delete this line completely cool now inside main let’s format the code inside main what do we have so if we scroll down below we see right here logo this is logo which is common for login as well as for sign up so we are going to leave this inside the layout then right here we have text which is specific to login okay so because this is specific to login we need this to be inside login blade not inside guest blade so that should be part of the login as well as the form the entire form so I’m going to take out the this and right here I’m going to Output the default slot okay now if we go in the login blade I’m going to delete everything and we’re going to use ex guest layout okay and I’m going to paste this login title as well as the entire form obviously we need to provide the title and body class as well so right here we need Title to be login in body class to be page- login and the last thing what we need to take out or create slot is where’s that this is the form I see okay so here inside the form we have this Google button Facebook button and this link okay so this Google button and Facebook button can be part of the layout right and the text what we see right here here that should be named slot so the interpretation can be different so right now we have this ex Google button and x Facebook button um inside the login blade uh which can be theoretically inside the guest layout if we simply close the form right here so we have the form closing tag right here I’m going to delete this and if we close the form right here okay so then what we can do is to take out this part okay and put this back inside guest layout right here okay so this slot will be replaced by the form with the login Button as well as by the title but the Google button as well as the Facebook button will be inside the layout now if we save this and if we check the login page we see the result is actually not changed however this part don’t you have an account this part now is part of the layout okay and what we need to do is to create named slot for that so for this we can create Nam slot for the entire div or we can only create Nam slot right here so for example if we call our named slot um footer link for example then we go in the login blade and right here we can Define x- slot and we give it name footer link okay and we put this right here inside the footer link now we save we reload we still see link right here now let’s create sign up page so here we are going to use we’re going to take out this H1 and we’re going to take out this four like this and we’re going to delete everything and we’re going to use x guest layout then we paste everything here we need to provide title to the sign up page and we call this sign up and we need body class and we need to call this page- signup okay we save this we reload the page we need to go to the sign up page and now we see uh the error footer link because we don’t provide this footer link obviously we can check first of all if the footer link is given or not or we should say that the footer link must always be presented so in this case we don’t have this footer link named slot so let’s provide it x- slot footer link for the sign up page let’s go into let’s expand this form we scroll down below we see we have this button here and the footer link here so what we need to do is again move this form closing tag after the register button right here and this is part of the layout so we can delete this and this text is part of the footer link so we extract this we take out this and we delete this div which is Again part of the layout right here awesome so let’s delete this now we put this footer link information here we save it we reload the page and now let’s have a look already have an account click here to log if we go on login page we see don’t have an account click here to create one so we successfully implemented this name slot for to link and we have different texts for login blade and different text for um sign up plate okay and in the guest layout we have this entire form including the Google and Facebook buttons in the footer link Down Below in the future if we decide to have separate images the car images to be different for the login page and different for the signup page you can create another named slot right here just like we are outputting footer link we can output um image link or image uh element right here okay and then you would Define right here image element slot different for sign up page and different for login [Music] page now I have another challenge to you if you open index blade PHP file from the home folder we’re going to see that we have a lot of duplicated code so this code is related to car item because we have the exact same car item many times we see the exact same HTML code right here the challenge is the following you have to create new component car item component and you have to use this component right here inside the loop but at the moment because we don’t actually have any data related to cars just Create A Primitive for Loop from 1 to 15 and render the exact same car item component 15 times in this case we’re going to have right here only couple of lines but it will render the exact same component multiple times and we won’t have code duplication and in the future when we actually Select Cars from the database we will have an actual data we will slightly modify the component okay as always think a little bit spend the time on this Challenge and then come back and see my [Music] solution all right now let’s see my solution first of all I’m going to bring up the terminal and we’re going to create new component PHP artisan make component car dish item we can create class-based component or viewon component in this case I don’t want class Associated to this component so I’m going to provide right here D- view we hit the enter the component created successfully now let’s go under views components car item blade PHP this is the component let’s open index plate PHP file I’m going to copy single example of car item and put this in the car item blade PHP let’s expand this we see this car item with everything is dummy right now and hardcoded we’re going to modify this later now right here we don’t need this hardcoded HTML anymore so feel free to collapse everything and delete it so let’s collapse everything here we go and I am going to delete all car items from here just like this then we’re going to use for Loop and we’re going to iterate from 1 to 15 so let’s introduce I variable which equals to zero while I is less than 15 we’re going to increase I and obviously we need right here and four and in between the opening directive for four and for closing directive of N4 we are going to use ex car item just like this now we save this and let’s check everything in the browser reload the page let’s scroll down below and we see all car items and it is exactly 15 times now let’s reduce this into 12 and we should see only three lines of car not more just like this reload the page and we see exactly three lines of code now let’s clean up our blade files and remove the content which we created only for learning purposes but we don’t need them in our final project for example these text is something we don’t need also in the footer text we don’t need them let’s open index blade PHP from the home folder and we’re going to remove the following PHP directive we’re going to remove this EX card and we’re going to remove this ex test component as well let’s collapse this Main and we’re going to remove these footer links as well and we’re going to also open up blade PHP layout and we’re going to remove this footer completely now we don’t see if we reload the page we don’t see these text in the header as well as in the footer however there are few more things we’re going to do first let’s open web PHP and let’s add names to this sign up and login rotes let’s provide name for sign up obviously it is going to be sign up and for login it is going to to be loging cool next is we’re going to adjust the CSS files so if we open base layout CSS and JavaScript files more specifically so we have the following CSS file included with a relative URL so if we put slash right here this is going to be absolute URL if we remove the slash this is relative URL meaning that when we create Pages um which will have slash in the URL for example car SLC create when we create the following page which includes the following CSS file because we have the CSS relative the actual request to the CSS file will be like this like this and the following CSS file does not exist so this will give us an error and the CSS will not be loaded in the same way JavaScript will not be loaded so we are going to add slash right here scroll down below and we’re going to add slash right here as well in the next lessons when we create those pages we’re going to see that the CSS and JavaScript is loaded properly now let’s create car controller and render several Pages for this I’m going to open HTML CSS project and here we have a little bit more HTML files than we had previously I updated the project and you’re going to see the updated project if you follow this project basically so let’s open this index HTML and let’s open with the live server and right now at this stage we are going to create the following Pages we’re going to create add new car page in our PHP project we’re going to create my cars page we’re going to also create view car page and we’re going to also create edit car page all right let’s start first with the controller let’s bring up the terminal and we’re going to execute PHP artisan make controller we’re going to call this car controller and then we’re going to provide the flag D- resource let’s hit the enter car controller was created created now let’s open car controller which by default has seven methods so what I’m going to do now Implement those methods and render the corresponding blade files so from here actually let me use multic cursor functionality so I’m going to create cursor right here inside the index then hit the alt on my keyboard and create second cursor right here we’re going to scroll down below I’m going to create create another cursor right here I’m hitting alt whenever I’m clicking now I have three cursors one here second here and third here and in the same way I’m going to click alt and click right here now I have four cursors I’m going to delete this comment and I’m going to return view then we need semicolon right here but inside this view we’re going to provide the actual blade file name so let’s move up and I’m going to copy the function and I’m copying this function using control and shift which select is selects the entire word I have many cursors as you notice so control shift and right arrow and it selects all these four words I’m going to hit contrl and C then come down with this Arrow navigation and right here I’m going to to write car dot and paste all right in the following way of course when you get used to it you’re going to do it much quicker and this gives you possibility to easily Implement four methods car show here we have car create and here we have car index all right we are going to create these blade files but additionally we need one more method which is for search so let’s create new function search and we’re going to return view card. search now let’s create five blade files I’m going to bring up the terminal and we’re going to execute HP artisan make view we need car index we hit the enter next we need car show hit the enter we need car edit we need car create and we need car search okay we created five blade files now let’s open HTML CSS project and we’re going to copy uh HTML content from this project into our blade files let’s start with this add new so let’s move up and we’re going to find this main tag okay I’m going to select this entire main tag now let’s go in our project and find car create so this is this is the blade file which will be responsible for rendering car form and I’m going to paste this main tag right here okay in the same way let’s find my cars let’s find this main tag I’m going to collapse this header and here we have this main tag so I’m going to copy this main tag and open car index blade and I’m going to put this main tag right here and we also need to adjust the layout before I proceed so here instead of D we need X up layout make sure that the closing tag is also X up layout we need to do the same thing for create as well X up layout just like this and and here we need X up layout as well okay awesome let’s continue so inside edit we need pretty much the same um content as inside create plade PHP so let me copy this uh let’s open this edit X up layout X up layout and paste this main right here inside edit we need search as well so let’s open search where is shtml and let’s search for the main tag opening main tag right here let’s copy this and let’s change this into ex up layout and paste the main tag oops I copied something else let’s C copy this again okay it was pasted awesome and the last one is show blade PHP which is view HTML so again let’s search for main tag we are going to copy that and we are going to put this right here let’s change this again into X up layout okay awesome now let’s open web.php and we’re going to Define Roots let’s define this right here and we’re going to Define uh a couple of roots but we are we are going to use the resource type of definition so we’re going to use root resource we’re going to provide car and we’re going to provide car controller right here okay awesome let’s replace this with import I’m going to hit alt and ENT enter hit right here so that car controller was imported okay this is good and that defines as we know seven rules okay additionally we need search as well but we need to Define this search root Above This root so this is important if you define this below this root it is not going to work and I will explain why root get slash car search and then we are going to use car controller uh I think I have to disable this autocomplete this is the um PHP storms built-in autocomplete which if you’re using PHP storm this will work on your computer as well quite probably but I don’t want this aut to complete to um do the things instead of me because we’re going to learn a lot of things so I’m going to disable this quickly this can be actually disabled if we go to settings and then we need to go to um or maybe we can just type enable full line inside editor General code completion here we have this enable full line suggestions uh which actually downloads the models for PHP and couple of other things and it uses the AI so I’m going to disable this because I want to do everything by ourself because we’re going to learn so here I’m using car controller class and we need search method and let’s provide name for it as well this is going to be car. search okay now let me try to explain why this should be defined before this resource because the following line root resource for car defines seven roots in one of them is car to view car for specific ID and the root let’s execute the following common PHP Artisan root column list and we have car search right here and we have car and variable here as well so if this is below the following route then the following rout will always match car search because car this is car whatever and car search obviously is car whatever ever that’s why any any arbitrary string okay that’s why we need to have this car search to find this before the car and the variable whatever or arbitrary string okay awesome now we have these roots defined let’s actually open the browser and we can try to have a look for example car we hit the enter and we see my cars let’s access car create and we see a new car we have also car and specific variable which is car show I think we have car edit in some variable as well or don’t we um let’s open DRS again car ID and then edit my bad car ID and then edit this is again a new car because we have the exact same HTML and finally we have car search which looks like this since we have the controller and Roots defined now let’s update the links to these Pages for example when we click add new it should access car SLC create and in the same way sign up and loging should be implemented as well let’s open pH push Tor we are going to open header header blade PHP let’s um let’s actually we can fix the following as well it has HF SL which is actually correct this always go to goes to slash that’s okay we can leave that here we have this add new HTML and we’re going to change this to the following root root car. create awesome let’s collapse this we have sign up HTML this is going to be root sign up and we have this login HTML which is going to be root at login okay let’s go also into car item and clicking on the car item opens this view HTML and I’m going to change this into root car. show and right now I’m going to provide hardcoded number one but again we’re going to implement this uh correctly in the future so we’re going to save this I think one last thing what I’m going to do is also open index HTML index blade PHP sorry and we’re going to find this uh form not this index we need home slash index blade PHP and we’re going to find this form ex search form let’s open search- form and here we have this action and method which we actually don’t need so let’s open this search form we are going to remove this action and method that was only there for learning purposes awesome and I’m going to change this action into the following root this is going to be car dot search and the method needs to be always get we’re going to implement search with method get now if we open homepage and if I click right here it is going to redirect us to car search passing the C parameters which we don’t have yet implemented but the main thing is that the redirect to the search page works successfully a lot of travel makes it super easy to work with different databases using raw SQL a smooth quer Builder or the eloquent orm currently Lal directly supports five databases it is Maria DB t.3 and above MySQL 5.7 and above post SQL 10.0 and above SQ light 3.35 and above and SQL Server 2017 and above all configurations of the database happens under config database file here we’re going to find the default database connection name which is taken from file we see all the connections configured to sq light MySQL marad DB pgsql SQL Server we have the default migration repository table and we have the radi database as well everything related to database is right here but we control which connection we want to take fromen file the connection right here um is configured for different databases from the I file and let’s open. file we decide which database we want to use for example for DB connection we have provided that we want SQ light if we want to use use MySQL for dbit connection then we can uncomment the following code um we’re going to remove the hashes we’re going to change the DB connection into MySQL and then we’re going to configure the DB host Port database username and password for our MySQL in the same way we can change this into SQL server or uh postra SQL and we have to provide the correct host po database username and password however if we have this as a SQ light we can also provide the database location which by default is taken from database database.sql light however if we provide right here DB underscore database then we can provide a different path to our sqi database which we don’t want in our cas so I’m going to remove this line and our database is located under database.sql light additionally we have also uh option to provide the configuration through the URL for example we can provide right here database uncore URL and right here we can provide the full URL of the database we can provide the driver of the database then we can provide the username and password then we’re going to need Ed symbol here then we need host and port and then we can provide the database using the following URL we can also connect to the desire database okay so in MySQL example this would be MySQL let’s say this username is root the password let’s say it is password the host might be 1 127 001 the port will be 3306 and the database might be LEL or whatever okay we could connect to my SQL in the following way okay I’m going to remove the following codes which you can find under the notes everything uh but we know how to connect to the database and by default we are connected to sq light now let’s explore the existing database which comes with the default installation of LEL for this we need SQ light browser if you follow this with on PHP storm we can use the PHP storms built-in database tool but if you don’t follow on PHP stor I’m going to show you which um which software you can use to open SQ light files and browse it so let’s type in the Google SQ light DB browser the very first link will be DB browser for SQ light this is what we need to um download we can access slash DL and here we have these versions for different operating system um on Windows we can download make sure you download and install okay I already downloaded and installed on my machine so we’re going to open DB browser for SQ light this is opened and now let’s open the database we’re going to click this open database and let’s go to desktop Lal course database and database.sql light hit open and we see the following tables the following indices and we can also browse it so let’s explore the tables so we have the users table which has ID name email email verify date password remember token create that and updated that so we have this SQ light sequence table separately this is necessary for SQ light we have the sessions table with couple of columns user ID for which user the session is opened IP address user address payload last activity which is the uh date we have this password resit tokens table as well for email token and the date we have the migrations which we’re going to talk more about it soon in in in the next lessons we have the jobs and job batches table which is related to uh some background jobs we have the failed jobs which is also related to it and we have cash and cash locks so this is how the default uh structure looks like for the default installation of LEL and all those tables are created um through the migrations which we’re going to talk more about it if you are using PHP storm and you want to explore the database using PHP storm like I’m going to do in most of the cases then you can go into database and double click on this database SQ light file this will bring the following popup it will detect that this is sqlite file you might need to download the driver right here you might have that download driver button once you download it you can click okay and it’s going to mount the database right here and right here you will have this Main and tables and here we have all the tables we observed in the DB browser for SQ light we have these users with all columns we have those SQ light uh master and sequence and sessions and everything basically what we covered generally because I am doing this in PHP storm and I have this database tool integrated inside there it is going to be much quicker for me so I’m going to use the following database tool but whenever if you don’t follow this on PHP storm no worries you can always open TB browser for SQL light and whatever I’m going to do um you can do the same thing in the DB browser for SQ all [Music] right now let’s have a look at the our database schema which uh we need for our project here we have couple of tables and let’s start with the users uh I didn’t add all the columns to the users table because the columns what is already in the users table which comes with the LEL will you should consider that we are not going to touch it okay so we don’t touch them like the name email email verify data and so on here I mentioned the new columns which we need to add to the users table like phone for example Google ID and Facebook ID Google ID and Facebook ID will be necessary for oou for sign up and login with Google in Facebook and I had to provide ID right here because the users table has forign key into other tables so then let’s start with the car types so we’re going to have table for car types and we have only name like if it is Jeep or sports car or SUV and so on we’re going to save that information in the car types we’re going to have also uh fuel types and this is going to be like diesel or gas or hybrid or electric and so on okay we’re going to have makers The Producers like BMW Lexus Toyota and so on and we’re going to have models his corresponding models like Toyota Prius Lexus RX and so on we’re going to have also States list of states and cities because the our application is specific for a single country it is not like a global type of application which don’t have countries okay we have States and obviously there is different interpretation of States into different countries and you can create you can put records in the states table based on your country for USA we all know what it states for Canada um there I I believe they exist all also States but for different countries there are sometimes it is called regions so you can insert insert regions as well and then we have cities for each state so cities has connection to States okay so these are so-called Leaf tables which connects to the main table which is cars table each car will have ID the maker ID model ID the ER the car was released the price V code um millage um we have the car type ID fuel type ID user user ID who added this car we have the city ID where the car is located we have uh address as well which is a free text field we have the phone uh on which the buyers potential buyers should contact to we have the long text description where the seller can write any information we have this published at when the car was published uh when it appeared on the website okay potential sellers can also specify the publish dat to be in the future and the car will automatically appear on the website in the future we have also created it when the car was created updated it when the car was last updated and the deleted at if the car is deleted when it was deleted for each car we have also car images we have the ID of the image we have the car ID for which car the image exists we have the image path and we have the position as well and if we scroll up we also have favorite cars each user will have many cars in its favorite list so cars and users have many to many connection like one user has many cars in favorite list and one car might be added by many users into favorites all right I think we covered almost everything here we have the car features and car features and cars have one to one connections so these are just Boolean features whether the car has abs air conditioning power windows power door locks and so on you can Define if you want to customize this project which I really encourage you uh you can add as many features right here as you want or you can remove the features if you don’t want but for now I recommend to follow the course as I’m explaining with all the exact same fields and um then when you finish the project you can add additional features you can remove the features you don’t need and you can improve the project as you [Music] need Lal migration is a way to manage and Version Control your database schema think of it like a versioned blueprint for your database it allows you to Define the structure of your database tables like columns and the data types inside your code with migrations you can easily create modify and share database changes with your team when you run a migration Lal applies these changes to your database this helps keep your database structure consistent and makes it easy to roll back changes if something goes wrong migration are typically located under database migrations [Music] folder now let’s open the very first migration from the migrations folder but before I open it let’s understand the pattern of the name of the migration file the file name consists of a time stamp followed by a descriptive name of the migration the time stamp is the following right now which is set to 0000 1 0 1 0 1 and bunch of zeros right here so this specifies to year month day and the time stamp of the current time then we have this descriptive name the time Stamps will ensure that migrations are going to run in the correct order so in our case first this is the migration which should be executed then this migration will be executed then this migration will be executed and when we create more migrations we’re going to see that it has a different and the current time stamp right here now let’s open the very first migration create users table I’m going to call up the left side it has the following structure every migration file extends the migration class and it has Anonymous class inside this Anonymous class has two two methods up and down the up method defines the changes which will be applied to the database such as creating or modifying tables the method uses lal’s schema Builder to define the schema changes such as creating tables in our case the down method reverts the changes made in the app method providing a way to roll back the migration this method undos the changes like dropping the table which was created using up method we’re going to learn how to create migrations but this is the general idea so the name of the migration the class which is an anonymous class extending the migration we have up and down methods now let’s explore each migration which comes with the default installation of Flavel in more details let’s expand this up and we see that we are creating users table providing ID string name email which must be unique we provide the Tim stamp email verify dat which can be also null we provide the password we provide the remember token and the timestamps such as created at and updated at we also create second table which is password reset tokens table which has email which is a primary key of the table it has a token and it has timestamp created at which can be null and there is a third table sessions which has ID as a string and primary key we have the foring ID which relates to users and the foring ID can actually be null because if there’s a guest user the user ID will be null because the session is created for the guest user there’s also index added on the foring ID we also have IP address which can be also n we have the text user agent which can be also null we have the long Tex some payload of the session and we have the integer last activity which also has index let’s explore other migrations like create cach table and create jobs table let’s open this create cache table first it creates the following tables with um string key with value and the expiration date of the cache and we have cach locks as well with key owner and expiration as well and in the jobs table it creates three tables the jobs table with its own columns it creates job batches table and it creates failed jobs table as well and all these tables are available when whenever we execute whenever we create new project basically which behind the scene executes the might migrations it creates all these tables right here now let’s get familiar with the migrate Artisan comment for this we’re going to open the terminal and I’m going to execute PHP Artisan list migrate this will give me all the available commments for the migrate Nam space and we have few of them like my mate fresh which drops all tables and reruns all the migrations migrate install which creates the migration repository we have the uh migrate refresh which resets and reruns all the migrations basically the difference between this refresh and fresh is that fresh drops all tables and then reruns migrations but refresh executes down methods uh in the reverse order it reverts all the migrations and then re reruns them we have reset as well which simply reverts uh roll backs all the database migration so this executes only down methods in the corresponding order we have roll back as well to roll back the last database migration and we have the migrate status as well which shows the status of each migration okay let’s explore these Commons PHP Artisan migrate colon status we hit the enter and we have the following status so we have three migrations in our project and all of them have the status of Ren now let’s execute PHP Artisan migrate colum fresh hit the enter let’s scroll up to see the result dropping all the tables which will stand preparing the database creating migration table and then running the migrations now let’s execute PHP Artisan migrate refresh we hit the enter let’s have a look so it is rolling back the migrations I mean calling down for each of the migration in the reverse order first it is calling down for jobs then for cash then for users and then running migrations first for users for cash and for jobs so if you want to execute any specific commment from this migrate namespace you can first execute this um PHP Artisan list migrate to have a look at the commons for the migrate namespace and then you can easily use it again let’s execute PHP Artisan migrate um resette for example with the enter it roll backs all the migrations and now if I open the database reload it we don’t have those tables we have only only these core tables which is necessary for our project uh in any case like the migrations table SQ light master and sqq light sequence as well now let’s apply our migrations PHP Artisan migrate which will simply execute all unapplied migrations we hit the enter and it run those three migrations and now we can reload the database and we can see those um tables so in the same way if you are using DB browser for SQ light you can um reopen the database if you execute reset for example I just executed PHP Artisan migrate reset then you can close this database and reopen it and you’re going to see updated tables right here so every time you make some changes um you can execute migrate for example you can close this or directly reopen the same database in you’re going to see all updates so this is how you can kind of refresh the database in your DB browser before we create our first migration let’s first update the existing create users table migration because we need to add couple of columns to the users table according to our schema so we need to add phone Google ID and Facebook ID all right let’s duplicate this string email and change this into phone and we’re going to make this with the length of 45 and we’re going to make it also unique but we’re going to make it also nullable because the users registered through Google or Facebook uh they will not have phone numbers Okay Google or Facebook will not provide it and we’re going to make this nullable for that reason uh then we need to Define Google ID with a length of 45 and we’re going to make it nullable as well and next we need Facebook ID which is going to be nullable as well because the users registered with normal sign up form not with Google not with Facebook they will not have Google ID or Facebook ID inside the user table that’s why we’re going to make them nullable now since we have the those columns defined we are going to execute migrations let’s open the terminal and we’re going to execute PHP Artisan migrate fresh so that we’re going to drop all the tables reapply them so that users will have those new columns we hit the enter the tables were dropped reapplied let’s open the database refresh it and we see right here users which has phone Google ID and and Facebook ID columns as [Music] well now let’s create our first migration and the first table we’re going to create is going to be car types table let’s execute the following Artisan commment PHP artisan make migration and we’re going to provide the migration file name create underscore car types uncore table there’s a convention that you should whenever you’re creating new table you should call your migration file create your table name underscore table this is exactly what I’m going to do right now hit the enter and it created the following migration file now let’s open this create car types table here we see this and pay attention to the Tim stamp so this is the current time when the migration file was generated let’s double click and open this and it also has create table create command inside up method and inside down method it has drop uh command as well whenever you name your migration file in the following way create your table name table Lal will automatically generate the following code with the table name and with these ID and Tim stamps columns okay this is awesome now let’s actually provide the content so if we have a look in the picture of our schema for car types we have only name which is varar 45 characters okay so we don’t need this time stamps which is actually created at and updated at columns we’re going to remove this and on table we’re going to call St string name we can provide the second argument 45 as a length and it must be required so just like this we have created our first migration for car types now let’s create the second one for fuel types as well PHP artisan make migration create fuel underscore types table we hit the enter the migration was created let’s open it and let’s remove this time stamps we provide table string um let’s provide name with 45 as well so if we check fuel types which we have um right here it also has name as an only column except ID which has varar of 45 okay we just created two new migrations in now we can execute [Music] them let’s bring up the terminal and first I’m going to execute status commment phpr artison migrate status and this shows us that three migrations files are executed but two of them are pending and these are the migrations we created create car types table and fuel types table as well we can execute these migrations using PHP Artisan migrate as we already covered it but we can also pretend the migration run and print the actual SQL statement which will be generated using the following comment PHP Artisan migrate d d uh pretend we hit the enter and now pay attention running migrations so this is the first migration and here is the SQL code generated create table car types ID integer primary key Auto increment not null name varart not null okay depending on which database you you are using the generated code might be slightly different for um MySQL it might be slightly different uh for sqlite this is how it looks like for mssql it might be slightly different and this is the power of LEL it is database agnostic so we write the following methods and larel knows based on the database connection how to generate the code for the specific database that is very cool now let’s execute PHP Artisan migrate hit the enter two migration files were applied and if we check the database reload Lo it we’re going to see car types table right here and fuel types table as well and again if you’re using DB browser you can click open database again double click on it it’s going to refresh it and we see car types and fuel types with idend name columns right here as well now let’s keep creating more migrations for our project and let’s create maker table and model table and also States table and Ci’s table let’s bring up the terminal and execute PHP artisan make migration create makers table we hit the enter let’s execute create models table we hit the enter next create States table and create CTS table so we created four new migration files let’s go into database migrations we had previously these two now we have four more and the time stamps are very close to each other as you see so this is the current seconds okay let’s open this create makers table actually we’re going to open all four and we’re going to provide the content uh um starting from the makers so the makers need ID and if we have a look again in our database schema it only needs name nothing else so we don’t need time stamps on table we need string name with a length of 45 that’s it that’s all what we need in the makers so we can close this makers table and the down basically is ready by L so it simply drops the makers table so we can close this makers uh now this models is a little bit interesting so the models table has maker ID as well this is a new type of column it is a foring key type of column okay so let’s delete the time stamps and first let’s define string name with a length of 45 cool now here let’s define this maker ID on table we’re going to call foring ID method okay we provide the local column name which is maker ID and we provide using which table the uh following column is constrained so there’s a constrained method and we have to provide the table name like makers in our case so the following line creates a new column inside models table calling maker ID defines the foring key onto make makers table um maker table’s primary key okay so lot ofel knows that there is ID primary key inside maker table and it creates this maker ID of the model table to connect to maker uh tables ID column this is cool so we created these modules now let’s do something similar for States we need only name string name with the length of 45 inside States and inside cities we need string name with the length of 45 but we also need Bing ID and this is going to be state ID which has constrain on States table okay cool we Define four new migration files let’s close all of them let’s bring up the terminal I’m going to clear this up and let’s first execute PHP Artisan migrate column status we see four of them is about to be executed and then we can execute phpr design migrate hit the enter all four we are executed and we can reload the table and we see cities we see States we see models and we see makers now let’s keep working and now let’s create two more migrations one for car stable and second for car featur table and those two uh tables have most of the columns cars table and car features table okay let’s go with it PHP artisan make migration create cars table we hit the enter and second is going to be create car features table okay awesome let’s open create cars table in car features table as well let’s start with a create cars table okay what Fields do we need inside cars table so we need ID which is there we need maker ID in modu ID which will be foring keys so let’s define right here foring ID maker ID which will be constrained by maker table okay let’s duplicate this line and let’s change this model ID which will be constrained by models table next we need Y and price which will be integer values okay so on table uh we’re going to call integer y let’s duplicate this and integer rice next we have VIN code which will be varart 255 and Mage which is going to be also integer so let’s duplicate this and let’s create first millage and then right here we need string Vin which will be 255 with the length of 255 by default it is also 255 if you hit control on your keyboard and hit Mouse on the string method you’re going to see that it has length null but then this length is taken from this Builder default string length and if we follow this we’re going to find out that by default it is also 255 so we can actually close this and we can delete this to 55 but I actually like this to be explicitly visible that the length of V code is um the maximum is 255 actually the the in practice the wi code is 17 characters so we can set this into 17 but because we are using actually varart it doesn’t really hard so we can leave this to 55 okay then we have um after millage we have a car type ID fuel type ID user ID and CT all will be foring IDs so we create uh car t type ID which will be constrained by car type stable let’s duplicate this three more times so this is going to be fuel type ID constrained by Fuel types table this is going to be user ID constrained by users table and this is going to be CTI ID constrained by CTS table next we have address and phone let’s provide string right here address 255 and let’s duplicate it and second will be phone with 45 characters after phone we have this long text description and then we have time stamp so on table let’s call long text description but whatever is nullable we have to provide to be nullable as well like the description is nullable so right here we have to provide nullable column nullable method as well so this is the description next we need Tim stamp Tim stamp of published at which also should be nullable after description we have a publish dat and then we have this created at and updated at time stamps right here and this if uh we hit control again and click on the time stamps we’re going to see that it creates these two columns and both of them are nullable actually so this is fine and after these Tim stamps we need another Tim stamp which is going to be deleted at column okay so we we defined all the columns for our car table now let’s open create car features table and provide the content for it so here we have all of them are uh tiny integer type of um columns um the same as Boolean basically uh so we have to provide Boolean right here which will be inter interpreted into tiny integer so we need Boolean right here that uh needs to be abs and we can provide the default value to be zero okay so when we provide Boolean LL will automatically convert this into tiny integer because our database uh sqi does not support Boolean so it supports tiny integer but if your database uh supports Boolean such as for example post SQL then the column would be created as Boolean column now let’s duplicate this um couple of times uh because the format is the same for every column we just have to provide the names like ear conditioning power windows air conditioning then we have power windows we have power door locks power door locks we have cruise control Bluetooth connectivity cruise control Bluetooth connectivity next we have this remote start in GPS navigation we’re going to duplicate this few more times remote start GPS GPS navigation we have heater heater seats it’s called heater seats uh heater maybe it’s a typo so it should be heated heated seats uh then we have climate control climate control and we have two more it’s a rear parking sensors and sensors and the last one should be uh leather seats and finally our car features table does not have ID it has car ID based on the schema and it has the relation to the car table based on the car ID so it has one to one relation so here what we are going to do instead of defining ID I’m going to provide unsigned big integer provide the car ID and make it as primary key okay so we actually don’t Define the constraint like we defined for other relations but we have the car ID and then later on the model level we are going to implement the relation between the car features and cars uh tables so this is how we’re going to have it and we also don’t need time stamps on the car features so we are going to remove it as well okay just like this we Define these car features now we save it and we can execute migrations PHP Artisan migrate we hit the enter these two tables we are created and again we can check them right here cars and car [Music] features now let’s learn how to roll back our migrations for for this first open migrations table and observe the content of it so in DB browser let’s reopen the database so that it should be refreshed then on migrations we can right click in browse table so this gives us the same content and we just need to understand how the content looks like so here we have this migration table name and we have the pitch as well okay I prefer to have a look in the PHP storm so I’m going to open this PHP storm so this bch means uh that the migrations which we are run together they were grouped in a single batch so these first three migrations which comes with LEL we executed together so they were are in the first batch then these two what we created are in the second batch then these four tables are in the third batch and these two tables are in the fourth batch okay so this indicates that the migrations are executed if I delete for example these two lines and then try to execute migrations again a lot of will try to execute the migrations but because the tables already exist in the database we are going to have an error problem right so I’m not going to do this but you can try to do it so what I want to show you how you can R roll back the migrations HP Artis on Migrate colon roll back we hit the enter and the last uh two migrations last batch was basically uh rolled back and if we check right now if we check right now migrations table we don’t see last two tables right here so the last was actually rolled back okay so we can reexecute it obviously phpr design migrate and they will be reapplied if we want to roll back certain number of steps we can provide dash dash steps in roll back D Dash steps right here and let’s provide three for example we hit the enter uh actually it should be step not Steps step d d step equals three we hit hit the enter and last three migrations we are rolled back so let’s reexecute them so in the same way if we want to roll back specific number of patches like uh patches or pch in a singular form PCH equals two it is going to roll back last two batches so this is uh because we actually did a roll back and then we executed migrate again now these three um migrate migration files are in the same batch and these three are in the same bch so if we roll back last two batches these six migrations will will be rolled back so we can hit the enter and we’re going to see uh bch equals 2 create fuel type table create car type table okay what just happened oh excuse me um when we provide the batch not excuse me uh when we provide the batch it actually roll back specific batch not the last couple of batches but specific batch so in our case because we provided bch equals 2 we rolled back the second badge which was create car type stable and fuel type stable okay this is how it works okay now let’s execute my great again and those two tables would be applied again if and if I reload they will have now higher bch right here higher uh pitch number okay and just like we can pretend running migrations we can also pretend rolling back migrations like pretend hit the enter and it’s going to generate the SQL codes if it is like um rolling back the last bch migrations like create fuel types and create car types table okay so I think this is pretty cool and we can also execute um refresh with Das Das step like I want to roll back and then reapply last three migrations for example we hit the enter it’s going to roll back and reply last three steps and obviously which we already covered we can simply reapply um this refresh or fresh which will drop everything reapply it which is exactly what happened right now and if we open this migrations table again now we see the ID starts from one this is because all tables were dropped and also ID started from uh one the auto increment and every migration is executed in a single batch [Music] last two tables for which we don’t have migrations are car images table and favorite cars table for all the others we already generated migrations now you have a challenge and you probably guessed what is a challenge you have to create migrations for these two tables favorite cars and car images you can do it in your desired order however I recommend to maybe first create C images because we have just created cars and car features and then you can create favorite car stable but again the ordering doesn’t matter you can do it as as you as you prefer okay so pause right now create these migrations also implement the code uh for for these migrations implement the app method of uh migrations for these two tables and then and you can come back and see my [Music] solution okay so here’s my solution PHP Artisan migrate uh excuse me make migration create car images table we created the first migration second is create favorite cars table we hit the enter both we are created now let’s open create car images table and we are going to Define uh table ring ID car ID which is constrained by cars so car images table has relation to cars so this is how it should be and also this table has string string um image path which should be 255 this table also has position which should be integer so we provide integer position and the table does not need time stamp so we can remove it and let’s check the schema so car ID image path and position integer which is correct next we have this uh favorite cars let’s open it and we have two foring IDs table foring ID car ID which is constrained by cars table and the second is going to be user ID which will be constrained by users all right so we save it let’s bring up the terminal PHP Artisan migrate hit the enter the migrations we are applied we can check the database we see car images and we see favorite cars as well and we are going to see them in DB browser for SQ light as well uh this is the browse data for um specific table but we need the database structure we see favorite cars and car images eloquent orm or object relational mapping is lal’s built-in library that allows developers to interact with databases using PHP objects rather than writing row SQL cues each database table has a corresponding so-called model that is used to interact with the that specific table eloquent provides a simple and intuitive active record implementation for working with database including methods for common crud create read update and delete operations it also supports relationships allowing you to Define and work with the associations between different database tables eloquent simplifies data manipulation and retrieval making database interactions more readable and maintainable eloquent models are located under app models directory and they typically extend the eloquent model class so the user model is a specific class which extends the following class illuminate Foundation out user but if we expand this out user it finally extends this modu class and when we generate new eloquent model classes we are going to see that all of them extend from illuminate database eloquent model class the following [Music] class now let’s open the terminal and try to generate new model class for this we’re going to execute the following Artisan comment PHP artisan make model and we have to provide the model name I’m going to provide fuel type in Pascal case naming uppercase F and uppercase t so when we hit the enter it generated the model file which is located under app models fuel type we also have possibility to generate migration and controller alongside with the model so if I open up moduls and I delete this fuel type and reexecute PHP artisan make model fuel type by provide DH m flag to generate migration alongside with a fuel type we can also optionally provide c as well to generate controller we hit the enter and it generated three files the model file the migration file and the controller file now let’s have a look under database migrations let’s open this create fuel types table and as you see it generates the proper code to create the table fuel types if we don’t have fuel types table this would be awesome this would be exactly what we want but we already have migration so we don’t want the migration also we don’t plan to manage the fuel types from from the user interface so we don’t need the fuel type controller as well so I’m going to delete all three files and let’s generate just the model PHP artisan make model fuel type hit the enter and the model was generated if you want to see information about the model we’re going to execute PHP Artisan model colum show and we provide the module name such as fuel type in our case we hit the enter and it give us a every information about the model such as what’s the model class name what database it connects to what is its corresponding table name fuel types what attributes it has and what relations and what observers it has now if you open fuel type model the class looks like this it extends illuminate database eloquent model and it is a very simple class and it has only one trade has Factory we don’t specify what table the model has mapping into the database by default laravel considers the table name of the class to be snake case version of the class name but in plural form for fuel type laravel assumes that the table name is fuel lowercase underscore types in plural form okay if the model name is car LEL will assume that the table name will be cars if the model name is car image Lal will assume that the table name is car images with underscore and if the model name is TV uh remote controller for example the the table name will be tvcore remote uncore controllers in plural for so this is how Lal defines uh what’s going to be the corresponding table for the model however we always have ability to provide custom table name so for example here we can provide protected property called table and we provide a different name such as car under _ fuelcore types okay and now if we execute PHP Artisan model colum show fuel type we hit the enter we see the information that this this model maps to car fuel types but we don’t see anything in the attributes because that model that table excuse me that table car fuel types table does not exist in the database okay so in our specific case we don’t need to customize the table name however this is how you can do it okay so I’m going to comment this out sometimes there are cases that you want to customize the primary key by default Lille assumes that the primary key of the table is going to be ID okay however if we override protected primary key camel case uh property and we provide something different such as fuel type ID for example then Lal will assume that there’s a column inside fuel types table which is called fuel type ID and this is the primary key of the fuel types table okay so this is commented out let me remove it and if it is removed LEL assumes that the table name is fuel types and the primary key is fuel type ID okay this is something also we don’t need and we are not going to need in our project so I’m going to remove it and all the nodes you can find under the video as well or maybe I can leave it and comment it out just like this okay if you want to disable auto incrementing of the primary key then you can provide public uh incrementing property and set it into false so this will disable Auto incrementing feature sometimes if you want to um change the primary key type from number into string you can provide key type equals string right here by default the key type is going to be integer and always always the primary keys will be integers if if uh the primary key is not defined to be a string inside the migration okay but in our case uh we have all primary keys to be numbers so their actual values will be also numbers but if we provide key type to a string even though the fuel types um in the database has the integer right here when we select the data through models the value of the ID will be string again again this is something we don’t need we can comment this part out as well and we can put this on next to each other okay there are cases when we want when we don’t have time stamps such as created it and updated it on our models and this is exactly on our case we can disable those time stamps by providing time stamps equals false this is something we are going to need because our fuel types table does not have time stamps such as created dat and updated dat in the database cool if you want to customize the created it and updated it column names you can provide constants const created it um and the column name right here such as create date for example in the same way we can provide second constant which would be updated a equals such as update date for example and Lal will assume that there exists create date and update date columns in the database of course if the time stamp is not disabled so in this case I’m just giving this information for you to learn what is possible through models or how you can customize it okay but we are going to then go back to what actually is necessary for our project okay and finally if we have only create date on our model and we don’t have update date we can simply set the updated at to be null which means that we’re disabling the update updated eight column and we can leave this create we can completely remove it and it means that the there exists created at column inside this database table but there is no updated Ed column okay so again this is all for learning purposes so we can comment this out as well but what we definitely need is Tim stamps false because we don’t have created it and updated eight columns into um our table now let’s generate remaining models for our project we have a bunch of them to generate so let’s execute PHP artisan make model uh car type is one of the models we want to generate uh let’s generate maker let’s generate model let’s generate state city car car car features car images and um favorite cars is something which we actually don’t need to generate so that is all we can clear this up now let’s open model class and we have to fix something okay because by default the template uses the following illuminate database eloquent model class now we have two model classes in this file and we have to we have to fix that so let’s give alas to the imported model class as a Lo quent model and then take this and extend right here okay great now our model is fixed the next thing what I’m going to do is let’s go into car model and I’m going to use second trait which is called Soft deletes whenever our database table has deleted at column just like our cars table has right here okay deleted that column then we have to add soft deletes trade into our car and whenever you use soft delites make sure that the following import is also added under use okay this soft deletes manages that automatically for us whenever we call delete on the car model instance it is not going to actually create uh sorry it is not going to actually delete it from the database but it is going to set deleted at column into the database so this is something we need to add [Music] if we open car controller um in methods like show and edit for example and in um update and in Destroy as well so we have string ID which is assumed to be the ID of the car however Lal supports soall it Road model binding so right here instead of accepting string we can try to accept an instance of the car model which we just generated okay let’s hit the enter make sure that the car model is imported at the top awesome and then instead of ID we can call this ID obviously but uh more relevant will be to call this car so we expect right here an instance of the car and whenever there is an ID in the URL LEL will select based on the ID will select the car and provide an instance of the car model right here in this model in this method and this makes it very easy so we already have an instance of the car a record of the database converted into an object okay and in the same way right here let’s change and accept car inside edit we need to accept car here as well and in Destroy as well instance of the car awesome we don’t yet have any records in the database but we’re going to leave it like this because uh this is how we’re going to have finally okay also when we are generating Roots such as if we open car item for example we have right here root car show whenever we implement this component uh we will have an instance of the car okay and we can provide an instance of the car right here and LEL will take the primary key of this car and provide it in the route so this is going to also work I have to return this into one because we don’t have an instance of the car at the moment but because we are talking about uh Road model binding uh I had to mention this part as well but I’m going to leave these parts because whenever we actually have cars in the database then we will get instance of these cars right [Music] here we disabled time stamps on fuel types but there are bunch of models for which we also need to disable time stamps the only table which has time stamps is cars table if we have a look again again into database schema image we don’t have created that or updated it columns in any of the tables except the cars table so we’re going to leave them on the cars but disable for every other model now let’s start with the car features um we can actually open all of them then I’m going to collapse the left side and we can start from here on maker we have to disable it time stamps equals false then on model we can say time STS equals false let me actually duplicate uh or copy this code on States we have to disable on car features we have to disable on uh car images we have to disable on car types we have to uh disable then we have City we have to disable as well and I think we are done so so we did on all models we disabled the time stamps the only model for which we need is the car model now we’re going to move further and we want to insert some data manually in the database so that we can start reading that data and then obviously we’re going to learn how to insert that data uh through code uh through our modules okay so first let’s open DB browser and I’m going to show how you can do this in DB browser and then I’m going to do this in PHP store let’s refresh the database and let’s open fuel types let’s browse fuel uh types table we have to click the following plus button to create new records and I’m going to create like four records and I’m going to type guess right here we hit apply then we have uh diesel basically I’m not going to do this for all the tables just I’m showing to you how you can do it so in in a DB browser if you are not familiar with it electric and finally um hybrid Okay click on apply and the records we are inserted inside the fuel types table and in the same way we’re going to insert records into other tables now let’s open PHP stor and I’m going to open the database uh fuel types and we don’t see them because I think we have not saved the file we’re going to click on file and write changes okay this will affect the changes into the database file and if I reload right now into fuel time y we’re going to see those uh Records right here okay now let me open car types and I’m going to click plus sign couple of times and let’s insert sedan right here then we have hchb for example then we have SUV and for example we have Jeep just couple of them will be enough then I hit control and enter to save everything now let’s open open makers and let’s create two records Toyota and second Fort hit the enter Then control and enter and it’s going to submit that let’s open modules and create four models okay uh two of them for the maker ID one which is Toyota Let It Be Camry for example and cor Corolla and then we have like F150 and escape and provide maker ID too okay we save it uh next we’re going to open States and create like two states for example California and New York okay then Open Cities and create uh four cities two of them with state ID one two of them with state ID 2 we have to provide Los Angeles here we provide s franisco uh franisco like this then we provide New York and let’s provide Buffalo okay and I’m going to create also one user okay let’s provide uh John John at example.com let’s provide some dammy phone number email verify dat I’m going to leave this empty password I’m going to leave it empty or it is required I cannot make it empty so let’s just provide one to three I don’t care the password um the Google ID Facebook ID I’m going to leave them now remember token created it and updated it I can leave them now as well so and finally I’m going to create a couple of cars and let’s create like four cars uh maker ID one one two two one two three and four then we have y we can provide something and 200 and um 20 20 anything doesn’t matter okay let’s provide different 2015 okay for the price is let’s provide 10,000 20 30 and 40 okay for win we can just provide one two three and four um it should be 17 characters but uh we are just testing right now okay it does doesn’t matter for the mid AG as well we can just provide one two three and four we are testing car type ID maybe 1 two 3 and four one two three and four user ID for all of them will be one city ID 1 2 3 and four uh for address we can provide test for all of them for phone we can provide 1 2 3 4 5 six and I think that’s it and we can also provide the published but let me save everything so far uh cars deleted it oops I made a mistake the deleted at should be null I made it required okay let’s open the migration file create cars table and we’re going to make this deleted at nullable and in ideal case we have to execute PHP artisan migrate freshh or refresh but this is going to drop all the tables and reapply migrations and it’s going to work but because we already create some records inside car types and inside uh fuel types and so on I don’t want to lose that data because if I execute migrate fresh or migrate refresh we’re going to lose that data this is something I don’t want so I already changed the migration the next next time if I decide to execute PHP migrate fresh or refresh it is going to create the deleted a column to be nullable but right now I’m going to fix that column manually from here right click modify column and I’m going to turn off this checkbox not now okay create table uh it is going to actually do the following code behind but I don’t care okay this is this is the code it is going to generate I can copy this code click okay now it uh did the following code behind what described finally I have cars table which has um the deleted that column to be knowable if you are doing the same thing in using DB browser okay inside cars uh we have this modify table and you can find that deleted add column which is not null but if we just refresh double click then if we click uh and modify table it should be knowable because we updated this from PHP storm but basically you have to turn this off and on from DB browser okay awesome now let’s uh create these four records um one two actually one one two and two one two three and four uh let me actually duplicate the same thing for ER price for fee Mage car type ID field type ID user ID will be now for all of them CT 1234 address we can provide test and phone from 1234 again and that is all let’s click on submit and it creates four cars we can provide uh the current date as well which will be published at date uh okay like this awesome so we created the data now let’s open Home controller and here we have this index method which is rendered in the browser right on the homepage and now let’s try to select the data right here so cars equals we’re going to use now car model app models and make sure it is imported every time when we are using it and then I’m going to call get which will simply select all the cars available in the database okay so let’s dump this information let’s print that information for this we have a couple of options one of them is dump and let’s provide these cars right here let’s save it and reload the page and we can see right here there are four items into this collection okay and all of them are instances of up models car and if we expand it inside attributes we’re going to see the data that data is ID maker ID module ID and so on the data what we just created into the database okay awesome so this selects all cars select all cars now let’s select specific cars like the cars which are published for example okay let’s say we don’t want unpublished cars to be displayed on the homepage for this select published cars for this we’re going to do the following on car we are going to call method called we the first argument of the Weir method is the column name like published the second argument is the value actually our model is called published it right and the second argument is the actual value so if our column would be like published Boolean type of column then then we could provide right here true or one but because our column is published at column we have to find all the cars which has a non null value inside published eight for this we can use uh the following operator exclamation equals does not equal and we have to provide null right here so basically this we function is multi-purpose function we can provide two arguments right here which means that uh the published at should be equal something whatever we provide but if we provide three arguments it means that publish dat does not equal to null and after that we can call get okay let’s actually dump this information and it’s going to print four cars because all cars have publish it value but if we open it and change for example on the first one I’m going to set the published that value to be null okay then we have three published cars then if we open the browser reload the page we are going to see array with length of three so we totally see three cars which are published if I said n again on the second one and then reload the page now we see two cars right right here okay if we want to only select the first car let’s do like this select the first car then we have to do the following we can call we if we want or not where where is optional in this case uh for example published it does not equal to null and this then this is the most important one then we are going to call first okay we just want the first object based on the following condition and in this case we can print car which will be an actual model up model’s car instance and it has its own attributes so this is the first car which is published with ID3 so this is pretty cool obviously if we don’t want to provide this we published at we can directly call First and this is going to select the first available car and it will probably have the ID one because we are not filtering by published column however there exists simplified version if you want to select the car based on the ID for example car find and provide the specific ID for example two and in this case we can print it and we’re going to see that the car right here will be the car which has say id2 let’s reload the page expand it car with id2 if we want to sort cars by specific column we can use also order by let me comment out these things and later I’m going to remove but I’m going to also leave these under the lesson or inside the source code so let’s comment this part let’s say I want to sort cars by created it created it in descending order or maybe published at in descending order and then we’re going to call get on this now let’s adjust the published Ed column into the database like all of them are the same let’s set this to be 10 for example oops I mistaken we type dot right there let’s Pro provide right here to be 12 oops okay here we need 12 well it provides the time stamps for some reason uh I mean the visibility is for the time stamps which is something I don’t want uh let’s change these minutes maybe 50 let me do this from DB browser for SQ light or cars browse and we need to go to the right side we provide different time 50 right here uh let’s provide 51 here maybe 52 here and and this is going to be 53 okay and let’s save everything uh write changes uh if I reload right here the changes have been applied now we’re printing we’re selecting cars and printing those cars with published at descending order now if I reload we see actually this should be order by excuse me order bu reload the page now we see four elements right here and if we expand the first one is with id4 and that one has the highest publish date okay the next one with highest published at date uh is which has the ID3 okay the next one is which has probably ID 2 and the ID one okay this is um how we can sort the cars by published at column if you want to limit meet the cars by specific criteria for example if we want to only select two cars then we can use this limit function and obviously we don’t need order by we can provide order by but we don’t also it is not necessary we can just provide cars limit to and it’s going to always select the two cars okay and we can also use the combination of all these properties like uh we can provide uh let me duplicate copy this part where uh the publish dat is not null then we can call um something some another we close for example we uh user ID equals to one then we can provide order by as well we can provide limit and finally we can call get only so we can do all this combination now I save reload it is returning two cars and all the Weir Clauses are actually um correct so if I provide we user ID equals 2 it is not going to return anything because there are no cars for the user ID 2 but there are cars for the user ID one in the database and just like this instead of writing row sqls we can write any select any ques with the following methods on every model of course this is not specific to car we can call these methods on every eloquent model now I’m going to comment out this part and let’s see how we can insert the data into the database let’s scroll up a little bit and let’s say that we want to insert a new car in the database for this we have to create an instance of the car model using new car like this then on the car we can provide each properties individually so I’m going to copy the columns what we have in the database so that I don’t have to type them manually and let’s duplicate this many many times like this then I’m going to use multic cursor and I’m going to paste um these columns from the database and then we have to provide some values for each column like let’s just type one there so make maker ID one model ID one y we can provide whatever uh we can provide price one to three we can provide the VIN code to be one to3 millage something one to three car type ID one fuel type ID one we can provide the user ID uh everything so the address should be string we can leave it integer but we can provide string as well like some lurm Ipson for example we can provide the phone to be string as well the description should be a very large string or we can leave it also empty because it is actually nullable inside the published at uh we can provide the current date or we can leave it null as well if we provide the current date we can provide the Now function right here and created it can be now as well or it is going to be automatically provided automatically set by eloquent so we actually don’t even need to set any values to create it and update it so I’m going to remove them delete them and then on the car I can call Save okay before I call this in the database of the car table we have four cars now let’s open the browser and reload it and we don’t see any error which means that the code what we have in the home controller actually worked now let’s open cars table and we see one more record right here and here we see the data what we just provided so it is as simple as that to work with the eloquent models to save the data there are cases when you have the data in the form of associative array from which we want to create the data um record in the database okay let’s say that our data looks like this uh let’s put a comma right here oops okay so I’m going to comment out the above part creating car in the following way and then down below we have the following car data okay and let’s say that we want to create record out of it we can call Car colon colon create providing that car data which will create the record in the database and return just created record so finally here we’re going to have just created car okay which is pretty cool the second approach like this is the um approach one second approach is to approach two is to actually first create the instance of the car car let’s call it Car 2 equals new car then on Car 2 we can call F so we want to fill the car 2 with the car data so this will populate all the properties of the Car 2 model and then once we call this um field then on Car 2 we can call Save and there’s a third approach which is to create car three with a new car and in Constructor of the new car provide this car data and then which behind the scene we’ll call as well so this is probably shorthand notation of this then on car three we can call safe okay so this is good and this is Handy however there’s one important consideration when filling the data so all these three approaches is filling the data from the associative area from here okay but for security reasons it is not allowed the model to be filled with arbitrary data let’s say that we don’t want the user ID to be filled from that associative array okay user ID should always be the currently authenticated users ID and we don’t want it to be provided inside the fields so it should not be provided something if we expect this data from the client let’s say if we expect the data from the the user from the browser the user from the browser can send any information inside the user ID it can actually create the car on behalf of somebody else which is something we don’t want right so for security reasons filling the model data with the associative array by default is not allowed is not uh is blocked unless we activate it so if we open now car model we need to Define right here a protected array feelable so which Fields can be filled so in our case I’m going to copy and paste all the properties of this car we can copy from here as well select every every column from here and paste here so I’m just going to paste all the properties just to test the code what we have written right here okay but you should be careful what you allow the users to feel we’re going to talk more about this security and everything but for now let’s just put everything in aailable this means that every column what we have right here can be provided using this field approach the approach one approach two or approach three uh whatever we don’t put inside this fillable will not be filled and will not be provided in the database for example if I comment out the user ID then the user ID will not be provided when we provide this car data so there is a second uh property which is called guarded guarded and this excludes um the fields so if we provide guarded to be an empty array and if we comment out this fiable completely this means that every column of this model can be filled but if we provide um user ID here for example this means every column can be filled except user ID okay by default the guarded is null so if we don’t allow anything to be filled we should leave it null or we should not present it but if we allow any column to be filled we need to create this guarded detected property with the empty array so in our case um so this is kind of um wh list I’m sorry this is kind of a blacklist what is not allowed okay we put right here what is not allowed but it’s more common to Define what is allowed then what is not allowed so in our case I’m going to uncomment this fillable and we Define everything except the user ID and we want to see an error I want to see an error because user ID is required and we are are filling with the data but the user ID will not be filled so we should see some sort of error I’m going to comment out the approach two and approach three and let’s reload in the browser and we see this error table car has no column named VIN code that’s my mistake that should be Vin not VIN code now let’s reload the page and now we see uh n constraint failed inside the uh Vin that is because in the fillable we also have VIN code that should be Vin again now let’s reload the page and this is what I expected now we have this null constraint failed for user ID because we are filling everything except the user ID and the user ID is required that’s why the car is not created now let’s uncomment this user ID let’s reload the page and we don’t see any error the car was created in the database Let’s Open Cars table reload it and we see one more car with approach one now let’s comment the approach one and uncomment the approach two it’s going to do the exact same thing but let’s reload the page we have one more car we have now seven cars and we can comment this out and uncomment the approach three and reload the page and total toally we are going to have eight cars in the database the data is is the same for all the last three cars because we have we are using the same data but the records are created as you [Music] see now let’s open remaining models and we’re going to Define feelable protected property on all these models we already did this for cars uh let’s open the database car features let’s start with the car features and I’m going to copy all the columns what we have right here then we need to Define aable array semicolon here and I’m going to paste all the columns and let’s use now this multic cursor functionality in PHP storm we’re going to hit the inner button the middle button of the mouse the wheel and uh then we can do it like this or you can Define this obviously um one by one so we Define this for car features let’s go into car images uh the rest is slightly easier because there are not many fields so for images we need image path and position right for car type we need only name let me copy these fillable and for City we also need only name but we also need state ID right for fuel type we need only name for maker we need only name for model we need name and maker ID for State we need only name now let’s open user model as well and we’re going to add the new columns to the user model inside failable like we have phone we have Google ID and we have Facebook ID as well if we have a look at our schema we’re going to notice that all tables have primary key ID the only table that does not have primary key ID is these car features it has car ID to be primary key so we’re going to open car features model and we’re going to change its primary key into car ID as it is defined inside the migration based on our schema make sure you do this because based on the primary key we’re going to do the updates or deletes of these car features now what should we do if we want to update specific car let’s say I want to select a car which has id1 so I’m going to call find with id1 then on that car I want to modify the price let’s open the database open cars find the car which has id1 and it has pricey one as well okay let’s modify the price and provide 1,000 right here then on that car we’re going to call Save method which will which will affect the changes to the database now if we open the website reload it we have this in the home controller index method so the code was executed if we open cars and reload we’re going to see that the price of the car is 1,000 this is one way how we can update the data let’s comment it out now let’s see second way on the car model there is a static static method called update or create okay the IDE doesn’t autocomplete this but this doesn’t mean that the method doesn’t exist so the method exists feel free to use it update or create and we’re going to provide two arrays right here the first array and the second one the first is the condition which cars needs to be updated so here we have to provide for example I want to update all cars which has VIN code 999 and price equals 1,000 okay let’s have a look if we have such cars which has price 1,000 and VIN code 999 no there doesn’t exist such car but there exist cars which has been code 999 and price is 20,000 so let’s modify the price and set it to 20,000 so this is the wear condition and now let’s provide right here the actual property actual data that needs to be updated actually I’m going to move this like so okay so the first one is condition second one is what properties we want to update let’s say that we want to update price for every such type of car and we’re going to increase the price into 25,000 okay now let’s save reload the page we don’t see any errors so the code worked let’s open car stable reload and we see price is 2 5,000 however that only does for a single car that does not do for all the cars if we want to do this for all the cars we need to do it slightly differently okay by the way this updates the car and it also Returns the just updated car so if we just dump the car which has been right now updated we reload the page it gives us the following output now it updated the second car because the first one this one was already updated so if I reload the page the second one was updated now the second one was the first car which had VIN code 999 and price 20,000 so if we provide right here the condition based on which the car doesn’t exist in the database then it will try to create new car with the data we are providing okay let’s change this VIN code into 9999 and there is no such car in the database which has VIN code 9999 and the price 20,000 in this case LL tries to create new car with the following data but we will have an error because we are only providing price nothing else let’s reload the page here’s the error maker ID is um required fi in the database but we are providing null now this is because as as I mentioned we are only providing price right here okay let’s take the data we have Above This is the car data okay which is not commented out actually let me copy this comment it out and let’s put this right here now we have this car data I’m going to minimize this and I’m going to provide this car data right here okay now if it does not find that car it’s going to create new car with the following data and let’s provide VIN code to be 9999 because this is the car we want to create if it doesn’t exist okay so we save it we reload it we don’t see any error we see only output this is the new car that was just created if we check the database we see new car which has VIN code 9999 and it has all the other attributes we defined inside this car data and the last thing what I’m going to show to you regarding update is how to do a mass update how to update multiple cars for this uh let’s first comment out this part for this we’re going to write a cury like on car we’re going to write we condition for example I want to find all the cars which has published it to be null which is not published yet which also belongs to the user with ID one and then I’m going to call update on those selected cars and I’m going to provide associative array right here okay the properties which I want to update we can say published it to be now oops h to be now additionally we can provide other properties like set the price uh right here set the price equals 100,000 whatever we can provide any properties we want but right now for Simplicity we’re going to just update the published at date so the cars which are not published and belong to the user one will be published let’s have a look in the database how many cars are there which are not published actually all of them are published so I’m going to set null to those cars the publish that date okay so these five cars should be published when we execute the following code let’s save it reload the browser we don’t see any error so it worked we reload the page and we see published at the current date set on those cars in the following way we can do Mass update of multiple records but this one only updates a single record or if it doesn’t exist it is going to create it okay so the idea of this is going to work only on one record if the record doesn’t exist obviously it is not going to create multiple records with the exact same data right so that works only on single record based on your needs you need to decide which approach you’re going to do this one this one or if you want to obviously update multiple cars you can do this one as [Music] well now let’s talk about how we can delete data through eloquent models so let’s as as always we have a couple of options so first let me select the car we want to delete we can select by any criteria we can provide right here we close we whatever conditions you want and finally then you can call first to get the very first car based on these wear conditions or we can simply select the first car easily and then on that car I’m going to call delete method okay so this is the approach one now let’s save it and let’s reload the browser okay the car was deleted let’s open now cars table and car with id1 should be deleted let’s reload the page we don’t see that the record is gone that is because we have soft deletes activated if you scroll on the right side we’re going to see deleted it is actually populated so this is what soft deletes does on the car PHP model let’s scroll up here we have the soft deletes and this is why we added this deleted add now if we try to select car with id1 again and delete it again it is going to give us an error it does not select that car so when we call Car find with one no it doesn’t exist that’s why the car is the the car is considered ing the soft deletes and it doesn’t select the car which is already deleted okay how we can work with the actual deleted data there is a different approach for this uh we need to use with trashed as well and we’re going to talk more about this in the next lessons I don’t want to over complicate this simple lesson but right now we just proceeded delete however if we do this delete on a fuel type for example find the first fuel type and delete the record will be actually deleted from the database because the fuel type doesn’t have deleted at uh column right there and we also don’t have the same trait soft deletes on the fuel type [Music] okay this is one way how we can delete the data second way is to delete um data by IDs so on car model we can call D destroy and provide a single ID as an integer or we can provide array of IDs one and two I want to delete cars with one and two okay the car with id1 is already deleted let’s provide two and three right here let’s comment out this code we save it we reload the page then we check car table and we see now cars with id2 and three are also deleted okay uh we can also provide the IDS right here not as an array but as regular arguments like this uh in this case it doesn’t do anything because the cars already deleted but it also doesn’t throw any kind of error but this will also work and the next method to delete specific cars by certain criteria is the following we can provide we let’s say we want to delete all cars which are not published okay so we published at equals null which belongs to user ID one and then we’re going to call delete on that now let’s check on the database which cars will be deleted uh published it is not null on any of the cars but we can set null on those cars okay I saved it and those cars will be marked as deleted uh let’s let’s comment out this code okay we publish that is null we user ID equals 1 let’s delete those cars awesome reload the page now let’s check cars table and here we see deleted at is set on those cars and finally we can call truncate method on the model on any model uh truncate which will delete every car from the database so we can comment this out save and reload and the cars should be deleted but truncate actually deletes those cars from the database it doesn’t doesn’t mark them as deleted but it actually deletes them so you should be very careful when you execute truncate in this case we that didn’t need those cars anymore we learned how to select how to insert how to update the data and I’m okay the data to be gone but you should be very care ful when you need when you execute the following truncate [Music] method when generating orm models I noticed that we named our car images model incorrectly we named it in a plural form if we notice every other model we have in a singular form except car features and car images the whole idea of the model is that it should be in a singular form because whenever working with an instance of the model it is a single record of that class in the database for example when we create new car we have we we’re going to create this using new car new car type we have a single instance of a city when we are working with an object and so on the car features is kind of exception because inside car features table a single record contains multiple features such as ABS air conditioning power windows and so on however when we create a new image it is going to be new car images which is not quite accurate so what I’m going to do is to rename that to refactor it and call it into car image node car images in PHP storm we can right click on this we can click on refractor rename and it is going to change the class name as well as the file name however if you don’t follow this on ph storm you can do this manually you have to update the class name and rename the file as well and just like this now we have car image in a singular form as well but as we decided we’re going to leave car features into a plural form because a single record in the database contains multiple features [Music] now I have five challenges to you here you see all the challenges the first one is to retrieve all car records where the price is greater than 20,000 second fetch the maker details where the maker name is Toyota insert a new fuel type with the name electric update the price of the car with id1 to 15 ,000 and we’re going to delete all car records where the year is before 2020 okay pause the video right now Implement those five challenges and then come back and see my [Music] solution all right let’s see my solution how I am going to do these challenges let’s start with the first one and we’re going to retrieve all car records where the price is greater than 20,000 okay cars equal on car model I’m going to call where price is greater than 20,000 finally I’m going to call get and then we can print or iterate over the cars it doesn’t really matter car records where the price is greater than 20,000 double check it looks correct next is to fetch the maker details where the maker name is Toyota so here we have the maker maker where name is Toyota and we’re going to call first next to insert a new fuel type with a name electric we have a couple of ways to create new fuel type let’s call Fiel type create and we’re going to provide associative area right here name is electric this is the simplest way in my opinion however we can create a new instance using new keyword assign name to it and then call save as well but I prefer this this is a easiest way the next is to update the price of the car with ID one uh to 15,000 so again we have a couple of ways right here but on the car I’m going to call we ID equals to one and then I’m going to call update providing the attributes with which I want to update like price set to 15,000 and the last one is to delete all car records where the Y is before 2020 so on car I’m going to call where Y is less than 2020 and I’m going to call delete so that is all and we can execute this and have a look so let’s dump cars let’s dump maker and we’re going to see that the electric is created and the price is updated and right here the cars will be deleted reload the page okay we’re dumping something we don’t see any errors let’s now open uh fuel types here we have second electric we had one electric but now we have second electric next is we updated the price for the car with ID one to 15,000 so here we have 15,000 and all the cars which has year less than 20,000 was uh 2020 actually was deleted we don’t have such cars anymore but if we change this into 2010 and reload the page we are going to see that it should be marked as deleted here we go it is marked as deleted hey if you are enjoying this tutorial so far maybe you want to check the entire course on my website the.com where you can find quizzes The Source Code of the project is available there you can find all the modules including the deployment section the testing section which contains I think three hours of uh content regarding testing uh using pest framework and a lot [Music] more in lal’s eloquent omm relationships Define how different database tables are related to each other eloquent supports several types of relationships including one to one which is how our cars and car features are connected to each other one to many which is how our cars and car images are connected to each other many to many which is how our cars and users are connected to each other and it also supports polymorphic relationships which is not an example of our particular project these relationships allow you to easily retrieve and manage related data using methods on your models for example the car model has one one to manyu relationship with car image model meaning that each car can have multiple images defining relationships in eloquent involves creating methods in the model classes that use predefined relationship methods like his one has many belongs to and belongs to many this simplifies complex database queries and enhances code readability leral has very comprehensive relationship system in this beginner’s course we are not going to learn every single detail of these relationships instead we will focus on the most important ones and the most common ones and learn how to define and use them in our [Music] project now let’s open car model and start working on onetoone relationships we’re going to add right here two relations to a different models let’s scroll down below and right here I’m going to add public function and we’re going to name the function whatever we want but later we can access to related object based on the following name so here I’m going to call this features then I’m going to return the following thing this has one and we have to provide the relational model name in this case we’re defining relation to car features so I’m going to use car features class right here we need semicolon at the end obviously and we need to also Define it is not mandatory but is a good practice and we should do this uh we should Define the return type of this method let’s define it has one and that has one is a class imported from illuminate database eloquent relations has one make sure that you import this if your id/ editor does not automatically import it okay PHP storm or vs code whatever you’re using the Hasan method has second argument as well and the second argument is the field is the column name in the database using which the two models relate to each other in our case the car model inside which we we’re defining this method in the car fi featur model the column name which is the foring key column name is the car ID and based on the car ID car features table connects to the car however the car ID column right here is optional because LEL automatically guesses this foring key name based on the current model name current model name is the car inside which we’re defining this relation and the foring key name is guessed in the following way Lal converts the class name into snake case version which will be lowercase car and it appends underscore ID so even if we remove this foring key right here the relation will still work however just want to you to know about this you if you have a different uh Convention of naming your foreign key is like if this is called my car ID or if this is called ID for example you have to provide this foring ID in our case I’m going to delete this and we have this relation defined uh next the second relation which I’m going to Define is the primary image we know that car has many images but car will have a single image which will be its primary image and I’m going to assume that the primary image will be the image which has the lowest position in most cases it’s going to be position one so the image on the First Position will be my primary image so I’m going to define the following relation this has one we’re going to define the relation into car image we can optionally again provide forign key name car ID but this is the default one is also car ID guessed by LEL and let’s define right here has one and then we have to provide additional method right here just to make sure that Lal will take the image which has the lowest uh position among the all the images of that specific car so in our case we’re going to use the method called oldest of many by default this oldest of many is looking at at the created at column and it is taking the record which has lowest created at date time but we can provide right here a column which LEL should look at uh when taking the oldest of many record okay in our case we have to provide position right here so among many images of this specific car L will take take the one which has uh lowest position and it’s going to return that as primary image of the specific car there is a second method called latest of many if we want to take the image which has the highest position uh of all the images of that specific car and if we don’t provide a position right here a Lal will take this latest of many based on the created Edge column in our case we need um L oldest of many based on the position so this is what we [Music] need now let’s open Home controller and remove every code what we have in the index method and let’s understand how we can access relational data with onetoone relationship how we can read that data update delete or even create let me Select Car using car find and I’m going to provide one right here so I’m selecting the first car at the moment I think we deleted all cars from the database so I have to very quickly create a couple of them here is what I did I created a single car then I added a record inside car features for that car and I also created two images with dumy image path inside car images table which has which is for the car I just created so two images for the car car features and the car itself this is what I did now if we open Home controller we’re selecting this car and now I want to access this relational data such as car features for example let me use DD and on car I’m going to call features we can access this relational data with the name of the method we defined right here so we we called our method features so we can access uh with features name as a property to the car now if I save this and we open our project on the homepage reload it we see right here car features an instance of the car features which has couple of attributes and it has car ID 1 ABS 1 air conditioning one power windows one and everything else is zero this is exactly how I defined so using the following way we we are accessing the car features now let’s try to access primary image because this is also what we defined on car we’re going to call primary image save and reload here we have car features and here we have car image which has position one okay this is how we’re accessing to the primary image if we open car model and change that method from oldest of many in to latest latest of many then if we reload we’re going to see that the position will be two okay however this is not what we want we want oldest of many and just like this we are accessing the features in primary image of the car however if we want to update features let’s say for example then on the car features this is an instance of the car features then we can interact with the car features exactly as we interacted with the car model when we learned the basics of create read update or delete car features is an instance of car features class so here for example we can provide ABS to be zero and then on car features we can call save this is one way how we can do or on car features we can call directly update and providing ABS to be zero both ways is going to work so let me comment out this part and I’m going to change this DD into just dump to print and don’t die so now if we reload the browser we see that the page was rendered now let’s open um car features reload the page and we see ABS was changed into zero in the following way obviously right here we can provide um any additional features for that specific model what we want now let me try to delete the primary image as well so car primary image we’re going to call delete in the images table we have two records but if I reload the page then if we check car images table we’re going to see that the first image is gone with position one now let’s learn how to create relation first let me create duplicate of the car I’m going to very quickly do this let’s change its ID into two everything else is the same however there is no car features available for the car with id2 this is exactly what we are going to do right now let’s go in the home controller uh I’m going to comment out everything right now and let’s Select Car with id2 now on that car I am going to call features but I’m going to call features as a method not as a property and then I’m going to call Save on that relation features and here inside the save I’m going to provide an instance of car features let me just Define this instance of car features right here let’s also import the car features make sure that it is at the top okay awesome we created car features with all the columns what we have in the database and now I’m going to take these car features and I’m going to pass inside the save now I save the file I reload it we don’t see any errors which is good let’s go in the car features reload and we see second record right here which has everything false just like we provided right here when we are creating an instance we in the following way passing associative area in the Constructor make sure that you have feelable attributes properly defined however because we are creating these car features through uh relation we don’t need to provide car ID right here instead when we are creating in the following way from the car feature save LEL will automatically assign the corresponding car ID to the car features now let’s learn how to define one to menu relationships let’s again open car PHP and right here I’m going to Define another public function but this is a relation to all the images not a single image but collection of images so I’m going to call my function images from here I’m going to return the following thing as many previously we used has one now we are using has many we provide car image class and as I mentioned as a second argument we can provide the relation name which by default is car ID so we don’t need to do this that’s awesome as a return type we have to Define has many relation and again make sure it is imported in the following way so we just defined this relation of has many now let’s go into home controller and learn how to access this relation I commented out all the code inside this home controller index so now let’s Select Car by id1 then on that car we can access to the relation through images with the same name what we Define in the method now if we have a look in the browser reload it we’re going to see a colle collection eloquent collection there’s only one item and that item is instance of car image and that has id2 car id1 image path and position as well if we have a look in the car images table in the database we see that there’s a single image only for that car let’s duplicate this let’s give it id1 for car id1 test and position one I’m going to save it now let’s reload the page and I see items too now there are two car images for that specific car now let’s learn how to create relation as many relation so I’m going to create new image for this first I’m going to create an instance of car image and in the Constructor let’s just provide image path to be something and we have to provide second argument second column position equals um let’s provide position two okay and I’m going to just delete that second image right here okay so we have only one image on this car now I’m going to try to create new image on that car images I’m going to call Save passing the image as argument now if I save this and reload in the browser we don’t see any error which is good now let’s open car images reload it and we see second image right here there’s a second option second way how we can create image on the car on that car images I am going to directly call create and it is not necessary to create an instance of the car image instead we can provide associative array of attributes like image path something two for example and position three let’s comment out this part we save it reload it let’s check the database table and we see one more image in the database there is also possibility to create multiple images with a single commment let’s say the following one car images I am going to call method called save many we’re going to pass an array right here where each element of the array is an instance of car image so we have to provide new car image right here and provide attributes columns for the car image like let’s provide position four and I’m going to duplicate this with position five okay or another way is to call on car images create many which does not require to create instances we have to provide array but each element of the array can be directly an associative array not an instance of car image so that’s the difference now let’s create six and seven position images okay awesome now if I reload the page this will create two images this will create two more images and finally we’re going to have a lot of images let’s reload the page let’s check car images reload it and here we go now let’s learn how to define many to one relationship and how to work with that related data again let’s open C PHP and I’m going to Define new relation to car type we know that car belongs to car type so every car has one car type but car types have multiple cars now let’s define this relation and we’re going to use the following method this belongs to car type class again the second argument will be the uh foreign key name we can Define it car type ID D but LEL is intelligent enough to identify that because car belongs to car type class it will try to search column named carore typeor ID even without providing so we don’t need to provide it however if your foreign key name is different such as my car type ID for example you can do it and you can provide this forign key okay awesome let’s find this uh return type which will be belongs belongs to and as always make sure that it is properly imported right here okay we defined this this relation car type and we can also Define the inverse relation so if we open car type from here we can Define cars just like we defined images inside the car where car has many images inside car type we can Define that car type has many cars so this has many car class and we Define here has many class as well okay and as always make sure that import is edit right here so I’m not going to mention this every time but whenever you define this has many if your IDE PHP storm or vs code does not automatically import this as many or as one or belongs to you have to write it okay so we defined these relations and now let’s learn how we can access that parent relation or how we can select data by relation let’s go in the home controller I comment out all the code let’s scroll up slightly and now let me select um the first car as as I generally do car find one awesome now let’s try to access to car type in the following way it’s pretty straightforward let’s dump with is the car type of the car reload the page and we see instance of car type which has two attributes and it its name is actually sedan okay let me try now to select car type by its name car type where name equals Edge and let’s select first and let’s assign to a variable car type should be car type single car type now I want to select all the cars and there’s a special method for this where belongs to car type and then we can call get so using the following way laravel will return all the cars which belongs to the given car type that is awesome now let’s just print those cards save reload the page and we see a collection but because there are no actual cars based on the following car type it returns an empty collection okay let’s fix this let’s go into car types and see what is its ID it’s ID is two now let’s go into cars and change the car type ID into two for both of the cars now we have two cars with the car type ID of hchb and here we are trying to select the cars which belong to hatchback let’s reload the page and here we see two items those are two cars which belong to cart type ID hedback that’s pretty handy and because we selected the card type right here now we can try to access all the cars of the hedback in the following way so this is one way probably long way how you can do the same thing but let’s try to access let me Dump Car type cars we Define this relation of cars in the car type model and we can access to all cars for the following given car type in the following way so that code actually is the equivalent of this so if I simply replace this part that’s pretty cool okay let me comment out this part and it’s going to give us the exact same result all right I commented out all the code about now let’s select the first car and I’m going to select a different car type and I want to change the association of that specific car from whatever it has right now into this new car type one way to do this is to change car type ID to be selected car types ID and then on that car we can call Save which will update the car type ID in the database so the sedon has car type of one our first car has car type type of two in the following way we are changing the car type ID from two to one but there’s a second way to do this and on that carard I’m going to call Car type relation and then I’m going to call associate providing the new car type all right and that is all and then we have to call Save on the car now let me comment out this part and let’s just reload the page now let’s check the database in car table and as you see C type ID was changed from two to [Music] one now let’s learn how to work with many to many data first let’s Define relations we have one many to many relation example in our database schema and that is cars related to users through this favorite cars table all right let’s open car model and I’m going to define the following relation public function let’s name the relation favored users favored users all right um favored awesome let’s return this belongs to many okay this is a new method uh this the car belongs to to main user and here we have couple of more parameters to provide the second argument to provide right here is the many to many table Name by default LL will take those two model table names like the cars and users and we’ll assume that the pivot table the table in between this table has the name like cars users but this is not our case so we have to provide the pivot table name which is favorite cars this is how we call the table name then we have to provide the foring uh pivot Keys like what are those two columns car ID and user ID so Lille will uh the first uh like foring pivot key is the column using which the pivot table relates to current model in the current model is the car PHP so by default Lal will assume that that is the current model name snake case version s uh suffixed with underscore ID so Lal will assume that the forign pivot key is carore ID which is actually correct this is exactly what is the column name in our database car ID right here the second argument is the related model column name so what using which column the this pivot table connects to the related table which is the user model okay and this is user ID so Lal will guess this car ID and user ID by default so we don’t need to provide them however if the names are different then we have to provide them okay so in our case we can just omit those two columns awesome let’s define now belongs to manyu return type here and it should be imported at the top we defined favored users right here now let’s open user and we’re going to define the inverse relation let’s call this favorite cars okay let’s return this belongs to many car then we have to provide the table name favorite uncore cars and then again the column names which level will assume U correctly so we had to provide right here the current model name which would be user ID and then we have to provide car ID but again LEL will do this instead of us we don’t need to provide them so here we need belongs to many okay we Define this relation because we don’t have model defined for these favorite cars whenever new record is created inside the favorite cars the created it and updated eight columns will not be managed we don’t even have have those created at and updated at columns defined in these favorite cars but uh in a different example you might need those two columns created it and updated at okay LEL actually gives you possibility to provide second method right here with time stamps and if you provide this with time stamps Lal will assume that this pivot table has those two columns created at in updated it and whenever we’re trying to create uh Records inside this pivot table through this relation LL will automatically provide those created that and updated it columns for us we can add uh obviously we don’t need this in our case but the with time Stamps will be used only when we are creating records through this favorite cars relation but not vice versa not from favored users relation if we want to manage uh the time stamps from this favored users relation as well we need to add this with the time stamps right here as well however as I mentioned we don’t have those created de and updated columns so we can completely remove them but just for your for your information I wanted to mention that part as well now let’s open Home controller in the index method comment out everything and learn how to select that related data I’m going to select again car with ID one and on that car we have favored users which will return all the users which added that specific car inside watch list inside this fa cars favored users okay let’s dump this and have a look in the browser reload the page this returns empty collection because there is no records there are no records in the favorite cars let’s open favorite cars and I’m going to add two records car ID one user one car ID 2 and user one okay great I believe we have at least two cars don’t we yeah we do have and at least one user we do have awesome now we are selecting all the users which added the first car into its favorite cars reload the page and we see a single user which is an instance of up models user and that user is our user what we have in the database join example.com so we can access in the reverse way for example we can let me duplicate this and we’re going to change the variable into user and change the model into um user as well so let’s comment out this part we selected the user let’s import the model app models user model and then I’m going to access favorite cars of the user user favorite cars we are using the exact same name of relation what we defined in the models right here awesome so we save it we reload it and we see now a collection of two items where each of them is an instance of up models car and those are two cars what we have defined um in the cars table in the database now let’s say we want to create new records in this pivot table so how we’re going to do this let me select the user and that on that user let’s say that the user added a couple of more cars in the watch list okay so we are going to do the following on this favorite cars relation as a method we’re going to call method called attach and we have to provide array right here with the ID of the cars okay so for example one and two uh let’s actually remove everything from the favorite cars okay now the the particular user does not have anything in the favorite cars we selected that user and through this favorite cars relation we are attaching cars with id1 and with id2 additionally if there are couple of more columns in this pivot table um additional columns you can provide those additional columns as a second argument of this attach method like column one which has value one in our case we don’t have it but you know how to do it if you have it okay so this is when you attach when you just create new records how however and let let’s actually try this let’s reload the page everything is good let’s open now favorite cars and we have two records right here now let’s say that I want to delete delete every favorite car which exists in the database and synchronize with the new values okay instead of attach for this we have a second method called sync which deletes all existing values in his favorite cars and creates new one for example that new one might be three we at the moment don’t have car with ID3 but I believe that still work no that doesn’t work so if we create let’s do like this if we open cars duplicate that with ID3 save that now in the favorite cars let’s create okay so we created again those two cars in the favorite cars so user with id1 has car with ID one and two in the favorite cars the sync will remove them and only the third car I save I reload we don’t see any errors let’s open favorite cars and we see only single record car ID3 this is how the sync works also if we want to provide additional columns like I showed to you how you can provide additional columns in the attach we can provide second argument right here but the method is different it is not sync it is sync with p values okay and then we can provide right here an associative array with column one value one or whatever you have in your database okay great let’s comment out this part again and the last thing I want to show to you how you can delete detach that data on that user through favorite cars I’m going to call detach and provide the IDS we want to detach CCH for example one and two but we want to leave ID3 uh let’s uncom the user we need the user at the moment we have only one record right here um ID3 but we can again add ID one and two for user one now we have three cars and I want to detach one and two so the cars which have ID one and two so I save this I reload it let’s check favorite cars and those were removed if I want to detach everything I can just call detach without any argument so in this case if I reload there will be no favorite cars uh for the user id1 this is how you can work with the main tomain data and obviously you can do this through inverse relation as well we used favorite cars right now but you can also use favored users as well if your like main class is car and you want to work with the users adding attaching users to that car or removing users from that [Music] car okay now let’s define all the remaining relations on every model we might need in the project so we have C type generally my personal convention is to have belongs to relations at the top and then has many relations so I’m going to move this car type um at the top right here and then I’m going to Define all the remaining belongs to relations okay so we have a couple of them in this project based on the based on the database schema we see that the car has um maker ID so car belongs to maker and model and fuel type and user as well and CT as well so there are a bunch of so let’s define them fuel type return this belongs to fuel type and here we need belongs to as well so we have to type this it’s going to take some time but we have to type this then we’re going to Define maker return this belongs to maker you know what I’m going to try to speed up a little bit and I’m going to just copy and paste this method couple of times okay so I have maker the next one is model so I’m going to change the name right here and the actual model up models right here uh next is probably the user who is the owner of the car so we can call this user but I prefer to call this owner okay and that is user okay great but in this case I want to also Define the actual foreign key name like this is user ID uh through user ID it is not owner ID so it is user ID based on which the current model the car model connects to the user table okay I had some issues that in certain cases LEL was trying to use owner ID instead of the user ID so let’s just provide this foring key right here the next is to provide City and the related class will be city um I think we finished belongs to relations so we have let’s remove it we have features uh then we have primary image and we have images as well and we have favored users okay great now let’s open next model which is car features the car features has only one relation and this is belongs to car let me duplicate this belongs to and put this here uh but we’re going to change this car and car here okay let’s move up we have this belongs to imported which is great and car features belongs to car that is correct now let’s continue and let’s open car image and car image belongs to car car model here next let’s open car type and the car type actually already has cars relation defined here which is has many cars so this is something I will need in couple of other methods couple of other models so I’m going to copy that and let’s go into City and City also has many cars City also belongs to state so let’s define belongs to relation but I’m going to do this above cars so public function State return this belongs to State model belongs to okay so we have these cars copied let’s open other models such as fuel type and I’m going to paste this right here maker I’m going to paste this right here however maker has multiple models so I’m going to duplicate these cars and let’s change this into models and the actual model will be model up models model okay that is good let’s now open model which has multiple cars many cars and we have state which has many cars and state also has many cities so we can Define cities here and City model right here okay and the user also has many cars the user actually is an owner of the car so the user has many cars I believe we defined all the relations but let me double check inside car we have the city and owner and model and maker and fuel type and car type I think that’s everything what we have in the schema perfect double check features features has um belongs to car that’s great image belongs to car car type has multiple cars city has belongs to State and has many cars fuel type has many cars maker has many cars and many models uh model has many cars state has many cars and many cities and user has many cars the one thing we probably missed is that model belongs to maker so we Define here relation to maker return these belongs to maker class belong belongs to that’s it a factory in Lal is a tool to generate fake data for models it makes easy to create test and see data it defines how a model should be created including the default values for attributes using factories you can quickly generate multiple instances of a model with realistic data which is helpful for testing and database seting factories in LEL are typically located inside database factories folder by default there’s only one Factory user Factory if we open it this is how it looks like it extends the factory class which is coming from illuminate database eloquent factories Factory it has the main method called definition which returns an array associative array and the key is the field name the column name for the user table and the value is how the data should be generated so in this case right here we are using the fake function which always generates the fake name here it generates fake and unique email address here it takes the current date here it takes the random string and so on using the following way we’re going to Define factories for every hour model to generate some C data to generate new factories we’re going to execute the following comment PHP artisan make Factory and we have to provide the factory name like I’m going to create new Factory called maker Factory okay which will create a factory class for maker model I’m going to hit the enter however if we want to generate the model itself and the factory at the same time we can do the following make model maker and provide flag called dasf this will create maker model alongside with its related Factory class which is something we don’t need at the moment but you should know now let’s open this maker Factory and updates its definitions so from here we’re going to return the name and I’m going to use now this fake function which is is using the php’s faker package which always generates some fake data it has bunch of methods and one of them is called word so every time I want to generate new word for my maker class okay let’s also open user Factory and I want to generate uh random fake phone number for the user so I’m going to update this and let’s use this fake method and then I’m going to call method called numerify and I have to provide the format like I want to numerify the following string and I’m going to provide this hashtags right here this will generate three digigit number and let’s provide couple of more okay so every time when we try to create new user using Factory it’s going to have n digigit phone number inside there now let’s talk about the naming of factories in the discovery conventions by default factories as I mentioned are located under database factories and if the factory name is named properly uh it lateral will automatically connect to the corresponding mode model for example if we have a maker model which is located under up models and we create maker Factory in the database Factor stable uh folder then LEL will automatically detect it Discover it and connect that factory to that model OKAY however if we name our maker Factory something different for example we call it car maker Factory then Lal will not be able to connect that car maker Factory to the maker model and we have to do this manually now let’s open maker model and do this manually to do this manually we have to Define new function right here and that function should have a specific name like that should be new Factory static protected function and that should return an instance of the factory in the following way whatever we’re going to call our Factory let’s say it is car maker Factory we are going to call new on that factory okay so in our case we don’t have this car maker Factory but if we had then we should return it like this or we can return maker Factory if we want but that doesn’t make any sense because our maker Factory has the convention based name okay but I hope that makes sense uh but this is not enough when we Define this new Factory static function and we return the the factory new instance then we have to go to this car maker Factory and we have to also Define protected model right here and that model should be maker class only after this that maker Factory car maker Factory whatever we call it will be connected to this maker model okay just like this okay because we follow the convention I’m going to remove this I’m going to remove that new Factory method from here as well and we can try to generate some [Music] data now let’s see how we can generate data using factories let’s use maker Factory what we just created and then on that maker model we’re going to call method called Factory on that factory there exists a couple of methods one of them is make that creates an instance of maker model and returns that so right here we have this maker model and we can print that however if we want to create new maker record in the database we should use right here create instead of make make simply creates makes that record an instance of the maker moduel it returns it but it does not put that in the database however create method is what inserts the record in the database now if we open makers right here we see that we have two makers all right let’s open browser reload it and right here we see maker instance of maker and there’s a new word new name Amit so that’s a like a fake word it doesn’t mean anything but in the database in the maker table we see new record okay so that’s the difference between the make make simply creates an instance of the maker class and returns it but it does not put the in the database the create puts it in the database however if we want to create multiple records in the database we can also provide right here count let’s provide count 10 for example and execute that reload the browser and now the returned result is a collection instead of a single instance now this more specifically is Makers array makers collection as we see and it has 10 items inside there each of them is an instance of maker and if we check Maker’s table in the database we’re going to see 10 more records made in the maker table in the database if we want to just create instances of maker models and don’t put them in the database we can use right here make method again so this creates the instances of maker modu and returns it but don’t does not put them in the database we also have options to provide additional properties in the men make method right here or in the create method right here for example I want that every maker to have a specific and hardcoded name or maybe we can use um different example let’s undo this and I’m going to use now user Factory I’m going to provide create and let’s provide name right here to be zura so this creates let’s un let’s comment out this part so this creates new user with the name zura and that puts the user in the database as well however if we want to create multiple users we can provide count right here and all users will have name zura we can execute this now let’s open users table and right here we see 10 more new users with name zura obviously we can provide right here as I mentioned make which simply creates an instances of user classes and returns them but does not put them in the database there is specific method which gives you possibility to override specific fields and that method is called State you can provide associative array and you can provide your Fields right here in this associative array so that does the same thing as providing name zoraa right here in this make and that obviously works for create really it doesn’t [Music] matter the following code will create 10 new users however I’m going to introduce a new method called sequence which gives you possibility to alternate different values when overriding the fields for the models so here I’m going to provide two arrays the first one will have name zura and the second one will have name John now when we execute the following code it is going to create 10 users the first one will have name zura second one will have name John then the third one will have name zura and the fourth one will have name John and so on in the user table right now we already have 11 columns this is the last 10 records we created 11 um records excuse me these are the last 10 records we created I’m going to delete them okay now let’s open the browser and reload it and now let’s check the users table now as I mentioned we have zoraa John Zur John and so on sequence method is pretty powerful method which gives you a possibility to provide different values when creating uh multiple records for example inside the sequence we can ALS o provide um closure function we can provide regular F function or Arrow function as well let me provide Arrow function and we have to accept an instance of sequence in this Arrow function we need arrow and then I’m going to return associative array where I’m going to return name but the name will be something Dynamic such as for example name space and then I’m going to use sequence index okay I’m going to comment out this sequence method and I’m going to leave this now the sequence index increases for every new user because we have 10 users the sequence will increase from 1 to 10 and for every new record before it is inserted into into the database the name will be changed with name one name two name three and so on let’s open our users I’m going to delete again these last 10 records let’s reload the browser let’s reload users table and now we see name zero name one name two and so on obviously if we want to name it to start from name one we have to Simply add one right here but this is how sequences are working a factory stating LEL is a way to define specific variations of data when using modu factories states allow you to Define different sets of attributes for the model and making it easy to create various types of data without duplicating the code if we have a look at the following code this creates 10 users and all of them will have email verified at to be now if we open user Factory we’re going to see that email verifi dat right here is set to now now but we are actually overriding the state from here however in the user Factory there exists a method called unverified which defines the state and inside the state which is an nrow function we are returning the following area email verified at equals null so instead of executing and providing state right here we simply can provide unverified right here the method which is defined inside user Factory that does the same thing and if we execute the following code it is going to create 10 users and all of them will have email verified at toal by default there also exists one predefined State method similar to unverified and this is called trashed that trashed will create records and each record will have have deleted it to be something so we have deleted it column only on cars when we create the cars we don’t want the cars to be deleted but if we want to create deleted cars we could provide trashed when creating cars and that is going to create cars which have some value inside deleted dat obviously this is not relevant for users but because we’re talking about States I wanted to mention that there is a predefined trashed um state which provides some value inside deleted Ed column when creating new records using factories we have possibility to add a certain call back when the record or records is created or when the record or records are made and that happens through after creating and after making callback methods so after making will be executed when we call right here make and after creating will be called uh when we call create right here and that callback function is executed for every single user that is created and that is very helpful because inside that callback function you can put information you can uh create some logs or you can even create additional information for that specific user for example we create user and then we can create uh like additional cards for that specific user or we can add additional information inside the database table for that specific user now let’s create new Factory for model PHP artisan make factory model Factory now obviously maker and model has one too many relationship now let’s see how we can create relational data Factory with models but first we have to open model Factory from database factories folder and I am going to Define name right here to be fake word great we can close this now let’s go in the home controller and let’s define Factory with models so we’re going to use maker Factory and then let’s create five factories for example and each Factory needs to have five models so for this we can use method a magic method called has and whatever is the relation name from maker to uh model so the relation name from maker to model is called models okay so basically we have to provide right here uppercase m models has models and we can also provide count how many models it should create for each maker so the name the relation name is converted into a so-called Pascal case so if this is models this is going to become uppercase a moduls so if this is called my models then we should have has my models like this okay let me undo the change and finally we’re going to call create and now this is going to create five five makers and five models for each maker now let’s open maker table uh I believe we can delete everything else from here and let’s also open models and we have four models right here let’s open the browser reload it now let’s open moduls and we have 25 more moduls inside here and five more makers inside here and the maker ID is is uh taken from the just created maker from the makers table okay uh these has models has additional capabilities for example if we want to override certain state right now our models table has only name so if we want for example to overwrite that name and provide specific model for every maker like test for example let’s create just one maker and one model for that maker and let’s reload the browser and and let’s go into models reload it and at the bottom we have new uh model which has the name test so this associative array gives us possibility to provide additional or override the fields um inside this relational model uh also this H model has ability to provide right here instead of array we can provide a function so if we provide function that function except array of attributes um attributes and we can also take the parent model which is maker in our case so I can accept the maker and then I have to return an array uh from here return associative array so this is helpful sometimes we want to take some information from this parent model like maker some property and let’s say that the child model has the Cent models certain property for example if in practice we’re going to create later we’re going to create cars and users and every car has phone and in most cases that phone will be a phone from the users table okay from here so if we change this and let’s say that we are creating user right here uh with has cars let’s imagine the following case and right here we’re accepting user this is user and then we are overriding those uh the the phone so from here we can return phone to be the same as user phone and every car will have the same phone as just created user isn’t this awesome for me this is really cool let me undo this because we are not yet creating users and uh cars let’s talk about makers but I just wanted to show you how you can do this thing also this has models is a magic method uh and that only works if there is a relation defined on the models inside the maker however there also exists uh I’m going to comment this out there also exists a general method called has and right here we can provide other Factory such as model Factory and then we can provide count um three for example so now this is going to create one maker and it’s going to have three um models so let’s reload this let’s reload this and now let’s refresh the browser and inside makers we have one more maker and for that maker with ID 20 there should be three more models in the models table if your relation from maker to models has a different name so if it has models name then this code is going to work however if the relation name is different for example car models then we have to provide that relation as a second optional argument inside this H function okay if the relation name is called models which is um like a singular lowercase version of the relational class model class right here then we don’t need to provide that relationship right here because LEL guesses that automatically based on that model name okay however if we have a different name like what I mentioned car models right here we have to provide that relationship here okay I’m going to remove this because we have a very standard name it is called models that’s why we don’t need to do anything [Music] here now let’s see a reverse example where we create model uh for the factory and we create Factory as well so the following code will try to create five mod models however this is not going to work because in the model Factory we don’t have a maker ID defined and that is actually mandatory column in the database however when we create model we want to create it for a specific Factory and that’s why we can provide right here magic method like we had has models we can provide magic method called for and the relationship name so if we open mod PHP it has relationship called maker then we have to provide maker here so we want to create five models and all of them should be for the same maker okay U this is going to create one maker in five modules we can also provide additional fields for this maker for example name to be um Lexus okay so it’s going to create new maker with the name Lexus and five modules so I’m going to save it reload it let’s open makers uh table reload it we see Lexus right here and if we check moduls table we’re going to see five models all of them has maker ID 21 which is actually Lexus there is a generic method called four inside which we can provide another Factory like we can provide maker Factory and we can also provide like state for example to be Lexus similarly what we had above so these two lines of code are doing the same thing however make sure that the relationship name should be maker from model it should be maker otherwise if it is for example car maker right here then we have to provide again the this relationship name as a second argument of these four method car maker right here so if we name our relationship in a um standard way then we don’t need to do this we also have possibility to use an existing maker so if I Define in maker right here maker Factory call create then we can use that maker object and provide for the maker object right here let’s create five models all of them will before the maker created above and obviously we can provide state or anything to this maker what we want now let’s go ahead and Define the remaining factories PHP artisan make vectory uh car type vectory um hit the enter the next one is going to be the fuel type Factory hit the enter we’re going to we have already have maker Factory we have modu Factory let’s create State Factory let’s create C victory victory uh we’re going to create car Victory let’s create car um car features Factory and car image factory car features Factory and car image factory okay great now let’s open victories and let’s start with the um where’s car type here’s car type Victory Fuel type Victory State City um let’s open then car factory car features and car image and we’re going to Define definitions array for every Factory let’s start with the car type Factory here we’re going to have name and the name should be some some fake in almost all cases we’re going to use fake function so we’re going to start um assigning some values using fake function which gives us a huge object of Faker PHP and then then we can call certain methods on that so in this case we’re going to um use the method random element but we have to provide the values and the faker will take randomly one element from this array like we can provide sedan here we can provide SUV we can provide truck uh why did I provide all in uppercase uh we can provide like van um Coupe or how it’s pronounced I don’t know and like cross over that’s enough uh let’s go in the fuel types and here let me copy this line to save some time paste here and in this case we have to provide um yes for example we can provide diesel Electric and hybrid okay the next is to go into State Factory which has a name and there actually exists State um I believe there is exist State why why it doesn’t have to complete I don’t know but there exists a state function in the definition so we’re going to use that and it’s going to create new random State now let’s open City Factory the name will be fake and here we need City here it is uh the city actually needs state ID as well but we are going to handle this when creating the data okay so we’re going to leave this right now and then we have car factory which is the largest one and we are going to spend some time on this so we need to provide maker ID here and here what I’m going to do so I’m going to select some random ID from the makers table from the database so I’m going to use maker model then I’m going to use the function called in random order so that function exists and that returns makers in random order so because this is in random order I’m going to pick the first one and then I’m going to take the ID of the first one okay awesome then we need model ID however the model ID should be from the same maker okay it doesn’t make any sense on the car to have maker ID to be Lexus ID for example and the model ID to be something which is from Toyota so doing the same thing for model what we did for maker doesn’t make any sense because because it is going to pick uh any model ID in random order and we don’t have any guarantees that it will be from the same maker so here we’re going to use function we have that ability as well inside that function we’re going to have attributes and then from that attributes we’re going to take the maker so this is where’re going to what we’re going to do so on model we’re going to call we we’re going to set select all the models which has maker ID to be from attributes maker ID this attributes maker ID is already generated this generated maker ID so we take it and filter models based on this maker ID then we can call in random order then we can take the first and then we can take its ID and of course we need to return that awesome next we have y here which is going to be fake y next we have price and for the price I’m going to get um random number in some range so let’s use fake uh and on that fake let’s take random uh there’s no such method random integer we have random float and here’s what I’m going to do on that random float we’re going to provide um first is the maximum decimals and we can provide two then we are going to provide the minimum and maximum values like minimum five and maximum 100 okay so this gives me any random float number from five to 100 okay I am going to cast this into integer so this is how I’m going to cast it into integer so any decimal things will be lost and now I have an integer value from five to 100 and then I’m going to multiply this on 1,000 and this gives me a random integer value from 5,000 to 100,000 okay next is to generate VIN code and for this uh we are going to use Str Str Str Str um support class and we’re going to call random and provide the 17 which is typically the VIN code length but I’m going to also use St Str to uper to convert that all into uppercase okay next we need millage sorry if I don’t pronounce this correctly um then we are going to call again random float on that from five to 500 let’s cast this on Integer and we’re going Tok multiply this on 1,000 awesome then we have car type ID which I’m going to pick a random ID from the database like car type in random order we take the first and ID next we have fuel type ID and let me duplicate this fuel type ID into the model will be fuel type make sure it is imported after fuel type we have the user ID I’m going to duplicate this again then we have City ID I’m going to duplicate this again user user ID City ID let’s use City model here user model here and next excuse me I lost field type ID I’m going to move this up so C type ID field type user and City ID after City ID we have some address so let’s provide some fake address okay next is provide to provide the phone and for phone I’m going to use a again function we get array of attributes then I’m going to select the user user find based on the attributes user ID and then I’m going to take the phone of that user awesome next we have the description which should be some text I’m going to use fake text with 2,000 characters maximum 2,000 characters and finally we have published a which is a Tim stamp and I’m going to use the following way to assign a time stamp randomly so I’m going to use optional so this optional means that it is going to generate uh the value randomly okay it is it might not also generate the value and this optional has also probability like 0 um n so in 90% of the cases this will generate whatever I provide here so it is going to provide date it is going to generate date time date time and I also want to provide date time between so I don’t want any Daye time but I want let me move this down I want date time uh minus one month in the past and plus one day so the if I remove this optional this will always generate the daytime between minus one month and plus one day adding that optional and that optional can be added on any method right here we can also add this optional to this um uh not right here but we can add this optional to and like a VIN code for example or or any any other uh property okay so this with 90% probability generate the following data okay so we generated the car factory we defined the definitions for carfactory let’s open car factory car features Factory and this basically is pretty simple so I’m going to copy and paste this part so we have car ID which I left this hardcoded one or we can completely delete this because we will provide let me actually delete this uh because we’re going to create these car features for the cars and we’re going to Define for which cars the feature is created when actually creating the data every other property right here ABS air conditioning power windows and so on all of them are bullan values okay you can um just take the time and um type this or you can go into you can go into features car features and we can copy those columns all of them and we can paste them and we can do the thing okay I try to save some time but I also don’t want to do things and you feel annoyed that I did it in a very Rush way so I want you to follow with me and um just create one then duplicate it couple of times and just change the names okay I hope you define this now let’s open a car image factory and we’re going to define the last one it is going to have um a car ID but I’m not going to provide car ID as well so we just need image path which will be um something random like uh let’s use image URL random image URL okay good and then we have have to provide a position the position is kind of interesting uh I’m going to provide function here with array of attributes and then I’m going to return I’m going to find uh car based on the attributes car ID I’m going to access its relation called images and then on that relation I’m going to call function called count to get how many images that car already has and for that new image which should be created uh through the following definitions I’m going to add one however when we actually create images we might even overwrite this position completely okay so you should also keep that in mind okay that’s it it we have the definitions for all the factories now I want to create data for many to many relations I want to create a user with five cars and we’re going to add those five cars in favorite cars table for the created users because we already have defined uh the definitions for all the factories cars can also be created now let’s use user Factory we’re going to use has and then I’m going to use car factory count so this creates um let’s provide five here this creates user with five cars but here I’m going to provide the relation so without uh the relation it is going to create a user in five cars and that user will be user ID for that five cars right here I’m going to provide the relation name which is called favorite cars I think this is how we named favorite cars in our user we can always access and see double check it make sure it is correct and then we’re going to call create okay great now let’s open the browser reload it and let’s have a look in the database let’s open users a new user should be created this is the new user which was just created then we should have five cars let’s check the last five cars were created and there should be also records in the favorite cars let’s also check what is the user ID of those five cars it should be a random here we see it is random user ID it’s a 26 28 29 so it is random random this is how we defined in the car factory however if we check favored cars we see five records and all of them all these five just created cars are for the same user which was just created for this uh Rosalia okay and in the following way this is how we can Define find one to many relationships if we want to provide if we have uh this pivot table the favorite cars pivot table which has different columns additional columns and we want to provide some information inside that additional columns we can use a second method called has attached okay here uh let me duplicate this has attached first we have to provide the factory like we are doing here then we have to provide additional columns like column one and its corresponding value one whatever it is and then we have to provide this relationship name so in our case we don’t need any additional columns inside this favorite car table so this is something we don’t need this is something what we need and we test it and it works perfectly [Music] a cedar in laravel is a class used to populate the database with simple and test data Cedars allow developers to quickly insert predefined data into database tables making it easier to set up a consistent development or testing environment they are typically defined in the database seeders directory and can be run using the PHP Artisan DB column seed command seeders can call other SE ERS and use eloquent models to insert data ensuring relationships and constraints are maintained this helps in simulating real world data scenarios for development and testing purposes now let’s open only one CED database Cedar in our project and if we check its run method we see the following code this uses user Factory and it creates a single user with name test user and email test example.com [Music] to create new Cedars we’re going to execute the following Artisan commment PHP artisan make column Cedar and we have to provide the cedar class name let’s create users Cedar class hit the enter the class was created now let’s open user Cedar and and every Ceder has run method we should put creating user code inside run method I’m going to copy this database Cedar user Factory create into user Cedar and let’s just change the names into test user 2 and test 2@ example.com to run seeders we’re going to open Terminal and we’re going to execute the following comment HPR design DB colum seed the following command will run the default Cedar which is database Cedar however we can provide custom class or the Ceder using the following flag D- class equals users Cedar when we execute this seeding database was completed now let’s open users table and as a very last record we see test user two which was written in inside users Cedar by default running Cedars are not all loow on production because it is going to maybe delete the database maybe create something in the production database based on the environment variable up which right now is set to local but when you deploy the application and production this needs to be set to production okay so and you are not by default allowed to execute ceders if you still want to run ceders on production you have to use the flag Das Das Force additionally if we run the migrations and we want to execute Cedar classes as well we can use the following command PHP Artisan migrate D- seed flag this will execute the migrations and also it will execute the default Cedar which is database CER the dash dash seat flag can be applied to migrate refresh and migrate fresh as well if we want to use one Cedar into another Cedar for example let’s put users Cedar into database Cedar for this we’re going to open the database Cedar and we’re going to use this call method providing a single class or array of classes and here we’re going to use users Cedar class in the following way when we execute the default Cedar it is going to first create the user then it’s it is going to execute the user Cedar now let’s bring up the terminal and I’m going to execute PHP Artisan migrate fresh D- seed this will drop all the tables create them and also apply the seeders and finally it is going to create two users let’s open now users table every data is deleted right now and we only have two [Music] users first I’m going to delete users Ceder because I don’t need second Cedar I’m going to put every code to create data in my database Cedar let’s delete this user Cedar completely let’s delete the comment as well next I added couple of comments in Sample data using which we’re going to create CED data for the database so we have to create car types with the following data using factories we have to create fuel types with the following data we have to create states with cities and here I have States alongside with its cities we have to create makers with their corresponding models right here here I have typo and we have to create users cars with images and features so this this is going to be the most challenging one let’s do it one after another and you can treat this as a challenge okay so you know what should be created right here you can pause right now you can try to do this on your own if you are not able to do this on your own then come back and see my solution it is going to be uh pretty clear like step by step we’re going to make it very clear and we will know how to define a very complex see data through factories inside our Cedar okay this one is pretty easy we’re going to use car type vectory then I’m going to use sequence and here I’m going to provide array of those values so here I have U whatever like nine values so I’m going to take all of them I’m going to put them right here inside the sequence but each element inside the sequence needs to be attributes for my car type so I am going to create array like this name corresponds to the value so we have car type Factory sequence then we need to call count and this count should be the exact same number how many elements we have here like 1 2 3 4 5 6 7 8 nine so we have totally nine elements and finally we’re going to call create okay awesome so when we execute this it is going to create uh the following the nine car factories and it’s going to try to use the following sequence okay awesome next fuel types now you can do this on your own I assume because it is very identical to the car type let’s use fuel type vectory let’s use sequence we need array four times and then we can use the following values name corresponds to gasoline and then let’s change the second one into diesel electric and hybrid we call count four then create great next is to create states with the corresponding cities okay so in this case we’re going to iterate over our states and create each state with its own cities okay let’s do this for each States is a state then we’re going to call State Factory and here I have to provide um State method so that State method is different from that state obviously so that State method gives us possibility to provide the values as we already learned in the factories section so we have to provide custom name for our state and this is going to be State actually we have here State as a key and the value will be cities right so we’re going to take this state name and provide it when creating new state however we need to create related data as well and for this we’re going to use Hees method inside Hees we’re we’re going to use City Factory we need to provide count and we need to create as many cities as many elements we have right here and in this case I will just take the count count of cities variable okay how many cities that specific state has the same amount of cities we’re going to create next we’re going to call sequence and in this case I want to generate array like this for cities okay so if I provide array like this inside the sequence for cities then I’m good so uh we have the count the exact number of the cities and then I just need to provide the sequence in the correct order in this case I’m going to use uh the following way so I’m going to use uh array map function which accepts a call back so I’m going to uh provide Arrow call Arrow function here okay uh that map obviously needs the second argument the C is to iterate so I’m going to iterate over my cities in inside the call bag I’m going to get CT and then I am going to return the following array where the name corresponds to CT so this returns an array all right and that array basically will look like this where each element is also array and it has name and the CT name so this sequence is kind of like a multi-purpose function we can provide here an array like we did um like we did right here or we can even provide multiple Arguments for example if I remove the square brickets right here and we just provided multiple arguments this is going to also work so in our specific example we can leave this array map as it is or we can use three dot notation to destructure this and provide um separate values inside the sequence both is going to work okay we can leave this as an array map and finally on that state Factory we are going to call create awesome so in the following way states and cities will be created now we have to do something similar for makers and its models okay let’s iterate over our makers we have maker and models then on maker Factory we’re going to call state to provide the name for the maker then we’re going to call has that is going to be model Factory we’re going to provide count which will be count of models and then we’re going to provide sequence which will be array map we provide an arrow function we accept model inside this Arrow function we return name corresponds to that model and the second argument of this array map is the array which needs to be iterated and this is going to be models finally we’re going to call create on that um maker Factory and that is it and the last one the most challenging one is the following so we’re going to create users okay cars with images and features first we’re going to create three users then we’re going to create two more users and for each user from the last two users we’re going to create 50 cars with images and features and add these cars to favorite cars of those two users pretty complicated right all right let’s break it down and do it step by step first we’re going to create three users so this is pretty straightforward user Factory count three create okay this is good if if we check user Factory we are going to see that um sorry uh I want to check car factory because we’re going to create Now cars inside car factory the user ID is the random user ID and we need something some users to be presented in the database that’s why first we created three users and now if we treate if we try to create cars the user ID already exists in the database so the following code will pick up a random user from these three users CTI ID also exists in the database we created cities fuel types car types we we created makers and models as well so all of them is created above okay and now we have to create cars alongside with users okay now let’s break break down the second part then create two more users okay let’s start with it user Factory count two okay then what do we need to do and for each user from the last two users create 50 cars okay for each user we have to create 50 cars with images and features and add these cars to favorite cars of those users okay let’s let’s remove this part um for for a moment like create 50 users and add those cars uh sorry create 50 cars and add those cars to favorite cars of these two users so we should do this in the following way the user has each user has 50 cars so we can use car factory we can call count 50 okay but we have to also provide the relation name of uh from user to car and the relation name is favorite cars because we want to add those 50 cars into favorite cars of these two users okay so here we need comma Now we created two users each user will have 50 new cars added into favorite cars that is pretty correct finally we can call create on that okay however we need to also create images and features for those 50 cars so on that car create we are going to call additional has each car from the 50 cars has something else uh they are going to have images and in this case we’re going to use car image factory oops car image factory we’re going to call count we can create as many images because it is not specifi right here how many images uh each car should have we can provide whatever we want I’m going to create five images for each um for each car but I need to also provide position for each um for each image okay so images should have different positions from one to five okay for this I’m going to use sequence okay and I’m going to provide function inside the sequence we are going going to accept an instance of sequence right here and I’m going to return array which will have position some value okay I’m going to move this down so position should be some value so I can use sequence index plus one but the thing is that finally we have to create um 100 cars totally and 500 images so for each two user we are creating 50 cars and for each car we’re going to create five images so totally we’re going to have 500 images and that sequence does not iterate over the over specific car it iterates from 1 to 500 not one to five so if we execute the following code and I’m going to leave this right now because I want to show this to you if you execute right now the sequence will be from 1 to 500 which we can fix later okay but anyway let’s leave the sequence so we have provided car images and additionally we need to also provide features so I’m going to use his magic method has features because every car has relation to Features somewhere and using this magic method like has features we can provide um that each car should have its own features okay awesome now we created uh I think we did everything inside this Cedar and now we just need to try to execute this and see if we have any errors let’s bring up the terminal and I’m going to execute PHP Artisan migrate fres D- seed let’s hit the enter and have a look okay we have very first error and let’s see we have some issue inside car types okay I know the reason the reason is that inside the sequence we have to provide arrays not a single array because we have just one array and inside there then we have nested arrays this this doesn’t work so sequence accepts um elements multiple arrays not single array okay we’re going to remove this array parenthesis right here and we have to fix this in other places like here we’re going to remove this and also if we scroll down below when we create this array map we have to destructure this and provide separate arguments inside the sequence so each paer of this name the associative array will be provided as a SE separate uh parameter of the sequence method and we should do this for makers as well and now we should be good so let’s save this and retry this again okay seeding database it needs couple of time because it is creating something okay we have another error okay we have bed method call to undefine Method car image from car okay we have to provide relation and name as well when we Tre try to create uh images like the car has and right here uh we need to provide image’s name and you know why because if we open car factory the relation to images is called images right here but the actual model is called car image if we call these car images then it would probably work but but we have car image right here we call the relation images and that’s why we have to provide the relation name I’m going to provide images right here we need comma now let’s try this once again PHP Artisan migrate fresh D- seed okay cing completed successfully and now we need to check the database let’s start with the users we totally should have five users and we do have so let’s open States we have the following states for each state we have couple of cities totally there are 50 cities we have cars we should have 100 cars in our database here we go we have 100 cars and all the data is provided very nicely let’s check car images this is something we we need to come back and look at this so we have five images for each car but the position as I mentioned starts from one and goes up to whatever it is 500 okay so this is something we need to come back and fix it let’s go into database Ceder scroll up and find where we provide the position so the sequence starts from one and ends with 500 so because I’m creating five uh uh images for every car this is what I want to do so I’m going to take that sequence index and I’m going to uh take the remainder when dividing this on Five okay and then I’m going to add one so whenever sequence is zero then the following expression will give me zero + one will give me final position one when the sequence increases like when it is one then this gives me two and so on and when the index reaches five then five divided on five the remainder will be zero and this will give me one again so using the following code the position will be alternated uh from like one to five or I could do also in the following way I will just show you the maybe the easier to understand way here we provide sequence and we provide the following let me comment out this part this is extra comma we need comma here okay position one and then we duplicate this several times position two position three four and five so if we format the code now this will do the same thing right here so for first car it is going to be position one second position two and so on and for the next car for the sixth car it is going to start with the position uh one again this is probably easier to understand but the above code this code will do the same thing so I’m going to leave both actually uh we need this comma here okay now let’s save this and let’s execute the migration fresh with D- seed again seeding completed successfully and let’s check now car images table and we see that the position is from 1 to 5 for every car and just like this we defined ideal data for our project and we can already start working on outputting these data on the [Music] website now let’s open Home controller and we’re going to select cars and render those cars on the homepage let’s use the following way to select cars car where I’m going to select the cars which are published so I’m going to provide published it to be less than now I want to select cars which are published in the past okay so then I’m going to sort those cards using order by Method with published add column in descending order latest published car at the top I want to limit the result with 30 and I want to get those cars now let’s pass these cars to the view through associative array great now let’s open homepage page index blade PHP file and here is where we simply iterate from 0 to 12 and we are rendering uh we using this ex car item instead of this for Loop I’m going to use for each we already have cars available in this plate file because we passed it from here okay we use cars as car here we need end for each and we are going to provide car right here so I’m going to provide this in the following way assuming that the component will accept a prop with name car let’s open this component car item component and let’s define inside props a single prop called car now we accept car right here now let’s use this car and um just display the information right here so here we have hardcoded image instead of hardcoded image I’m going to use car primary image image path next here we have the um city of the car so car city is a relation on the car name scroll down below we have here y I’m going to use car y here we have the maker name I’m going to use car maker name and here we have model name car model name let’s move this down like this here we output the price car price here we have the car type car uh car type name let me double check what is the relation um to car type the relation is called car type we could call this type as well but car type is also fine so car car type name and here we have car fuel type name and just like this we defined the car item component exact exactly um as it should be now if I save and if I reload the browser um okay attempt to read property image path on now I have a typo here I can’t access primary now let’s rad the page again and the homepage was rendered and we see latest edit cars we see these are dummy images we see cities right here we see y we see maker model we see price we see car type and we see fuel type as well and all the cars are unique we are displaying 30 cars on the homepage and finally we have to also fix the root to the car show page here we have hardcoded one but we’re going to replace this and provide the either the entire car object or we can provide just ID if we provide the object LEL will resolve this automatically and takes the primary key of that [Music] object now let’s have a look at different ways how we can Cur data for example if we don’t have orm model created for our table we can still cure the data from the Cars table using the following way we’re going to use DB support class for this and DB table we provide the table name cars and the then we can call any CER Builder method such as get to get all cars however if we have car model then we obviously know how to CER the data but there is a specific method to create the CER Builder instance and that method is called qer we can create that qer instance and then on that qer we can use any methods from the qer class such as we order by limit and so on okay to get a list of all cars we can do the following way to get the first car we’re going to use the first method we can also get a single value from the car for example I want to get the highest price I’m going to order by cars with a price descending order and call the method value specifying the column name and this will return a single um integer or string value highest price from the database if you want to get a list of values for a specific column we can use a method called pluck we ordering uh cars by Price descending then calling PLU for Price column gives me a plain least onedimensional plain array of prices from the car table or I can provide a second argument in the plaque which will index those prices by that ID column so the second code will give us an associative area we key will be the car ID if we want to check if a record exists or does not exist in the database we can use methods like exist or does not exist if you want to specify inside select which columns we want to select we can use the select method and provide the column names we can also provide aliases using as keyword like we have done in the first case uh right here or right here if we we can also use additional method called add select to select for example wi code here and price here but we can also add millage for each car and after that we call get and each car will have three columns V code price with the name of car uncore price in the millage if we want to select the distinct records we can use distinct method on the select like if we want to select the distinct maker ID and distinct module ID from Cars if you want to limit and take the off use the offset as well on the car we can use limit and offset methods but there’s Alternatives as well like skip which is equivalent for offset and take which is the same as limit if you want to select how many records exist in the database with some conditions or even without the conditions we can simply use count method we can use this count method directly on the car model which will return how many cars totally exist in the database if you want to select minimum maximum and average prices for example we can use mean Max and AVG methods on the CER Builder providing the column names for example the first code will return the minimum price of published cars inside the cars table the second will return the maximum price of published cars and the third would will return the average price of published cars in the database if you want to group cars we can use Group by Method provide the column using which we want to group for example we can use also this select row method which we’ll go which we will cover in the next lessons as well we’re going to select the car ID and count as image count and group by this car ID this will return car ID and how many images that specific car has and this will return array of cars car image instances and if we just print the first cars from that array we’re going to get something like this it is an instance of car image but it only has two attributes car ID and image count this is exactly what we selected if we access search page on our website we see that it’s still outputs dami data now let’s fix that let’s open car controller search method and let’s Select Cars so let’s use car we I want to always Select Cars which are uh published so publish that is less than now then I’m going to call order by to sort it by published it in descending order and that gives me CER quer Builder instance then on that CER Builder I want to do two things first I want to calculate how many cars there exist with the search criterias like car count equals on the Cy I’m going to call count next is to actually get the cars so cars equal on my cury I want to call limit to select only 30 cars and then I’m going to call get now I have car count and I have cars and I’m going to pass them right here cars and car count great now let’s open car slash search Search Blade PHP and let’s find the corresponding place where we need to Output them let’s scroll down below here we have found random number cars and this is where we need to put found car count cars and if we check in the browser that was the place where the random hardcoded number was outputed if I reload right now we see found 80 cars now let’s scroll down below and find the place um where we have these car items here it is this is the car item and we have this code duplicated main times so I’m going to collapse that actually I’m going to delete now those car items there’s plenty [Music] oops let’s see okay here we go so I deleted now we are going to iterate over received cars as car and we are going to use x car item providing the car right here because the prop name matches the variable name we’re going to provide we can do this in the following way now if I save and reload we see found 80 cars and those are cars selected from the database and those are 30 cars the pagination is dummy at the moment but we’re going to come back to this now let’s see different ways how we can order data using cery Builder we already saw an example of order bu but we haven’t mentioned that we have ability to provide multiple order by methods so we can do this couple of times provide the first order by column and its direction second order by column right here and its direction we can also use predefined latest and oldest methods latest method is going to do the same thing to order records by created that in descending order and the oldest method is going to do this thing to order by created it in ascending order however there is also possibility to provide additional column on latest and oldest methods like in this case we are sorting latest by published at so this is going to to the same as order by publish dat in descending order we can also select any records in random order and the method is called in random order and then we can get cars in random order so that’s a good thing if you want to always display random cars on the homepage you can do it like this also if we want to remove ordering an existing ordering let’s say we have this query Builder which is ordered by published at in descending order and we want to remove this ordering we can call reorder which removes existing ordering and then we can apply a new ordering order by price for example or we can also provide new column in the reorder method like if it is sorted with publish dat we call reorder price it removes publish dat and applies um the price in [Music] ordering when we open the listing of the cars and click any of the cars it is going to open hardcoded content right here and now let’s fix that part for this let’s open show blade PHP file from resources views car folder and we have to adjust this here we need maker so this is going to be car maker name let’s move this down then we need to Output car model name we need to Output car y here then we need to Output the city car city name this is the date when the car was displayed so let’s just output car published at date okay scroll down below now this is the image section so this is the primary image so let’s just output car primary image image PA and down below we have all the remaining images so we need to iterate using for each over car images as image and we need image right here and we have to provide image image path here image image path cool let’s delete all these hardcoded images let’s scroll down below what else do we have so here’s the detailed description we can provide here we need to provide the description of the car car description but let’s assume that this might have um content like HTML type of content so let’s use and output this with entities with unencoded okay and this is also part of description so we are going to remove REM this here we go we have then car specifications and these are car features okay uh we are going to get back to these car features in a moment but let’s scroll down below and find where we output the price and everything else so I think that’s the part here we have make this is car maker name then we have our model name we have car y this is car type so we have car car type name and we have car fuel type name what else do we have so we have the user Avatar who is the owner of the car we also have the username we don’t have actually avatar for the user but we have the username so here we’re going to use car owner and we have the relation to user through owner name car owner name and we can also output how many cars the owner has like car owner cars count it’s pretty handy car owner cars count let’s understand this car PHP it has owner method and through owner it connects to user and then user class has cars which relates how many cars that user has and we can access to that relation and then through that relation uh if we access this as a method then this returns qer Builder and then on that Q Builder we can call count okay great then here we have the phone number and we need to Output it for this I’m going to use St Str um helper class let’s use Str Str and I’m going to use method called mask we’re going to provide car phone and I’m going to provide the symbol which should be used for mask and I’m going to provide also the integer after how many digits uh it should apply this mask so here in this case we’re going to provide minus three which means that first uh the the last three symbols will be masked okay so we’re going to take this and we are going to put this right here as well now I’m going to save this and re reload the browser uh car maker name okay undefine variable okay let make sense let’s open car controller we have not passed that car let’s find show method here we have this car but we have not passed that car to car show blade file so let’s provide it here save reload now we see the name y whatever we see the price I believe this is hardcoded price we can come back to this but we have like the name how many cars that uh has the last three characters is masked we have some detailed description as for the car specifications this is something we have to fix the CSS needs to fix to be fixed as well I recently made some changes in the HTML CSS project inside CSS you probably have the latest version you probably don’t need to do this I’m going to copy that up CSS and put this in my project inside up CSS which comes from the public folder let’s replace everything awesome now reload the browser and we see these car specifications now on the right side we don’t display all the information like we don’t display VIN code we don’t display millage or address let’s open PHP storm go into show blade and here we also have this hardcoded price let’s replace this with car rice and now if we scroll down below we have make model ER let me duplicate this and this should be Vin then we have car type fuel type and we need address this is going to be car address and we probably need millage as well so I’m going to put this after WI okay cool reload the page and now we have a lot of information actually the whole list of information what we need to have last thing what we’re going to do on this page is this car specifications so this is hardcoded at the moment and if we observe that part which is above we’re going to see a lot of duplicated code so this is the lii which has the color red this means that uh it doesn’t have that specific feature and this feature is leather seats okay anyway so we have a lot of Li elements inside these car specifications and this is something I want to fix for each Li I want to create uh separate component so let’s open Terminal I’m going to execute PHP artisan make component car well I’m going to create this as view only component so I’m going to call this in a lower case car specification so this is going to be the component name Das D view PHP artisan make component okay now let’s open car specification blade PHP file let’s open show blade PHP file as well and I’m going to copy this liit tag one of the LI tags let’s take this one and I’m going to put this in the car specification however this one has color green which means that it’s um it is a checkbox we need the second SVG icon as well like this one here and we need to alternate based on the value okay now we have two SVG icons here now let’s accept prop props value and here let’s check check if value is true then we display this SVG the green SVG in lse case we display this red SVG we need end if here I’m going to use default slot okay cool now let’s go right here and we have to adjust this so let’s start from the first one we’re going to use X car specification and we have to provide value the value will be car features abs and we have to provide the actual content like the label as well let’s finish this car specification and the label will be ABS now if we save this reload the page we see an error okay the problem is right here yes car X car specification okay well this should be an array that’s my bet there should be an array now we save it reload it and we see ABS which has minus so this is the car with ID 23 now if we open the car with ID 23 ID equals 23 find that and let’s find its features we want to find features car ID equals 23 ABS is zero if I set the ABS to be one and save that then reload the page we’re going to see now the ABS turns into green and in the following way we are going to follow and implement the other specifications like I’m going to duplicate this many times I can delete all Lis right now don’t need them anymore collapse them to easily delete them okay cool let’s delete them and maybe I need labels corresponding labels okay let’s duplicate this multi times okay and then I’m going to copy labels for all of them using multi cursor I’m hitting alt on my keyboard here and here I just want to copy labels for all of them creas control Bluetooth connectivity remote start GPS navigation system heated seats climate control rear parking sensors and leather seats okay I have a lot of cursors created for every label then I’m going to hit shift on my keyboard and hit end on my keyboard so this selects the whole entire line and all these labels are selected so then I’m going to hit contrl and C just to copy all of them now let’s scroll up move up find that specification area and I’m going to create now again multiple cursor the first cursor goes right here then here so if you want to create previously we had multiple cursors already created like right now I have two cursors if I click somewhere else hitting alt it’s going to create the third cursor but if I click somewhere else without alt it is going to create only one cursor right here in this place so the first cursor here second here with alt then I’m pressing alt okay okay now I’m going to hit shift again and in this case home button and delete everything and hit control and V to just paste that rear parking sensors is the last one but there was something else after it as well so I just created uh not in enough ex car specifications okay I copied like maybe 11 lines but I had 10 cursor points that’s why one was lost maybe one maybe two was lost after rear parking sensors there was something else we need to scroll down and find that it was leather seats okay now let’s delete all these Allis because we copied the ual labels I’m trying to be cautious don’t to delete too many lines okay now I duplicate this and the last one was leather seats okay now we have a lot of X item specifications the only thing we need to adjust is to provide uh the corresponding uh Keys column names right here so let’s expand this and expand the column names and let’s start with the first one which is air conditioning so we can copy the column name and instead of ABS we can paste it right here next we have power windows we can copy the column name and put this right here next we have power door locks we can copy this put right here next we we have abs which is correct next we have cruise control which we can copy and put this right here next we have Bluetooth connectivity copy the column name put this right here we have remote start we have GPS navigation we have heated seats we have climate control oops uh we have climate control here then we have rear parking sensors and finally we have leather seats okay now this looks good um let’s save the file I’m going to open car features and I’m going to quickly test this I’m going to select all the features and I’m going to set zero for all of them now let’s open reload the page see minus in all of them now I’m going to put one in all of them and using PHP sh we can very easily do this you just need to select all the cells and put zero or one there okay then we need to hit this submit button right here so now we I reload and I see checkbox on all of them so our implementation of car specifications works perfectly and we have I believe very ready car details page as well let’s go back and open another car like this one Chevrolet Tahoe 2005 price every information different seller different phone number eight cars detailed description and different specifications if we access SLC car URL we’re going to see this hardcoded my cars page now let’s try to implement this for this let’s open car controller and we’re going to find index method here we are going to select the cars which belong to the currently authenticated user because at the moment we don’t have authentication implemented in our project we’re going to use hardcoded user ID 1 and select the cars for the user ID one so cars equal user let’s find with id1 and that we’re going to import that user up modules user and then I’m going to call cars um Q method on that and I’m going to also call order by I want to sort the cars by uh created at in descending order and finally we’re going to call get so I select the cars and let’s provide the cars right right here now let’s open car index blade PHP and we have to scroll down below where we iterate over our data inside tbody and we have to iterate over given cars is car okay let’s move this end for each below this TR right here and we can delete remaining TRS because those are hardcoded and we’re going to work inside that TR to Output the correct data so here for example we need to Output car primary image image path next we have car y car maker name car model name here we have the date when the car was created or when the car was published we can decide which one we want to display I’m going to display when the car was created car created it however I want to display just the date not the time okay so this will display the daytime uh let’s display this and then I’m going to come back to it and so here we have um whether it is published or not and we can use if car published at exists then we print yes if not we print no this is something which we have to provide car. a edit and the car entire object we can collapse this and this is a link to car images uh well we can skip that right now when we Implement car images page then we can come back to this and this is the button to delete the car and I’m going to come back to this later as well now I save this I reload the page and here we go so we see the cars for the user for the user one so we see um the basic information we see date with time which we need to change and only display uh date without time we have the published flag this one is not published and we have this edit images and delete button as well if we have a look at the HTML CSS project we can see that the edit and images buttons have different colors and they look slightly differently that’s because there is uh these buttons are styled under page M cars so what we need to do is to add page my cars to this page so let’s scroll up and inside X up layout um do we support this page class let’s open up Dash layout or up blade PHP okay we don’t accept page class we accept it probably in the base layout but we don’t accept in this um up plate PHP so let’s take like body class which by default will be null and then let’s provide body class here like this okay now from here we provide body class to be page my uh well we have to remove this column page my cars is it correct I mean the naming page- my cars it looks correct so we save it and reload in our LEL and we see that the buttons got blue and the delete is red and the styles are properly applied next is to fix that date right here and for this we are going to use use carbon package in LL there is by default um it comes with LEL it’s a carbon package working with a date carbon is a very um powerful date manipulation Library okay so we can create an instance of carbon providing this car created at and then on that we can call format I’m going to put this in parenthesis I’m going to going to call format on this or we can create a method in the car model so if we open car. PHP scroll down below we can add new method here get create date we’re going to return new carbon we provide this created it and we’re going to call then format on this providing year month day okay now U and we can specify that this returns string now let’s take this method name and use it right here so on car we’re going to call get create date and let’s check in the browser reload the page and we see just the date here we are using for each but if there are no Cars I want to also display um some information that there are no Cars the user has no cars and so on instead of for each we can use for else then oops like this for else then we have to provide right here empty directive and inside we need TR then we need TD I’m going to provide call span to these five let’s provide also text Center pting uh Dash large and inside here I’m going to write the following text you don’t have cars yet and we’re going to put a link to car create page as well so for else empty and finally we need end for else we save it we reload it we don’t see any changes right now but if we open car controller and change the user uh ID from one into three for example I believe three doesn’t have any cars uh no it has uh let’s change it into four maybe five it looks like all of them have some cars user okay all three all users have cars let’s search for user ID equal five and these are the cars for the user ID five which I’m going to change and assign it into user 4 now fifth user doesn’t have any cars so I reload and I see the following page you didn’t have any cars yet a new car clicking on this should open this a new car [Music] form now let’s Implement watch list page first let’s create blade file HP artisan make view let’s call this watch list but we need to put this inside car folder car. watchlist cool now let’s open car controller and I’m going to add additional function right here called watch list okay okay then I’m going to return a view from here car. watch list I’m going to select the watch list cars right here so cars equals let’s find user with id4 again we are doing this uh with hardcoded approach so to do we come back to this okay so we find the user and then I’m going to call F favorite cars on that user then we provide cars to be the cars now let’s open just created watch list blade file inside car and we have to copy and paste some content from the HTML CSS project here we have watch list HTM HML and we’re going to find this main tag here it is I’m going to copy and here we’re going to use x up layout and put this inside X up layout okay if I save this uh we have to Define the root as well so let’s open web.php duplicate this car search and I’m going to call this car watch list and we should change this into watch list as well and the name will be car watch list as well now let’s open the browser and access car watch list hit the enter and we see my favorite cars right here which again at the moment is hardcoded now let’s open this watch list blade and we have bunch of car items we need to delete pretty much all of them so I’m going to scroll at the very [Music] bottom where it is here it is here it ends okay oops sorry so this is what what I’m doing we have this car items listing and I’m going to leave my cursor right here and then scroll at the very bottom until I find it’s matching close using tag here it is so this is it now I can delete from the top so from here up until here I’m just trying to do this slowly so that you can learn but in practice when you get used to it so you can you you’re going to speed up your working process a lot so for each cars is car and we’re going to use x car item providing car right here now we save we reload and we see the items which are in the watch list so we see that the page does not have uh the heart icon highlighted like it is right here on this HTML CSS project so this is watchlist. HTML so the heart is highlighted here but not here and we have to fix that let’s open HTML CSS project again and we are going to find the heart icon which is highlighted so this is inside this car item let’s scroll down below here we have this SVG uh and I’m going to select this SVG let’s go go into our car item scroll down below find that SVG and I’m going to put the copied SVG here the width is 20 pixel here we have the 16 pixel we can reduce this to 16 pixel okay always now we probably have two icons um one which is not which is highlighted which is fielded and the second which is not field now based on some flag we need to decide which one we should display okay so if we are rendering this car item from the watch list we know that all the cars are inside the watch list so on this props inside this car item let’s add a additional prop um is in watch list let’s call this is in watch list and by default we’re going to provide false it is not in watch list then based on this flag is in watch list we are going to do the following so I’m going to add extra class on this SVG which is not fi SVG so this should be hidden if it is in watch list let’s format this nicely and in the same way the second SVG should to be hidden if it is not in watch list now because all of the items are in watch list if I reload the page uh we don’t provide watch list don’t we or maybe do we have this hidden class let’s open up. CSS and find hidden class and here we go here we see only one icon but that is not the one we want so maybe maybe we should inverse this so hidden uh if this is in watch list and hidden if this is not in watch list now we save and we reload and we see that this is filled however the styes right here is again different so we need to inspect this and have a look so we have this pitting hard icon it has text primary B um BTN heart text primary let’s have a look we have just BTN heart not text primary let’s add the following class as well reload the page and we see this in Orange nice orange color however because we add this text primary it will be in orange color even on the homepage uh right here uh which well this should be this should be in or orange color but not fi so let’s check we have this car item is in watch list this is always false we are going to print what is the value of this is in watch list when rendering on the homepage so it is always false then why do we see this field one we shouldn’t see this field one right so again we did something wrong so the first first one this should be hidden if this is in watch list and this should be hidden if it is not in watch list reload the page that is correct however if we go in the watch list page this is the issue the watch list page we’re going to provide is in watch list and we are going to provide um well we can provide always true at the moment because if we are rendering this from watch list page it will be in the watch list in any case so let’s remove this dump reload the page we see this orange but not fied if we go into car watch list page then we don’t see also it fied let me return this damp again and we see that this is false is in watch list I have a typo is in watch list this is it s was missing right here save reload remove the dump and reload building realtime applications not the real time but the real world applications is challenging you always make some typos you always have some issues but the good thing is that when you finally make it you feel that satisfaction now I want to talk about one very important concept and this is called eager loading now imagine the following case we’re selecting five cars we are iterating over our cars and we are just printing the car city name however this line uh has accesses the relation City and this line makes select for every city so finally the following Cod code will make six queries one select will be to select these those five cars and then there will be five subsequent queries for each car to select its Associated City okay and even right here the first select and the last select uh is the exact same even the ID is 15 that’s because the first car and the last car both are for the same city okay how to fix that problem uh and that problem actually is very common problem this is called n plus one problem cers problem and this problem will get even worse if you try to access multiple relations like we are trying to access U City and we are also trying to access car types now number of curers will be much more it will be actually uh 2 * n+ one so one quer to select cars and then for five cars and then there will be 10 more cies five for each relation and imagine that we’re now selecting 30 cars or 100 cars the number of C is made for cities and car types will be 200 for if we are selecting 100 cars so this this is very common problem and that problem is the might be the number one problem on your website to which degrades the performance um and the load time of the website how to deal with this problem we can provide with method on the qer and we can provide the relation names right here we can provide just a single relation name City or car type but we can provide both so in in this case this line does not make select for every Cy instead there will be totally three selects made the first select will be to Select Cars the next select will be to select cities for all the selected cars in the next select will be to select car types for all the selected car types totally three qies and it really doesn’t matter in this case if we we’re selecting five cars or 400 cars there will be still three curers made on the database this is pretty handy now imagine the case that we are accessing nested relations like we are accessing cities states name in our case without this eager loading it is going to make again a lot of requests so want to Select Cars want to select the city even though we don’t need city um and the next one we don’t need any information from the city but we need just information from state so we are not using information from City but it’s still is going to make um to cities and then States cities states and so on to fix that we can provide nested relations inside with right here with city. State and again we can provide multiple relations in this with method now when we are trying to access CT and State totally there will be three Qs made one for cars second for cities and the third one for States we can do the same thing if we provide such type of nested array inside with like city which is an aray and it has inside their state or car type so this uh selects cars with city and state and car type as well there is possibility to provide this with and like activate this eager loading by default if we provide protected dollar sign with property on the car so here we have those three relations defined inside car protected with like city state city. state car type and fuel type now when we write the following select without with inside car this selects five cars then we try to access city and state but totally this is going to make five queries one query is going to be to access the cars the next query is going to be to access cities based on the relation the third query will be to access States fourth one for car types and the last one will be for fuel types and here are all CES made okay there’s also also possibility to provide additional constraints additional wear Clauses when implementing eer eager loading for example we want to select car with images but right here we are providing also a closure function as a value of this associative array of images okay pay attention on that cury here in this function we are accepting the qer and on that qer we are adding additional re Cloud where the position is one which means that I want to select cars with images but only those images which has position one so finally when we try to access right here on this following line uh images when we dump the images the images array will always be one and it will be an image which has position one and here are the cers made for this first to select cars and the second one is to select car images for the already selected cars but the position needs to be one as [Music] well now we know what is eager loading or and how we activate the eager loading let’s implement this in our project for example on the home controller and on the home page so I’m going to give you this challenge to you you can think a little bit try to implement this and come back back and see my solution but I’m going to also give you hint how to do this if we open Home index blade PHP from here we are actually iterating over cars and we are using this car item so let’s open car item here this is the place we are accessing relations of car like here we are accessing the primary image City and so on you have to identify all the different Rel relation types we are accessing from this car item and then you have to provide those relation names inside with method right here okay enough speaking try to implement this and come back and see my [Music] solution all right here’s my solution let’s provide with the method here we need primary image we need City we need car type we need fuel type we need maker and we need model so these are the relations as I remember we are using inside the car item but I’m going to double check so primary image we are using CT we are using scroll down below we are using the model maker car type and fuel type and that is all now since we Implement those relations now totally the following code will make the code on our page will make um let’s count how many selects it will make and maybe this also try to guess how many selects pause the right now and try to guess how many selects will be made on the homepage okay now let’s count it together the first select will be to Select Cars the next one is to select primary image then the third one is for City fourth one for C type uh fifth one six and seven so totally there will be seven cures made on the homepage and it really does not matter if we’re selecting 30 uh Records right here or even 100 but without this with now I have another challenge to you if I comment out this with can you guess how many selects will be made on the homepage okay let’s count this together as well one select will be made to select cars now when we try to access to this primary image second select will be made third and so on I’m not going to count all of them but the point is that for every car we are going to make select for every relation totally we have 30 cars and how many relations we have 1 2 3 4 5 and six so totally this is going to make 180 selects just to select the relations and plus one to select the cars you see the difference right 181 select versus six select um this is how powerful eager loading is and this is why eager loading uh is the best thing what you can do on your website uh the probably the very first thing what you should check if you have correct eager loading implemented on the website if your website doesn’t work [Music] fast now I have additional challenge to you I want you to implement this eager loading on search page watch list page and my cars page okay I hope you did it now let’s see my solution on the watch list page after whenever I’m trying to access favorite cars so if I try to access with properties this gives me collection but I am going to access as a method which Returns the CER Builder instance and then on that I’m going to call with let’s move these favorite cards down I’m going to call with on this and I need need the exact same relations I defined in the home controller because the car watch list is using car item component and car item component is accessing the same relations which what we have added in the home controller so we’re going to open Home controller and I’m going to copy this with method and put this right here and semicolon at the end now let’s find search method and we’re going to do the exact same thing on search because search is also using the same component car item component now let’s access index page which is my cars page and here we don’t need all the same relations for this let’s open car index blade and identify what relations we are using so we are using primary image so let’s put right here cars with primary image next what do we have we have model we have maker let’s provide maker and model do we have anything else no in the listing we don’t have anything else so these three relations inside car controller index will be totally enough in the W list method I forgot to call get method after providing with without the get obviously we we cannot have any kind of cars so this get should be [Music] here sometimes when we select data we want to join to another tables and filter the data by another table or simply select the data from another table I assume that you are familiar with typical database joins this is how we’re going to implement the same thing in l through eloquent we have right here cars and let’s say that I want to filter those cars with State okay how we’re going to do this on cury I’m going to call join and I want to join to cities right then I’m going to provide the first argument of the join method is the table name I want to join the second argument is the the column name from the related table cs. ID the third argument is going to be the operator using which we’re going to do the comparison equal sign and the last argument is going to be the column name in the current Table like cars CT ID Now using the following way we joined to cities and now let’s say that I want to filter those cars based on the state ID so then I can add extra we Clause right here where cities. state ID equals 1 and in the following way we are going to have filtered data for the state id1 on the search page now let’s open the browser let’s go to search page and now look at this we have totally found seven cars only seven cars and we see only seven records and all of them belong to the same state and this is a probably Los Angeles State because we have um cities um around Los Angeles if I comment out this part reload the page we’re going to see 80 cars and we’re going to see 80 cars in the listing as well so that’s the one use case how you can use join and in which case in why you want to use join the second reason is that you might don’t want to make make an extra quy for example on City even though we have that City inside with a second extra query will be made to select city right so what we can do is the following on cury we can call Select to select everything from Cars plus we are going to select cities. name as cityor name now we select um the select does the select accept multiple arguments we’re going to see then right here inside the cars let’s just dump cars at zero we save reload and the first we have the first car right here and if we expand its attributes we are going to see CT name right here now if we access this is using the car search now if we access car item component uh here we are accessing through relation car city name and this makes the request and right here this also makes request what we can do is remove move this city from here okay and here instead of relation city name we can access ccore name because that is already selected okay however in this specific case I’m going to leave this accessing through relation because that is not um very expensive operation for our website to just make one select for City but but sometimes that separate select might be very expensive Cy that’s why uh if you are still making the join uh why not selecting it so there’s you should always choose between like the readability of your code um and the performance you should take something in between making your code super super optimal while you have like 100 users monthly active users on the website doesn’t make any sense rather it’s it’s better to uh focus on code readability because the relations also is going to work very fast okay let me comment out this part uh you can also apply joins um multiple times on your table for example here we are joining on cities and filtering but we can also apply additional join on let’s say car types where car types ID equals to cars car type ID and let’s say that I want to filter cars which has car types name equal sedan right so we can use this combination as well in this case I assume I doubt there will be any records uh oops where is that yeah there was nothing found because uh the two wears like the cars which are in state one and also uh they are sedan it doesn’t exist but if I change this into two maybe it exists yeah it was found and here we see that um car type ID is one which is San and this is here we see name as well sedan and the question is probably why do we see right here name sedan in state ID as well because when we don’t provide anything with this select by default Lal selects everything so everything from joined tables and that’s why everything from cars from cities and from car types is selected and that’s why we see right here state ID and name however it’s a good practice to provide if we are doing join it’s a good practice to provide everything from Cars table only and nothing else now I reload the page and we don’t see here state ID or name because we are only selecting information from the Cars table okay so this was inner join example however there is also a separate method called Left join left camel case join uh and we also have right join and it works in the exact same way like it works in regular databases in MySQL or in in even SQ light um I’m not going to provide more information about that right now because it’s a pretty straightforward it’s the the syntax is the same the table name First Column equals second column and um the left join Works differently right join Works differently and I assume that you know what’s the difference between inner joint left joint and right join uh if you take this course if you want more advanced joins and more additional we Clauses on the join you can do this in the following way let’s say we’re selecting cars joining into car images and right here in this join we can provide closure as a second argument uh we accept instance of join clause and on the join Clause we can call on our own condition how we connect these two tables together like cars ID equals car images car ID and we can provide extra we right here car images position equals one so we are making the join to car images but only those images which has position one we can also add extra or on like car’s ID equals car images car ID or and second condition whatever you want so this a pretty Advanced uh case uh you won’t find this very often but I just wanted to show to you that in case you need it you you know that that this course has a slide on that information and you can come back and find this [Music] out we already covered the most common wear Clauses in L but there are even more let’s see couple of examples how we can use wear Clauses or what additional wear Clause methods exist in LEL we can apply multiple we Clauses just like we are doing right here this is pre pretty straightforward however every we method accepts three argument by default and the second argument can be the operator and that operator can be any valid operator supported by your database like in our case we are using equal sign greater than or even like where are we providing the string with with parenthesis the we method also accepts an array and in which case we can provide multiple we Clauses as array each of them like array of sub arrays where each sub array is the column name operator and the actual value now let’s see an example of or wear Clauses sometimes we want to select very old cars or very new ones and for this we’re going to use or we like in our case we your is less than 1970 or where the year is greater than 2022 we also have we are not Clauses we are not dedicated method and in this case this is going to Select Cars where millage is not greater than 100,000 obviously we can write is less than or equal to 100,000 with we close but just for your information you should know that there exists we not as well there exists also we any clause which gives you possibility to provide multiple columns and if any of the provided columns satisfy the condition then the car will be in the final result so in our case if address or description contains the text York inside there then the will be selected there also exist wear all CLA in which case all Fields provided in this array needs to contain the word [Music] York now let’s cover a couple of more wear Clauses which are not so often used for example this we between or we between in our case we are selecting cars which has Y in between in 2000 in 2020 we can also provide or where between if we need so there also exists we are not between and or we are not between so in our case we are not selecting cars which are between 2000 and 2020 which means that we’re selecting cars which are outside of 2000 and 2020 years the next one is we we null we are not null or we are null or we are not null if we want to select all the cars which are not published yet this is the code how we can do it car we are null published at get if you want to select the cars which are published then we’re going to use we not null published at and get again we can always use or we are null or we are not null if we need to use or we CLA as well the next one is we are in we are not in or we are in or we are not in for example if you want to select cars which are for maker one or two we are going to use we in maker ID one or two if you want to select the cars where the maker ID is not in one or two we would use we’re not in maker ID one and two we are in we are not in also accepts additional cury for example if you want to select the users which are signed up with Google we would use the following select user we are not n Google ID but this returns a quer we are not calling get method we just return the quer then we could use that quer to provide inside wein method car wein user ID in the given qer finally the generated SQL looks like this select everything from Cars where user ID is in and second select right here so this gives us possibility to provide extra additional subcy inside this we in the same way we can use or we are in or we are not in the next is we date we month we day we year and we time these are pretty straightforward all of them works with dates the first argument is the column name which typically contains datetime values and the second arguments are depending on which method we are using for example in the first case uh this just make sure that the published dat is a specific date like 2024 07 12 the second method where month makes sure that the publish date is a specific month like July we day make sure that publish date is the first day of the month we are year will return cars which was published in the last year in 2023 and the last one we are time simply I think this this is going to be very rarely used but we can select the cars which we published at a specific time hour minute and second the next one is we column or we column if we have like two columns created it and updated that and we want to select those records cars or users or whatever where the created Ed and updated it columns are the same which typically means that the record was not updated after it was created so if you want to select records which were not updated after it was created we can use this Weir column the second example is to select the records we the record was updated since it was created where the updated at is more than created at we can also provide multiple conditions inside we column in the following way array of sub arrays there are also exists we are between columns we are not between columns or we are between columns or we are not between columns we don’t have a specific example in our project so I took this example from Lal official documentations so we select the patients where the patient weight is between minimum allow weight and maximum allow weight or we can take the patients where the patients weight is not in between minimum allow weights or maximum allow weights and finally there is we full text method as well our current database which we are using for this project sqi does not support full text search but if we are using any other database like MySQL postgress and so on it supports full text and if there exists full text index on the database then we can search cars or whatever information in the following way considering that full text index where full text the column name and the search keyword BMW for example now let’s have a look at the following example car we Y is more than 2010 additional Weir price is more than 10,000 or where price is less than 5,000 so imagine that we want to select the cars where the Y is more than 20110 and the price is either greater than 10,000 or less than 5,000 so the generated SQL looks like this and here is a problem if we want to have the price condition grouped together let’s say that the Y condition must always be there and the price condition should be grouped together then this qer has a problem so you should be always careful when using or we in your applications and the recommended practice is to use this logical grouping so in our case we can use another Weir like we have the first Weir to compare the ER but here we have the second Weir which accepts a callback function as well so we provide the Callback function inside this callback function we accept this Q with a builder and then we can add those two conditions where price is more than 10,000 or pric is less than 10,000 and because we have provided closure function and we use that grouping the generated SQL looks like this now as you pay attention we see that the r is more than 2010 and the price condition is grouped inside parenthesis and this is exactly what we wanted now let’s see an example of where exists let’s say we want to select cars that have images and we don’t want to select any car that doesn’t have image so in this case we can provide a method called where exists we can provide the function and closure function that function accepts a query parameter right here so we take that query and on that query we can select something from car images but we are connecting to the outside select so select ID from car images we column car images car ID equals cars. ID so here the equals is not we can obviously provide the second argument to be equals but if we don’t provide second argument equals and if we only provide two arguments right here LEL will automatically assume that the parameter the operator excuse me the operator using which we’re comparing these two columns means equals the nested select right here means to select car images for the parent car so this finally it’s going to create nested select using this we exists or we can do it in the following way as well we can directly provide viy inside we exists car image select ID we column car imagees car ID equals cars ID so this two piece of code is doing the same thing and this is what generated SQL looks like select everything from Cars where exists and the nested select to ID to select ID from car images where car images car ID equals cars [Music] ID now let’s talk about sub CES the Weir method accepts a closure function and that closure function accepts the CER filter we can pass that function to a couple of other methods like or we we’re not um and and couple of others as well but in our case we are selecting sedan cars but we are using this nested select approach so let’s Analyze This nested select first cury select name from car types where column cars car type ID equals car types ID and we’re just selecting one okay so this nested select will be executed for every car and it simply is going to select name of the car types and in the outside this Weir has second argument equal and sedan as well so inside this wear so whatever is written inside this wear will be a value which equals sedan that quer is the same as the following one we have that subquery in its own separate variable car type select we column cars car type ID equals car types ID limit one and we’re providing the subquery inside this where where the subquery equals San and the final generated SQL looks like this select everything from Cars where something is selected here equals San and that something is Select name from car types where cars car type ID equals car types ID line one this limit one is important otherwise the following select will select multiple values and the wear condition will not work because multiple values cannot be compared to a single value here we have another example we’re selecting cars which has price below average price so here inside this we first we have the price Which is less than and the closure function so in previous example first we had the closure function and the subq then we have the operator and the static value here we have it in a reverse order we have static value not the static value but actual column and that column operator and then we have this subquery inside subquery we’re selecting using select row we’re selecting average price from Cars so we’re simply selecting cars which has price below average and the generated SQL looks like this if we want to debug our SQL cies there are couple of functions for that one of them is dump which dumps the cury with its parameters it is going to dump the actual generated SQL as well as the parameters which are bound to this we close in our case we have only one parameter this is 100,000 the second method is DD which dumps the SQL the parameters and it dieses stops the code execution there also exists 2 SQL which dumps the row SQL which has parameters replaced already this does not print separately parameters and separately prepared SQL statement instead it is going to dump a single row SQL parameters already injected inside SQL and the last one is DD row SQL which dumps prints the row SQL and it simply stops the [Music] execution in Lal there are multiple methods to implement pagination the easiest approach involves using paginate method on either the query Builder or on an eloquent cury for example I’m going to delete everything right now and on that cury I’m going to call method called paginate which returns an instance of paginator and I’m going to assign this into cars then when we provide cars and car count right here we can completely remove this car count and we’re going to take care of how car count will be displayed in the search blade in a moment this method the power of this pinate method is that it automatically handles setting the C’s limit and offset according to the page the user is currently viewing by default the C page is identified by the page cury string parameter in the HTTP request Lal detects this value automatically and inserts it into the pagination links generated by the paginator awesome let’s open Search Blade PHP we don’t change the iteration we have these cars as an instance of pator and we leave it like this now let’s search for car count and this place we are going to change we’re going to use cars total method for this and finally let’s render the pagination links on cars I’m going to call method called links so we save it now let’s have a look in the browser we reload the search page and we see found 82 cars which is coming from now paginator total method and if you scroll down below this is the pagination links generated by L this is our hardcoded pagination uh right here it is collapsed uh we’re going to take care of the templating in the next lesson but let’s understand why we see preview and next right here or where are the other links I’m going to inspect this and I’m going to collapse this D and here we have another D which has class hidden by default the default template Lille uses for pagination is taln CSS template and the template has different pagination links on different screen sizes like it has preview and next on small screens and um the full pagination links on large screens and it adds this hidden class on the pagination links on large screen okay so if I remove this hidden class now we see the summary of the pagination as well as the pagination links and again we’re we’re going to work styling of these pagination links in the next lessons now if we Mouse over or if we click any of the links right here we’re going to see in the URL page equals 4 if you scroll down below if we just remove this hidden class once again then we see that now we’re showing 46 to 60 results and the active page is four right here this is what I mentioned LL automatically manages the pagination links based on the Cy parameter and it automatically generates also these links based on the Q parameter and based on the pageat result we can use this next button now we are on page five obviously the summary is hidden but we are vieing different results set and um that is all now I think we can customize the pagination links there are several ways to customize pagination the first way is to provide New View name inside links method right here for example let’s call this pagination the view doesn’t exist that’s why we’re going to get an error the error tells view pagination not found the second way is to not provide pagination here but open up service provider in inside boot Define what should be the default pagination view for this we’re going to use paginator illuminate pagination paginator and on that we’re going to call default view for example pagination again if we save this and if we reload we’re going to still see the same error view pagination not found and the third method is to customize existing TN CSS view now let’s open Terminal and I’m going to execute the following Artisan comment PHP Artisan vendor column publish D- tag equals LEL D pagination we hit the enter now it copied directory from vendor Lal framework illuminate pagination resources views into our resources views vendor pagination okay now let’s have a look inside resources views vendor now we have a pagination folder and there we have bunch of pagination examples for bootstrap 4 five default one this is semantic UI simple buop four simple buop five simple default blate simple tnd blade and tnd blade so the tnd blade is what right now Lal is using by default so we can customize this if I simply remove everything from here and just leave one one one we save this reload the page we are still using the default one so I’m going to comment this out reload the page and if we scroll down below here we see 11 one which is coming from the following tallwind blade PHP so you should choose which approach you want in your desired specific case but right now I’m going to create new view called it pagination and I’m going to use that pagination view instead of modifying the tnd blade PHP and actually we don’t even need that vendor folder right here I just show to you how you can publish it and customize it but you know what I’m going to delete this vendor folder completely let’s uncomment this and set the default view to be pagination and then I’m going to create new view let me create this using Artisan PHP artisan make view agation we hit the enter the view was created actually it created um yeah it created only view yes I thought I created component and I thought that maybe it created the component class as well but no we created just the view so here we have this pagination blade PHP the pagination blade PHP right here accepts an instance of paginator and I am going to Define this right here for my PHP storm so that PHP storm autocompletes all the methods it has slash asterisk two times then I’m going to define the variable paginator is an instance of length a paginator so this is the class uh which instance the paginator is is okay great we can print that right now let’s use Cur braces DD paginator and we’re going to see all the properties of this paginator here we see that so it is an instance of pagination length of we paginator it has its own items let’s expand it it has items it has per page current page path and so on it has options as well and a couple of other things okay now let’s start step by step implementing pagination first let’s open Search Blade and let’s take this nav which is the our pagination template and let’s copy I’m going to copy not cut because I have to modify and then when I Implement everything in the pagination blade then I will delete this now okay so here I have this pagination if I save this right now and reload it we see pagination two time which is fine now let’s start in the following way first we need to check if the paginator has more pages if it doesn’t have more pages we should not even display pagination at all so if it has more pages then we display the pagination okay this is the first step next step is to take care of the links so here we have the this is the first page link this is the previous page link then we have links for each page and then we have next page link and the last page link so the first page link this one and the last page link I’m going to remove okay we’re going to use only preview and next and then the first page link right here will always be displayed and the last page link will also always be displayed that’s why we don’t need a separate like the first page Links at the top and at the beginning okay now what we are doing we need to check let’s use if directive we need to check if paginator is on first page or not if it is on the first page we need to disable the previous page link uh button link whatever okay so if it is on first page then we have to disable this however in else case if it is not on the first page we have to show it let me copy this a and if it is on the first page I am going to remove this hre and I’m going to change this into span now we have span instead of a if it is on the first page link which means that it is disabled however if it is not the first page then right here we have to Output previous page URL now if I save this reload the page we are on the first page and this is actually disabled if I Mouse over we don’t see any horor effect however if I change page into two scroll down below then I Mouse over now it is enabled and it takes me to the first page so that part already works and we can do something similar for the next page as well so right here let’s write if a gator has more pages then we need to display the link and if in else case if it has more pages then we have to display the link if it doesn’t have more pages then we have to display right here span okay let’s format this nicely and I think we are good now let’s reload the page the last page I believe is um how many links do we have okay we can take care of we can check everything at the end I just wanted to check that the last part was working but we can check this everything at the end okay now we need to iterate over the links and render them however there exists a special uh variable already available which is called elements so let’s print elements what is it scroll down below it is an array at the moment it contains only one element inside there and that one element is also array and this is links those are the pagination links so in the nutshell we need to iterate over these pagination links however if we go into another page like page four for example scroll down below okay we have to increase the pagination uh number of pages so instead of 15 right here I’m going to provide five which increases the total number of pages and let me try to access page number seven scroll down below now look at this inside this array elements array we have three elements uh the first one which is array of 10 elements then we have string and then we have second array which has only two elements inside there okay now this is something we need to take care of and we need to handle properly okay let’s go into pagination and let’s start iterating over our elements for each elements as element then we need to check if is string if the element is string it means that it is that three dot here we have this three dot if it is string it is a three Dot and we are going to display it in the following way imagination item let’s remove active class it doesn’t need and right here we’re going to Output the element this is a three dot however if it is not string and if is array elements or element then we have to iterate over element so here I’m using nested Loop for each element is Page and the URL this is how we have those elements right page and URL okay great now I have the page and URL and I’m going to grab this a link and I’m going to put this right here however we also need to check well right here we need to Output p and right here we need to provide URL however we need to also check if the current page is the loop page so that instead of a we’re going to display Span in this case so let’s use the following if if page equals paginator current page here is the current page okay paginator current page will always return what is the current page in the URL query parameter and if it is the same as the page right here in this Loop it means that we are on that page so we’re going to display pan in else case we’re going to display a link and let’s take this and display span right here let’s remove this hre and let’s also add class active okay I think we are done if I scroll down below we can remove this two three four awesome so this is for next this is for current pages and this is for preview I save it I load it and you you see bunch of pages right so we see one two whatever so we have a lot of pages and I believe we can reduce this if we use method on the pagination called on we should provide it here on each side and let’s provide one on each side of the current page on the left and on the right side we want only one page to be displayed so I reload it and now this is how we look it okay so we see the current page is seven um before that we have only six nothing else and on the right side we have only eight if I activate eight I scroll down below then we see nine and seven here and just like this we always see one page before and after then we see three dots and at the end and at the beginning we see uh two Pages now we can open search plate PHP and we can remove this hardcoded now and just like this we have pagination implemented if we want to go to the last page we are going to click um 17 right here then the pagination is gone the pagination is gone because in this pagination blade PHP I used incorrect method has more pages instead of has more pages I should have used has Pages if the paginator has Pages not more pages if I reload right now we see this pagination links the last one is disabled however I noticed something if I Mouse over on this one I see that the link is not correct so let’s open pagination scroll down below and right here we are going to use pator next page URL save reload and this one takes me to the page [Music] 17 now let’s output correct pagination links on my favorite cars page and on my cars page as well let’s open watch list method right here and instead of calling get right here we’re going to call Page inate and let’s provide 15 here so we’re going to display 15 items per page we provide cars let’s open watch list blade PHP here we have this my favorite cars here we iterate over cars and right here we’re going to display page Nation links this is going to be cars links and I’m going to provide also on each side to be one I save it reload it scroll down below okay it is working perfectly so there are totally four pages and that’s why we don’t see more than that but navigating between Pages works perfectly fine great however I also want to display how many cars the user has in its favorite cars section so maybe next to this my favorite cars right here on the right side we can display this pagination summary for this we’re going to do a kind of custom solution here so I’m going to wrap I’m going to introduce a new div let’s give it class CSS class FES uh justify between and items Center okay then we need H2 and then I’m going to check if cars total is more than zero and if in this case we’re going to display a div with class of pagination Das summary I’m going to create paragraph as well and inside the paragraph I’m going to write showing we’re going to use cars first first item item car’s first item then we need two here we need cars last item then we need off and we need cars total results or cars okay we save it we reload the page and here we see showing 31 to 45 of 50 results we know that when we create C data the user has 50 cars in its own watch list in its own favorite cars list that’s why we see totally 50 results if we go on the first page then we see from 1 to 15 of 50 results I believe we don’t need dot at the end but the summary is there which is great so let’s go to search page and I think that we have this pagination set to five and we’re going to increase that so I’m going to search for method search then change this page8 into 15 and then let’s open index and we are going to change this as well if we try to access car right now there are no cars for this specific user user five but let’s use user one reload the page now user one has multiple cars let’s change this g into pinate for 15 now let’s open car index blade PHP scroll down below here we have this nav let’s remove this nav and use cars links and again I’m going to use on each side we need one save and reload scroll down below we see only two links because there are not many cars for that specific user however if we change this page inate from 15 to five we’re going to see much more links right here okay this is great let’s return this back into 15 [Music] leral also supports simple pagination which is simplified version what we already covered for example I’m going to change this pagate into simple paginate save it and if we reload the page we’re going to see just preview and next links we don’t see all the links in the pagination and there are couple of other restrictions regarding the simple pagination simple pagination is more lightweight it um it is less expensive in terms of how many Q are made on the database so if you only need next and preview links then this is what you are going to use also simple Pate doesn’t support total number of Records in your application so we cannot actually use Simple pagate on our watch list because right here we are displaying total number of Records we cannot also use it on search page because we are using 82 or we are using the total number of Records right here okay and on these Pages we need those pagination links so it doesn’t make sense to use the simple paginate in our case but I just wanted to give you information that if you only need next and previous pons and nothing else no total a number of Records no actual links then simple page8 is what you should use if I try to use right now simple paginate on watch list simple paginate we are going to see error let’s go back reload the page and this is the error method total does not exist and this is exactly what I mentioned simple page n doesn’t support that and also the instance um right here the instance of cars is different it is not what we previously covered length paginator it is simple paginator I’m going to Simply undo this but now you know that if you need simple paginate it is there if we are using simple paginate and we also want to customize the pagination buttons these preview and next buttons we can provide again in the same way we can provide view to the links method in the car index here we can provide a new New View file or we can Define uh the default view file for simple pagination and we can do this in the following way paginator default view simple View and provide pagination D simple for example in this case because we are not going to actually customize it I’m not going to create this pagination simple but if you want it you can customize the view in the following way or again you can publish the vendor BL pagination blade files and you can also customize the default simple pagination file from there now I’m going to show you several more cool features regarding pagination first let me reduce these five so that we can have everything easily visible on the page I don’t want too many records next after we call paginate we can call couple of more useful methods such as for example if we want to link each pagination button into a different page we can use method called with path for example if we want to link this to a different page as I mentioned like user SL cars page if we save it reload it then if I Mouse over on this we see that the URL is user cars obviously we don’t have that URL it doesn’t support that URL but uh if you need that it is there and sometimes that P might be very helpful the next one what I’m going to show is to provide additional query parameters such as for example if we have sorting applied on the website and we want to keep that sorting we can provide that sorting uh cury parameter we’re going to learn how to take those cery parameters from requests and reply it right here here but for now let’s just append additional query parameter on the generated links appends associative array sort in price we save it reload it and now if I click on page two we see in the URL sort equals price and then we have page click on page three sort equals price and then we have page three which is pretty cool if we want to save preserve all Q parameters what we currently have in the URL in this case we have to use with quy string so that is going to preserve all the other Q parameters what we have in the URL so reload the page now we have sort query parameter in the URL we navigate between pages and sort will stay there if we add additional query parameter for example name equals Zora hit the enter Then the generated links will also contain name equals zura in the URL that is pretty cool however if I just leave up and sort and comment these with C string and if we have additional CER parameters such as name Zora for example then when we navigate between Pages name zoraa will be lost okay so depending on your use case sometimes you want to preserve all the Q parameters sometimes you only want to provide your own parameter through a pens method and the last method I want to mention is fragment so here I can provide if I have a specific section on my page which has ID cards then I can provide the fragment and generated links will have hasht cars in the URL this is also pretty cool and you can use these methods in combination together like all of them or a couple of them as you want but based on your needs now you know what possibilities there exist in lot of pagination and you can always come back to this video and remember how each of them works if you want to access request data there are two common ways one is to accept request variable in your road call function function or in your controllers method for example in car controller index I’m going to try to accept instance of illuminate HTTP request and LEL will automatically inject that variable because I am accepting it right here and let’s just dump what is that request but the second method to accept the same request variable is through request Global function request like this now if we dump both of them save and reload in the browser we’re going to see the following result so we see request printed right here and the same request printed right here and this request is a very large object containing bunch of properties and even more methods we have information about like cury parameters about uh files cookies headers the request URL method and a lot of other things if we want to to accept the road parameters like we’re accepting right here and we want to also accept request it is common practice to put your query parameters after request or any other variable which will be injected by LEL so here let’s accept request and only after that we should accept car now let’s access the following URL car SL1 and I’m going to also add cury parameters like page equals 1 it doesn’t make any sense providing cury parameters on the um car details page but um I just want to demonstrate you something that’s why that’s let’s put this page equals 1 as well now I’m going to copy this URL and we know this URL how it looks like and the request URL looks like this right now let’s try to access some important information from the request we have this request variable and we can access request path in the following way which will output car /1 we can also access request URL which will give us the entire URL but without Q parameters we can also access request full URL which will provide the entire URL including qer parameters we can also access request method which will in our case gives us get if we have obviously if we submit the form with the post method then the request method will give us Post request class has a lot of methods if you want to test if the request method is get or post we can use method called is Method so this if will be satisfied only if the request method is post we can use the method is XML HTTP request to detect if the request is made using Ajax if you want to test if the specific URL uh satisfies the following pattern like if it starts with admin slash something then we can use method is we can also use root is method which will in this case so the is accepts right here the path and root is accepts the route name so if we have every rad for admin users starting with admin dot then we can check this using rout is if we want to check if the request expects J or not we can use this expects Json method as well now let’s see few more useful methods they are not as commonly used as the above ones which I just mentioned but maybe you need them in certain cases so I’m just going to mention them very quickly full URL with C we already see we already saw what is this full URL but we have full URL with qer which gives us possibility to provide additional qer Pro before retrieving the URL so in our case the URL will look like this so it will have quer parameter sort equals price and it will also have right here page equals 1 I’m going to mention few more methods from request they are not as commonly used as the above ones but maybe you need them in certain cases so I’m just going to me mention them very quickly one of them is fully Ur URL with C we also we already saw what is full URL doing it is returning the entire URL however if you want to return the URL plus add additional query parameters this is exactly what is doing so the output will be that the URL will have page one as well as new query parameter sort equals price we also have similar method called Full URL with without cury let’s say that we want to remove specific cury parameters only one cury parameter or several cury parameters we can do the following in this in which case the URL looks like this the other one I I want to mention is host which will return the host of the URL we also have HTTP host which will return with the port and we also have schema and HTTP host which will return the following response we also have possibility to access specific headers from the request like if I want to get the information about the content type we can do it like this it might output something or it might output null we can uh get the request beer token if we are doing beer authentication in our websites beer token is mostly used when building rest apis so it is not as common for building websites and the last one I want to mention is the IP address so if I save this everything and reload the browser we’re going to see bunch of outputs right here and we see that um the header basically right here from the line 81 is actually null this is null which is the be token but everything else is populated the IP address the host with schema and so on now let’s open Home controller index method and learn how to return responses with different ways and in different formats okay so there are couple of ways to return response and one of them is very primitive we can just return the variable as we want for example we can return hello world as a string from here and if we simply reload the homepage we’re going to see Hello World string right here we also have possibility to return array from here we can put anything in the array the interesting thing is that we can also return collection of models for example if I call car get to return all the cars I reload in the browser we’re going to see Json LL is intelligent enough to detect what we are doing and in this case LL is serializing models orm models car model objects and returning Json if we pretty print this we’re going to see how each model looks like it has all the information that is necessary and that is very useful if we are building apis right we also have possibility to return single object if we call first method right here reload now this is a single car object so that was like implicit returning of response so where we return some object some string some array and Lal converts that into appropriate response however we have dedicated response function as well in this response function we can provide pretty much anything like string array collection object whatever we want let’s provide something like Hello World however this response function has additional features we can provide for example status code like 200 or if we are creating new record and we want to return uh with a different status code like 2011 we can do this from here this is how we can do it now if I reload the page we see Hello World however if we inspect the website and if we check Network and reload once again we’re going to see that the status code is 2011 which typically means that the record is created when building rest apis which is not our case just I wanted to mention how we can return different status codes we can even return 404 reload the page now we see that this is the there is the content but the status code is 404 age not found additionally we can also provide um couple of like um headers on that response for example we can provide like a content type to the application Json uh and we can chain those header um methods like we can do this multiple times this is header one it’s corresponding value one we can have header two and it’s corresponding value two also if you have any questions what is available what methods are available in this response you can always take that response object you can dump this right here which will give you in the browser what type of object response is this is illuminate HTTP response okay and then by the way you can do this on any model in LEL so if you are interested what methods are available there so this is I think very important thing so you can do this in any um Lal class then we open lal’s official documentation lal.com we go in the documentation scroll down below on the left side we click on API documentation and then we can search for that class that class is illuminate HTTP response we can put that class right here it’s going to bring us couple of things like the first one is what we are looking for and right here you’re going to find all the methods like status to get the status code of the response uh content header this is what we right now used we can provide some cookies um get call back throw response micro and there are a couple of other things so you can have a look always at the official documentation what methods are available in your object whether this is response or something else and then you can use those methods we know that we can return array which will be converted into Json however if we want to explicitly specify that we are returning Json on the response we can do the following we can create response and then we can call method called Json and provide data the data can be anything it can be object it can be array it can be collection and let’s put just one two and put the semicolon here and if we reload right now we see here Json if we want to return view but also control the status code of the response as well as what headers we’re going to pass we can do this in the following way we can call response then we can call view provide our view name and then we can provide right here data which will be passed to The View and we can provide then status code whatever we want like uh 44 2011 what whatever okay and then we can provide also additional header or multiple headers we have couple of methods regarding headers like we already cover covered header but we can provide with headers as well which accepts an associative array like this where the key is the header name and the value is going to be the header [Music] value there are several ways to implement redirect in Lal first of all we have to return whatever we are redirecting because redirect constructs response and we have to immediately return that response with the appropriate header so let’s do redirect and we can provide the URL right here for example we want to redirect user to car SLC create we save it and if we reload the homepage we will be redirected into car cre create page now let’s see a different example of redirect I’m just going to call redirect and then I’m going to call root this root accepts a root name so instead of URL we can provide card. create right here and if we try to access homepage again we will be redirected to car create page if we want to redirect user to a UR L which requires parameters we can also provide additional parameters right here for example if we want to redirect user to car show page and we can provide right here ID equals one we save let’s go on the homepage okay uh it is not ID it is called car reload the page and we are redirected to specific car page however we can also provide right here the entire car object on redirect so we can search car first we provide it right here then we try to access the homepage and we will be redirected on the first car page if we want to implement redirect on an external URL then we can call redirect a which means outside of the website https google.com we save it again try to access homepage and we are redirected to google.com now this is the end of this YouTube tutorial if you like the course so far maybe you want to check the entire course on my website the cod.com where you can find much more than what is available on YouTube you can find written lessons quizzes you can find the certificate of the completion the entire deployment section testing section and a lot more thanks for watching and I will see you in the next video

By Amjad Izhar
Contact: amjad.izhar@gmail.com
https://amjadizhar.blog
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!

Leave a comment