Author: Amjad Izhar

  • JavaScript Programming: From Fundamentals to Practical Applications

    JavaScript Programming: From Fundamentals to Practical Applications

    This YouTube transcript presents a comprehensive JavaScript course designed for beginners. The course covers fundamental concepts such as variables, data types, operators, control flow, functions, objects, classes, and the Document Object Model (DOM). It emphasizes practical application through real-world projects like a notes app, quiz app, and e-commerce product page. The transcript also includes explanations of JavaScript scope, event handling, and advanced topics like constructor functions and prototypes. Finally, there are instructions for building applications like a digital clock and a form validation project.

    JavaScript Fundamentals Study Guide

    Quiz

    Instructions: Answer the following questions in 2-3 sentences each.

    1. What is JavaScript, and what are two common uses for it in web development?
    2. Describe three different ways you can embed JavaScript code in an HTML file.
    3. Explain the difference between the var, let, and const keywords when declaring variables in JavaScript.
    4. Define “scope” in JavaScript, and name the three types of scope.
    5. Name four of the seven primitive data types in JavaScript and give an example of each.
    6. Explain the difference between the == and === operators in JavaScript.
    7. Describe the purpose of control flow statements in JavaScript and give one example of a conditional statement.
    8. Explain the difference between the break and continue statements within a JavaScript loop.
    9. What is a JavaScript function, and how is it defined and called?
    10. What is a JavaScript object, and how do you access properties and methods within it?

    Quiz Answer Key

    1. JavaScript is a scripting language used to create interactive and dynamic websites. It’s commonly used for front-end web development to add interactivity, such as button clicks and form validation, and also used in back-end web development with Node.js.
    2. JavaScript code can be embedded in an HTML file in the <head> tag within <script> tags, within the <body> tag, or through an external JavaScript file linked using the src attribute in the <script> tag.
    3. var is the oldest and most common way to declare variables, with function scope. let is a newer keyword that declares block-scoped variables, meaning they are only visible within the block in which they are declared. const is used to declare constants, which are variables that cannot be reassigned once they are declared.
    4. Scope refers to the visibility of variables and functions within a program. There are three types of scope in JavaScript: global scope, function scope, and block scope.
    5. Four primitive data types in JavaScript are: string (e.g., “Hello World”), number (e.g., 3.14), boolean (e.g., true), and undefined (a variable that has been declared but not assigned a value).
    6. The == operator checks for equality of values after type coercion, meaning it may convert the types of the operands before comparison. The === operator checks for strict equality, meaning it compares both the value and the type of the operands without type coercion.
    7. Control flow statements are used to control the order in which code is executed in a JavaScript program. An example of a conditional statement is the if statement, which executes a block of code only if a specified condition is true.
    8. The break statement is used to terminate a loop immediately, while the continue statement skips the current iteration of the loop and proceeds to the next iteration.
    9. A JavaScript function is a reusable block of code that performs a specific task. It’s defined using the function keyword followed by the function name, parameters (optional), and the code block enclosed in curly braces. It’s called by using the function name followed by parentheses.
    10. A JavaScript object is a non-primitive data type that stores a collection of data in key-value pairs. You can access properties using dot notation (e.g., object.property) or bracket notation (e.g., object[“property”]). Methods are functions associated with the object and are accessed the same way as properties (e.g. object.method()).

    Essay Questions

    1. Discuss the importance of understanding variable scope in JavaScript and how different types of scope can affect the behavior of your code. Provide examples to illustrate your points.
    2. Explain the concept of data types in JavaScript, differentiating between primitive and reference data types. How does an understanding of data types contribute to writing robust and error-free code?
    3. Describe the various operators available in JavaScript, categorizing them by function (arithmetic, assignment, comparison, logical). Explain how operator precedence and associativity impact the evaluation of expressions.
    4. Compare and contrast the different looping structures available in JavaScript (for, while, do…while). Provide scenarios where each type of loop would be most appropriate and justify your choices.
    5. Explain the concept of DOM (Document Object Model). Discuss DOM manipulation techniques using JavaScript. What is the importance of DOM manipulation in web development?

    Glossary of Key Terms

    • JavaScript: A scripting language primarily used to create interactive and dynamic websites.
    • DOM (Document Object Model): A programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content.
    • Variable: A storage location that holds a value.
    • Keyword: A reserved word that has a special meaning in the JavaScript language.
    • Scope: The visibility of variables and functions in a JavaScript program.
    • Global Scope: Variables declared outside any function or block, accessible from anywhere in the script.
    • Function Scope: Variables declared inside a function, only accessible within that function.
    • Block Scope: Variables declared inside a block (e.g., within an if statement or loop), only accessible within that block (introduced with let and const).
    • Data Type: The type of value that a variable can hold (e.g., string, number, boolean).
    • Primitive Data Type: Basic data types that represent a single value (string, number, boolean, null, undefined, symbol, bigInt).
    • String: A sequence of characters enclosed in single or double quotes.
    • Number: Represents numeric values, including integers and floating-point numbers.
    • Boolean: A data type with two possible values: true or false.
    • Undefined: A value assigned to a variable that has been declared but not yet assigned a value.
    • Operator: A symbol that performs an operation on one or more operands.
    • Arithmetic Operators: Operators used to perform mathematical calculations (e.g., +, -, *, /).
    • Assignment Operators: Operators used to assign values to variables (e.g., =, +=, -=).
    • Comparison Operators: Operators used to compare two values (e.g., ==, ===, >, <).
    • Logical Operators: Operators used to perform logical operations (e.g., &&, ||, !).
    • Operator Precedence: The order in which operators are evaluated in an expression.
    • Operator Associativity: The direction in which operators of the same precedence are evaluated (left-to-right or right-to-left).
    • Control Flow Statements: Statements that control the order in which code is executed (e.g., if, else, switch, for, while).
    • Conditional Statement: A statement that executes different code based on a condition (e.g., if, else if, else).
    • Loop: A control flow statement that repeats a block of code multiple times (e.g., for, while, do…while).
    • Function: A reusable block of code that performs a specific task.
    • Parameter: A variable declared in a function definition that receives a value when the function is called.
    • Argument: The actual value passed to a function when it is called.
    • Return Statement: A statement that ends the execution of a function and returns a value (optional).
    • Object: A collection of properties (key-value pairs).
    • Property: A key-value pair in an object, where the key is a string (or symbol) and the value can be any data type.
    • Method: A function that is a property of an object.
    • this Keyword: A keyword that refers to the current object in a method.
    • Constructor Function: A function used to create objects.
    • new Keyword: An operator used to create an instance of an object from a constructor function.
    • class Keyword: A keyword used to define a class, which is a blueprint for creating objects (introduced in ES6).
    • Getter: A special method in JavaScript that is called when a property is accessed, used to retrieve property values.
    • Setter: A special method in JavaScript that is called when a property is modified, used to set property values.
    • Event: An action that occurs in the web browser, such as a click, mouseover, or keypress.
    • Event Listener: A function that is executed when a specific event occurs.
    • Element: An individual component of an HTML document.
    • Node: A generic term for any type of object in the DOM tree (e.g., element, text, comment).
    • Parent Node: The node directly above another node in the DOM tree.
    • Child Node: A node directly below another node in the DOM tree.
    • Sibling Node: Nodes that share the same parent node in the DOM tree.
    • document.getElementById(): A DOM method to select a specific element.
    • document.querySelector(): A DOM method to select an element using CSS selectors.
    • document.querySelectorAll(): A DOM method to select a set of elements using CSS selectors.
    • element.parentNode: Returns parent element of specified node.
    • element.children: Returns HTMLCollection of an element’s child elements.
    • element.innerHTML: Sets or returns the content of an element.
    • element.textContent: Sets or returns the text content of an element.
    • element.setAttribute(): Sets the value of an attribute on the specified element.
    • element.classList: Returns the class names of an element.
    • Event Bubbling: Is an event flow model in which event flows from the most specific element to the least specific.
    • Event Capturing: Is an event flow model in which event flows from the least specific element to the most specific.

    JavaScript Tutorial: A Beginner’s Guide

    Okay, here’s a detailed briefing document summarizing the main themes and important ideas from the provided JavaScript tutorial excerpts.

    Briefing Document: JavaScript Tutorial Overview

    I. Main Themes

    • Introduction to JavaScript: The core of the excerpts focuses on introducing JavaScript as a scripting language essential for creating interactive and dynamic websites. It emphasizes its widespread use and relevance in modern web development.
    • Beginner-Friendly Approach: The tutorial is explicitly designed for individuals with no prior coding experience. It promises clear explanations, practical examples, and complete notes to facilitate learning.
    • Practical Application and Projects: A key element is the emphasis on learning by doing. The tutorial promises real-world projects (online notes app, quiz app, etc.) to solidify understanding.
    • Fundamental Concepts: The tutorial covers essential JavaScript concepts, including variables, data types, operators, control flow statements, functions, objects, and DOM manipulation.
    • Modern JavaScript Features: The excerpts touch on newer JavaScript features introduced in ES6, such as the let keyword and default parameters.
    • Emphasis on DOM (Document Object Model): A significant portion is dedicated to understanding and manipulating the DOM, enabling dynamic interaction with web page elements.
    • Event Handling: An introduction to JavaScript events, detailing how to make web pages interactive.
    • Project-Based Learning: Several mini-projects are outlined to provide hands-on experience in applying JavaScript concepts.

    II. Important Ideas and Facts

    • What is JavaScript?“JavaScript is a scripting language that is used to create interactive and dynamic websites.”
    • Interactive websites: enable user actions like “button click, submit a form, write comments, and live chat.”
    • Dynamic websites: change content/layout like “sliding effect, e-commerce website and quiz website.”
    • Why Learn JavaScript?“JavaScript is the most popular programming language in the world.”
    • Used by major websites: “Google, Facebook, Twitter, Amazon, Netflix.”
    • Vast ecosystem: “tons of Frameworks and libraries to reduce your time to create websites and mobile apps some of the popular Frameworks are react angular and vuejs.”
    • Career opportunities: “if you learn JavaScript it opens a lot of job opportunities in the software development Industries.”
    • Uses of JavaScript:Beyond front-end: “not only limited to front-end web development it is also used in backend web development mobile app development desktop app development game development and API creation.”
    • Setting Up a Development Environment:Requires a web browser (e.g., Google Chrome) and a code editor (e.g., Visual Studio Code).
    • Adding JavaScript to HTML:Inline: Within <script> tags in the <head> or <body>.
    • External: Using <script src=”script.js”></script>, linking to an external .js file.
    • “There are multiple options to display the output of JavaScript on the web page or browser.”
    • alert(“message”): Displays an alert box.
    • document.write(“message”): Writes directly to the HTML document.
    • console.log(“message”): Logs messages to the browser’s console.
    • Variables:“Variables are used to store data.”
    • Declaration: var, let, const.
    • var: Oldest, most common way.
    • let: Block-scoped (ES6).
    • const: Declares constants (cannot be reassigned).
    • Naming: Must begin with “alphabet dollar sign or underscore”.
    • Case-sensitive: “JavaScript is case sensitive”.
    • Scope:Global: Accessible from anywhere.
    • “variables and functions declared in the global scope are visible from anywhere in the program”
    • Function: Only accessible within the function.
    • “variables and functions declared in a functions scope are only ual within that function”
    • Block: Only accessible within the block (e.g., within an if statement).
    • “variables and functions declared in a block scope are only visible within that block”
    • Data Types:Primitive: String, Number, Boolean, Null, Undefined, BigInt, Symbol.
    • String: “a string is a sequence of zero or more characters”
    • Number: represents integer and floating point numbers
    • Boolean: true or false values
    • Reference: Object, Array, Function.
    • Object: “a non-primitive data type that allows you to store multiple collections of data”
    • Array: “arrays are a type of object that stores a collection of values”
    • Function: “functions are a type of object that can be used to execute code”
    • Dynamic Typing: “JavaScript is a dynamically typed language so we can store different data type in the same variable.”
    • Operators:Arithmetic: +, -, *, /, % (modulus), ** (exponentiation).
    • Assignment: =, +=, -=, *=, /=, %=, **=.
    • Increment/Decrement: ++, — (prefix and postfix).
    • Comparison: <, >, <=, >=, == (equality), != (inequality), === (strict equality), !== (strict inequality).
    • Logical: && (AND), || (OR), ! (NOT).
    • String: + (concatenation).
    • Operator Precedence and Associativity:Precedence: Determines the order of operations.
    • Associativity: Determines the order when operators have the same precedence (left-to-right or right-to-left).
    • Control Flow Statements:Conditional: if, else if, else, switch, ternary operator (condition ? valueIfTrue : valueIfFalse).
    • Loops: for, while, do…while.
    • break: Terminates a loop.
    • continue: Skips the current iteration.
    • Functions:“a block of code that performs the specific task.”
    • Declaration: function functionName(parameters) { … }.
    • Parameters and Arguments: Parameters are variables in the function definition; arguments are the values passed when calling the function.
    • Default Parameters: function myFunction(param1 = defaultValue) { … }.
    • return: Returns a value from the function.
    • Recursive Functions: Functions that call themselves.
    • Anonymous Functions: Functions without a name.
    • Callback Functions: Functions passed as arguments to other functions.
    • Objects:“a non-primitive data type that allows you to store multiple collections of data”
    • Key-value pairs: const myObject = { key1: value1, key2: value2 };.
    • Accessing properties: objectName.propertyName or objectName[“propertyName”].
    • Methods: Functions within objects.
    • this keyword: Refers to the current object.
    • Getters and Setters: Special methods to control property access and modification.
    • Classes:A blueprint for creating objects.
    • constructor: A special method to initialize object properties.
    • Methods: Functions within classes.
    • Inheritance: Creating new classes based on existing ones (using extends).
    • Private methods: A method inside of the class that can not be accessed from outside the class.
    • Static methods: can be accessed without creating an object of the class
    • DOM (Document Object Model):Represents the structure of an HTML document as a tree.
    • Nodes: Elements, text, attributes, etc.
    • Traversing: Moving through the DOM tree (parent, children, siblings).
    • parentNode: Returns the parent element of a node.
    • firstChild, lastChild: First and last child nodes.
    • childNodes: All child nodes.
    • nextElementSibling, previousElementSibling: Next and previous sibling elements.
    • Selecting Elements:
    • document.getElementById(“id”): Selects an element by its ID.
    • document.getElementsByClassName(“class”): Selects elements by class name (returns an HTMLCollection).
    • document.getElementsByTagName(“tag”): Selects elements by tag name (returns an HTMLCollection).
    • document.querySelector(“selector”): Selects the first element matching a CSS selector.
    • document.querySelectorAll(“selector”): Selects all elements matching a CSS selector (returns a NodeList).
    • Manipulating Elements:
    • document.createElement(“tag”): Creates a new HTML element.
    • element.appendChild(newNode): Adds a node as a child to an element.
    • element.textContent = “text”: Sets the text content of an element.
    • element.innerHTML = “html”: Sets the HTML content of an element.
    • element.setAttribute(“attribute”, “value”): Sets the value of an attribute.
    • element.removeAttribute(“attribute”): Removes an attribute.
    • element.classList: For adding, removing, and toggling CSS classes.
    • Adding and Removing elements:
    • element.insertAdjacentHTML(): A method to add HTML adjacent to an element.
    • replaceChild(): replaces a child element with a new one.
    • cloneNode(): clones a node.
    • removeChild(): removes a child element of a node.
    • insertBefore(): insert a new node before an existing node.
    • Attributes:
    • “The ID is the attribute name username is the attribute value”
    • to get the attributes of any HTML element use javaScript.
    • hasAttribute(): used to check whether an element has a specified attribute or not.
    • getAttribute(): method use to get the value of specified attribute.
    • setAttribute(): set the attribute.
    • removeAttribute(): remove the attribute.
    • Events:Actions that occur in the browser (e.g., click, mouseover, load).
    • Event bubbling: Event flow from the most specific element to the least.
    • Event capturing: Starts from the least specific element.

    III. Examples of Projects Mentioned

    • Online Notes App
    • Quiz App
    • Form Validation
    • Image Slider
    • Digital Clock
    • E-commerce Product Page
    • To-Do List App
    • Weather App
    • Calculator
    • Image Gallery

    IV. Conclusion

    The provided excerpts outline a comprehensive JavaScript tutorial suitable for beginners. It covers fundamental concepts, practical application through projects, and introduces modern JavaScript features. The emphasis on DOM manipulation and event handling highlights the tutorial’s focus on building interactive web experiences. By following this course, individuals with no prior programming experience can become proficient in JavaScript and be able to develop real-world applications.

    JavaScript FAQs: A Quick Reference

    Frequently Asked Questions about JavaScript

    1. What is JavaScript and what are its primary uses?

    JavaScript is a scripting language primarily used to create interactive and dynamic websites. It enables user actions like button clicks, form submissions, live chats, and website content or layout changes such as sliding effects, e-commerce functionalities, and quizzes. It can be used in front-end web development, back-end web development, mobile app development, desktop app development, game development, and API creation.

    2. Why should I learn JavaScript?

    JavaScript is the most popular programming language globally, used by almost all popular websites like Google, Facebook, Twitter, Amazon, and Netflix. It has numerous frameworks and libraries like React, Angular, and Vue.js, which help reduce development time. Learning JavaScript opens many job opportunities in the software development industry.

    3. How can I get started with writing JavaScript code?

    To start writing JavaScript, you need a web browser (like Google Chrome) and a code editor (like Visual Studio Code). You can add JavaScript code directly within the HTML file using the <script> tag in the <head> or <body>, or you can link an external JavaScript file using <script src=”script.js”></script>.

    4. What are variables in JavaScript and how do I declare them?

    Variables are used to store data. In JavaScript, you declare variables using the var, let, or const keywords. For example: var x = 30;, let x = 10;, or const a = 4;. var is the oldest and most common way, let is a newer keyword introduced in ES6 for block-scoped variables, and const is used for variables that should not be reassigned. Variable names must begin with an alphabet, dollar sign ($), or underscore (_).

    5. What is scope in JavaScript and what are the different types?

    Scope refers to the visibility of variables and functions within a program. There are three types of scope in JavaScript:

    • Global scope: Variables and functions declared in the global scope are visible from anywhere in the program.
    • Function scope: Variables and functions declared within a function are only visible within that function.
    • Block scope: Variables and functions declared within a block of code (enclosed in curly braces) are only visible within that block (using let or const).

    6. What are the different data types in JavaScript?

    JavaScript has two main categories of data types:

    • Primitive data types: These include string, number, boolean, null, undefined, bigint, and symbol.
    • Reference data types: These include object, array, and function.

    JavaScript is a dynamically typed language, allowing you to store different data types in the same variable during its lifecycle.

    7. What are operators in JavaScript and what are some common types?

    Operators are symbols used to perform operations on operands (values and variables). Common types include:

    • Arithmetic operators: Used for mathematical operations (e.g., +, -, *, /, %).
    • Assignment operators: Used to assign values to variables (e.g., =, +=, -=).
    • Comparison operators: Used to compare two values (e.g., ==, ===, !=, >, <). They return Boolean values.
    • Logical operators: Used to perform logical operations (e.g., && (AND), || (OR), ! (NOT)).
    • String operators: Used to concatenate strings (e.g., +).

    8. What are control flow statements in JavaScript and how are they used?

    Control flow statements are used to control the flow of execution in a JavaScript program. There are three main types:

    • Conditional statements: (e.g., if, else if, else, switch) used to execute different code based on different conditions.
    • Loops: (e.g., for, while, do…while) used to repeat a block of code.
    • try…catch statements: Used to handle errors.

    9. What are functions in JavaScript and how are they used?

    Functions are reusable blocks of code that perform specific tasks. You can define a function using the function keyword, followed by the function name, parameters (optional), and the function body. Functions can return values using the return statement. Parameters act as placeholders that receive argument values passed during the function call.

    10. How do parameters and arguments work in Javascript functions?

    Parameters are declared in the function definition, while arguments are the actual values passed to the function when it’s called. You can also use default parameters, which provide a default value if an argument is not provided when calling the function. JavaScript functions can be declared without names, also known as anonymous functions and can call upon themselves, known as recursion.

    11. What are objects in JavaScript and how do I work with them?

    Objects are non-primitive data types that store collections of data in key-value pairs. You can create objects using curly braces {}. Access properties using dot notation (e.g., object.property) or bracket notation (e.g., object[‘property’]). You can add, modify, and delete properties of an object. Objects can contain other objects, which are called nested objects, and methods.

    12. How do I define and use methods within JavaScript objects?

    Methods are functions that are properties of an object. You can define methods within an object using function expressions or by directly assigning a function to a property. You can call object methods using dot notation followed by parentheses (e.g., object.method()). To access other properties of the object within a method, you can use the this keyword.

    13. What is the DOM (Document Object Model) and how do I use it to manipulate web pages?

    The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. It allows JavaScript to dynamically access and update the content, structure, and style of web pages. You can select elements using methods like getElementById, getElementsByClassName, getElementsByTagName, querySelector, and querySelectorAll. You can traverse the DOM to navigate between parent, child, and sibling elements. You can manipulate elements by creating new elements, appending or inserting them, modifying content and attributes, and removing elements.

    14. How do I handle events in JavaScript?

    Events are actions that occur in the web browser (e.g., clicks, mouse movements, page loads). You can handle events using event listeners, which are functions that are executed when a specific event occurs. The two event models are event bubbling (event flows from the most specific element to the least) and event capturing (event flows from the least specific element to the most).

    15. What are classes in JavaScript and how do I use them?

    Classes are a template for creating objects. They are a way to organize and structure your code using object-oriented programming principles. A constructor is a special method within a class that is called when a new object is created from the class. The new keyword is used to create an instance of a class. Getters and setters are special methods that allow you to control how properties are accessed and modified. Using the # prefix indicates that the method is private. Static methods and properties are associated with the class itself, rather than with individual instances of the class. This means that you can access them directly using the class name without having to create an object.

    JavaScript Fundamentals: Variables, Data Types, and DOM Manipulation

    JavaScript is a scripting language utilized to create dynamic and interactive websites. A dynamic website can alter its content and layout, while an interactive website enables user actions like button clicks or form submissions.

    Key aspects of JavaScript covered in the sources include:

    • Variables and Scope Variables are used to store data and are declared using keywords like var, let, and const. The let keyword declares block-scoped variables, visible only within their defined block, while const declares variables that cannot be reassigned. JavaScript recognizes three types of scope: global, function, and block scope.
    • Data Types JavaScript divides data types into primitive and reference types. Primitive data types include string, number, boolean, null, undefined, bigint, and symbol. Reference data types include object, array, and function. JavaScript is a dynamically typed language, allowing variables to store different data types.
    • Operators Operators are symbols that perform operations on operands (values and variables). Types include arithmetic, assignment, comparison, logical, and string operators. Operator precedence determines the order in which operators are processed.
    • Control Flow Statements These statements manage the execution flow in a JavaScript program, enabling decisions, loops, and error handling. Common conditional statements are if, else if, and else. Loops include for, while, and do while loops. The break statement exits a loop, and the continue statement skips the current iteration.
    • Functions Functions are reusable code blocks that perform specific tasks. They are defined using the function keyword and can accept parameters and return values. Functions can be recursive, calling themselves within their own code. A callback is a function passed as an argument to another function.
    • Objects Objects store collections of data in key-value pairs. Objects can contain properties (data) and methods (functions). The this keyword refers to the object in which it is used. A constructor function is used to create objects.
    • Prototypes Every JavaScript object has a prototype property. Prototypes allow objects to inherit properties and methods.
    • Classes Introduced in ES6, classes are templates for creating objects. They contain a constructor method for initializing object properties and can have other methods.
    • DOM (Document Object Model) The DOM represents HTML documents, allowing JavaScript to manipulate webpage content and structure. Methods like getElementById, getElementsByName, getElementsByTagName, querySelector, and querySelectorAll are used to select HTML elements. JavaScript can modify element attributes, styles, and classes using DOM manipulation techniques.
    • Events Events are actions that occur in a web browser, like clicks or mouse movements. Event listeners are used to execute code in response to specific events. Common events include mousemove, mousedown, mouseup, mouseover, mouseout, keydown, keyup, and scroll.

    JavaScript DOM Manipulation Essentials

    DOM (Document Object Model) is an API for manipulating HTML documents. The DOM represents an HTML document as a tree of nodes, where each HTML tag, attribute, or text is a node.

    Selecting Elements To access and manipulate elements within an HTML document, JavaScript provides several DOM methods:

    • getElementById(id): Retrieves the element with the specified id attribute.
    • getElementsByName(name): Returns a collection of elements with the given name attribute.
    • getElementsByTagName(tagname): Returns a collection of elements with the specified tag name.
    • getElementsByClassName(classname): Returns a collection of elements with the given class name.
    • querySelector(selector): Returns the first element that matches the specified CSS selector.
    • querySelectorAll(selector): Returns a collection of all elements that match the specified CSS selector.

    Traversing Elements Once an element is selected, you can navigate the DOM tree to access its related nodes:

    • parentNode: Gets the parent node of the specified node.
    • firstChild: Gets the first child node of the specified element.
    • lastChild: Gets the last child node of the specified element.
    • childNodes: Gets all child nodes of the specified element.
    • firstElementChild: Gets the first element child of the specified element.
    • lastElementChild: Gets the last element child of the specified element.
    • nextElementSibling: Gets the next sibling element of the specified element.
    • previousElementSibling: Gets the previous sibling element of the specified element.

    Modifying Elements JavaScript provides several ways to modify HTML elements:

    • createElement(tagname): Creates a new HTML element with the specified tag name.
    • appendChild(node): Adds a node to the end of the list of child nodes for a specified parent node.
    • textContent: Gets or sets the text content of a node and its descendants.
    • innerHTML: Gets or sets the HTML code within an element.
    • after(node or string): Inserts one or more nodes or strings after the element.
    • append(node or string): Appends new nodes or strings to the end of the children of an element.
    • prepend(node): Adds a new node as the first child of an element.
    • insertAdjacentHTML(position, text): Inserts HTML code at a specified position relative to the element.
    • replaceChild(newchild, oldchild): Replaces a child element with a new one.
    • cloneNode(deep): Clones an element, optionally including its descendants (deep is a boolean value).
    • removeChild(child): Removes a child element from a node.
    • insertBefore(newnode, existingnode): Inserts a new node before an existing node as a child of a parent node.

    Attribute Manipulation HTML attributes can be accessed and modified using the following methods:

    • attributes: Returns a collection of all attributes of an element.
    • getAttribute(name): Gets the value of the attribute with the specified name.
    • setAttribute(name, value): Sets the value of an attribute.
    • hasAttribute(name): Returns a boolean value indicating whether the element has the specified attribute.
    • removeAttribute(name): Removes the attribute with the specified name.

    Style Manipulation The style of an element can be manipulated using the style property:

    • element.style.property: Gets or sets the value of an inline style property.

    Class Manipulation CSS classes of an element can be manipulated using the following properties:

    • className: Gets or sets the class name of an element as a string.
    • classList: Returns a collection of CSS classes of an element, providing methods to add, remove, toggle, and check classes.
    • add(classname): Adds a CSS class to the element.
    • remove(classname): Removes a CSS class from the element.
    • replace(oldclass, newclass): Replaces an existing class with a new one.
    • contains(classname): Checks if the element contains a specific class.
    • toggle(classname): Adds the class if it doesn’t exist or removes it if it does.

    Events Events are actions that occur in a web browser. Event listeners are used to execute code in response to specific events. There are three ways to assign event handlers:

    • Using HTML attributes.
    • Assigning event handler names in JavaScript.
    • Using the addEventListener method.

    The addEventListener method accepts three arguments: the event type, the function to be executed when the event fires, and an optional boolean value indicating whether to use capture. The removeEventListener method removes an event listener that was added using addEventListener.

    JavaScript Events and Event Handlers

    Events are actions that occur in a web browser, like clicks or mouse movements. An event handler, also known as an event listener, is a piece of code that will be executed when the event occurs.

    There are three ways to assign event handlers:

    1. Using HTML attributes: For each event, there is an event handler, and their names typically begin with on. For example, the event handler for a click event is onclick. The JavaScript code can be added within the quotes of the HTML attribute. The event handler attribute can also call a function. When the event occurs, the web browser passes an event object to the event handler. Inside the event handler, the this keyword refers to the target element on which the event occurs.
    2. Assigning event handler names in JavaScript: The event handler can be added to the HTML element in the JavaScript code. For example, element.onclick = function(){}. In this method also, the this keyword refers to the target element. To remove the event handler, assign null to the event handler.
    3. Using the addEventListener method: The addEventListener method registers an event handler, and the removeEventListener method removes an event handler that was added using addEventListener. The addEventListener accepts three arguments: the event type, the function to be executed when the event fires, and an optional boolean value indicating whether to use capture.

    Some useful JavaScript events:

    • mousemove: Fires repeatedly when you move the mouse cursor around the element.
    • mousedown: Fires when you press the mouse button on the element.
    • mouseup: Fires when you release the mouse button on the element.
    • mouseover: Occurs when the mouse cursor moves from outside to inside the boundaries of the element.
    • mouseout: Occurs when the mouse cursor is over an element and then moves to another element.
    • keydown: Fires when you press a key on the keyboard and fires repeatedly while you are holding down the key.
    • keyup: Fires when you release a key on the keyboard.
    • keypress: Occurs when you press a character keyboard like ABC and fires repeatedly while you hold down the key on the keyboard.
    • scroll: Occurs when you scroll a document or an element.

    When an event occurs, the event flows from the most specific element to the least specific element; this is event bubbling. When the event starts at the least specific element and flows towards the most specific element, this event model is known as event capturing.

    JavaScript Prototypes: Inheritance, Properties, and Methods

    In JavaScript, every function and object has its own property called prototype. A prototype itself is also an object, creating a prototype chain.

    Key aspects of JavaScript prototypes include:

    • Prototype Inheritance You can use the prototype to add properties and methods to a Constructor function, and objects inherit the properties and methods from a prototype.
    • Adding Properties To add a new property to a constructor function, use function name.prototype.property name = value.
    • Adding Methods To add a method, use function name.prototype.method name = function(){}.
    • Accessing Properties and Methods Objects created with the constructor function can access the properties and methods defined in the prototype.
    • Changing Prototype Values If a prototype value is changed, all new objects will have the changed property value, while previously created objects will have the previous value.

    For example, consider a constructor function Person:

    function Person(first, last) {

    this.firstName = first;

    this.lastName = last;

    }

    To add a new property called gender to the Person constructor function, use the prototype:

    Person.prototype.gender = “male”;

    To add a method called getFullName, use the prototype as well:

    Person.prototype.getFullName = function() {

    return this.firstName + ” ” + this.lastName;

    }

    Now, create two objects using the Person constructor function:

    const person1 = new Person(“Elon”, “Musk”);

    const person2 = new Person(“Bill”, “Gates”);

    The objects person1 and person2 can access the gender property and getFullName method:

    console.log(person1.gender); // Output: male

    console.log(person2.getFullName()); // Output: Bill Gates

    JavaScript and the DOM: Manipulating HTML Elements

    The sources provide information on manipulating HTML elements using JavaScript, primarily through the DOM (Document Object Model).

    Selecting HTML Elements To begin manipulating HTML elements, they must first be selected. Several DOM methods are available for this purpose:

    • getElementById(id): Selects an element by its id attribute.
    • getElementsByName(name): Retrieves all elements with a specific name attribute.
    • getElementsByTagName(tagname): Selects all elements with a given tag name.
    • getElementsByClassName(classname): Selects all elements with a specified class name.
    • querySelector(selector): Selects the first element that matches a CSS selector.
    • querySelectorAll(selector): Selects all elements that match a CSS selector.

    Traversing HTML Elements After selecting an element, it’s possible to navigate the DOM tree to reach related elements:

    • parentNode: Accesses the parent node of an element.
    • firstChild: Accesses the first child node of an element.
    • lastChild: Accesses the last child node of an element.
    • childNodes: Provides a collection of all child nodes of an element.
    • firstElementChild: Accesses the first element child of an element.
    • lastElementChild: Accesses the last element child of an element.
    • nextElementSibling: Accesses the next sibling element of an element.
    • previousElementSibling: Accesses the previous sibling element of an element.

    Modifying HTML Elements JavaScript offers various methods for modifying HTML elements:

    • createElement(tagname): Creates a new HTML element with the specified tag name.
    • appendChild(node): Adds a node as the last child of a parent node.
    • textContent: Sets or retrieves the text content of an element, ignoring HTML tags.
    • innerHTML: Sets or retrieves the HTML content within an element, interpreting HTML tags.
    • after(node or string): Inserts a node or string after a specified element.
    • append(node or string): Appends a node or string to the end of an element’s children.
    • prepend(node): Adds a node as the first child of an element.
    • insertAdjacentHTML(position, text): Inserts HTML at a specified position relative to an element.
    • replaceChild(newchild, oldchild): Replaces one child element of a node with another.
    • cloneNode(deep): Clones an HTML element. The deep argument specifies whether to clone all descendant nodes as well.
    • removeChild(child): Removes a child element from a node.
    • insertBefore(newnode, existingnode): Inserts a new node before an existing node.

    Working with HTML Attributes Attributes of HTML elements can be accessed and changed with these methods:

    • attributes: Returns a collection of all attributes of an element.
    • getAttribute(name): Retrieves the value of the attribute with the specified name.
    • setAttribute(name, value): Sets the value of an attribute.
    • hasAttribute(name): Checks if an element has a specific attribute.
    • removeAttribute(name): Removes an attribute from an element.

    Manipulating Element Style The style property is used to manipulate the inline styles of an HTML element:

    • element.style.property: Retrieves or sets the value of a CSS property.
    • element.style.cssText: Sets multiple CSS properties at once. Using += with cssText allows appending new styles without overriding existing ones.
    • getComputedStyle(element): Returns an object containing the values of all CSS properties of an element, including those from external stylesheets.

    Manipulating Classes CSS classes can be manipulated for styling purposes:

    • className: Gets or sets the class name of an element. Assigning a new value overwrites existing classes, but concatenation can be used to add classes without removing existing ones.
    • classList: Provides methods for adding, removing, and toggling CSS classes.
    • add(classname): Adds a class to an element.
    • remove(classname): Removes a class from an element.
    • replace(oldclass, newclass): Replaces one class with another.
    • contains(classname): Checks if an element has a specific class.
    • toggle(classname): Adds or removes a class, depending on its presence.
    JavaScript Full Course For Beginners With JavaScript Projects Tutorial And Notes 2024

    The Original Text

    hi guys welcome back to another video of greatest tack if you think JavaScript is difficult to learn and tired of watching multiple tutorials of JavaScript and still not feeling confident well you have come to the right video by the way this is not just a simple video but it is an ultimate course to start your journey into the exciting world of JavaScript in this JavaScript course we will start from the absolute Basics and I will guide you through the fundamentals of JavaScript that will help you to build a solid foundation in this course we will cover the introduction of JavaScript then we will see the basics of JavaScript where we will learn about the variables scope operators keyword reserved keywords and expression then we will see the data types and after that we will see the difference between primitive and reference values then we will move to operate s where we will learn about the arithmetic operator assignment operator logical operator comparison and then we will move to control flow statements where we will learn about if if else statements for while and do while loop and break and continue statement after that we will see the functions functions are important Concepts in JavaScript so in the function we will learn about the function parameters arguments return keyword in the function then we will see the anonymous function recursive function and default parameters after that we will learn about the objects and prototype where we will learn about the key values and method in the object then we will see the Constructor function prototype object D structuring and object literal syntax extensions after completing the object we will learn about the classes classes are also very important in JavaScript so in the classes we will learn about about the class getter and Setter methods then we’ll see the class Expressions inheritance static methods and private methods after completing the classes we will move to the Dom which is document object model so in this Dom we will learn about the notes then we will learn about get elements and query selected methods then we will see the create and clone element then we will learn add nodes to document then we will see get elements details using the Dom then we will learn about the modifying element using Dom then we will see get and modify the element class using the Dom then we will learn about the events available in this Dom each concept is clearly made to be beginner friendly with clear explanation and practical examples along with this I will also provide you the complete notes of this course in the video description but here is the best part it’s not just Theory at at the end of this tutorial we will make some real world projects like online Notes app Quiz app form validation image slider digital clock and e-commerce product page don’t worry you will not need any prior coding experience before starting this course by the end of this course you will be writing JavaScript code with confidence so are you ready to master JavaScript hit that subscribe button and help me to get the 5,000 likes on this course now let’s dive into the world of JavaScript together welcome to JavaScript introduction tutorial in this tutorial we will learn what is Javascript why you should learn JavaScript what is the use of JavaScript and how to write your first JavaScript program so what is Javascript JavaScript is a scripting language that is used to create interactive and dynamic websites interactive website means user can perform some action on website for example button click submit a form write comments and live chat Dynamic website means the website that changes its content or layout like sliding effect e-commerce website and quiz website why you should learn JavaScript JavaScript is the most popular programming language in the world it is used in almost all popular websites like Google Facebook Twitter Amazon Netflix and many others great thing about JavaScript is that you will find tons of Frameworks and libraries to reduce your time to create websites and mobile apps some of the popular Frameworks are react angular and vuejs if you learn JavaScript it opens a lot of job opportunities in the software development Industries what what is the use of JavaScript uses of JavaScript is not only limited to front-end web development it is also used in backend web development mobile app development desktop app development game development and API creation using JavaScript you can easily create websites like Amazon and Netflix mobile apps like Instagram and WhatsApp games like Tic Tac to and snake game you can also create mini JavaScript projects like to-do list app Quiz app Notes app weather app calculator or image gallery I already have 30 mini JavaScript projects on my YouTube channel that you can check out from the link given in the video description and these projects are more than enough to learn and practice JavaScript how to write your first JavaScript program to start with JavaScript you need to have a web browser and a code editor I’m using Google Chrome web browser and visual studio code editor I already have a tutorial how to download and install Visual Studio code editor you can find the video link in the description so let me open my code editor here I have one HTML file with basic HTML structure in this HTML page you can see we have the head open tag and head closing tag and this is the body open p and closing tag so the first option is to add the JavaScript code within the head tag so before closing of this head tag we can add our JavaScript code so let me add one a script tag a script open and closing tag like this and within this script we can add our JavaScript code so let me add one line of JavaScript here alert welcome to greatest stack this JavaScript code will give instruction to browser to alert this message welcome to greatest stack so let’s open this web page you can see this message welcome to greatest tack click okay so this was the first option to add the JavaScript code in the SML file now the second option is to write the JavaScript code within the body tag let me remove this script from here we have to add the code within this body tag so I will add it here a script open and closing tag within this we have the JavaScript code to alert one message welcome to greatest tag now let’s open the web page again and again you can see this message welcome to greatest tag so this JavaScript code written within the body tag is also working now let me remove it from here also there is another option to add the JavaScript code in the HTML file that is external Javascript so to add the external Javascript we will use a script SRC and the new file name so here let’s create a new file name and write the file name script.js you can write your own file name but the file name extension should bejs I’m writing a script.js you can write main.js index.js anything so this is the new file script.js and next we have to add this file here a script SRC and the file path a script.js so we have added the file path here now let me open the folder in this intro folder you can see there was one HTML file and now we have one more file the script.js and we have connected the script.js with the HTML file with thist script tag and now we can add our JavaScript code within this external file so here we will add alert welcome to greatest tag after adding this let’s come back to the website and now you can see this alert message welcome to greatest tag so this JavaScript code is also working now let me come back to the HTML file and we can move this a script tag in the head also like this and it will also work you can see this alert is working let me place it here within this body tag there are multiple options to display the output of JavaScript on the web page or browser so here I have added alert welcome to greatest T so we can see the message in the alert box there’s another option we can add document dot write welcome to greatest stack we can write like this document. write so it will write this message in the web page let’s see our web page you can see this message welcome to greatest tack it is written on the website now we have one more option here if I write console do log this will give the output in the browser console tab so let me show you come to this browser right click and select inspect it will open this developer tool and here you have to click on Console let me Zoom it click on Console we can change the theme by clicking on this setting icon appearance and do so this is the console tab here you can see this message welcome to greatest tag because here I have added console.log welcome to greatest tack if I change the message JavaScript tutorial come back to the website you can see welcome to greatest Tech here because I have added document. write and here you can see JavaScript tutorial because I have added console.log so it will add this message in the console Tab and in this console also we can add our JavaScript code we can write and execute the JavaScript code within this console tab also so let me show you one example if I write 4 + 5 and we got the result 9 so it is executing the JavaScript code here let me add one more thing if I write console dolog hello and hit enter you can see we have added console.log Hello and it is printed here hello now if you want to display the output on the browser alert box we can write like this alert hello hit enter you can see this alert box with the message hello now you can display the output on the website also let me add document dot WR and here we will add the message hello click enter you can see the Hello message on the website so this is how you can display the JavaScript output on your website or browser console and now you know how to write your JavaScript code so this was all about JavaScript introduction and writing your first JavaScript program what is variable in JavaScript variables are used to a store data it is like a container where we use to store things at home to declare a variable in JavaScript we use the V let and const keyword we can write where X here where is the keyword to declare a variable and X is the identifier or name of the variable we can also declare variable like let X or const X the V keyword is the oldest and the most common way to declare variables theet keyword is a newer keyword that was introduced in es6 we will learn about es6 later in the advanced JavaScript the const keyword is used to declare constants which are variables that cannot be changed once you have declared a variable you can assign a value to it using using equal sign for example where xal to 30 the following code declares a variable called X and assign it the value 30 variables can be used to store any type of data including number a string objects and arrays for example if I write where x equal to double quote or single quote any message hello world so here we are storing the string data type in the X variable variables name must begin with alphabet dollar sign or underscore if I write 2x it is not a valid name for the variable if I write anything in the alphabet it is valid and we can also declare it with the dollar sign we can start like this dollar X it is valid and we can also use underscore here like this underscore X let me remove it so you can see it is valid format to write a variable name you can start with dollar and you can start with any alphabet in upper case or lower case it is valid but if you start from the number it is not a valid name for the variable if you add the valid character then later you can add number it is valid JavaScript is case sensitive so if you write where first name equal to greatest stack and if you write first name with the lowercase end so these two variables name are different it is not same because here we have the different case so JavaScript is case sensitive that’s why it is two different variables name now let’s understand about the let keyword let keyword in JavaScript is used to declare a block scoped variable this means that the variable is only visible within the Block in which it is dict cleared for example if I write let x equal to 10 and if x greater than 5 yes it is greater than 5 because the x value is 10 in this block we will add let y = to 20 and here if I try to display the value of y we will add console do log y so you can see this y value in the console tab here you can see 20 correct we have added this code within this curly bres so it’s a block and if I try to access this y outside of this block we will copy this and paste it here here outside of this block and now if I try to run it you can see one error reference error why is not defined so if you try to access the Y value outside of this if statement you will get a reference error this is because variable Y is not defined outside of this block now let’s understand about the const keyword so the const keyword in JavaScript is used to declare a con Conant variable this means that the variable cannot be reassigned to a new value for example if I write const a equal to 4 so we are assigning a value for in the a variable now if I print this console do log a we will get four in the console tab now in the next line if I try to write AAL to 5 we are trying to reassign a new value a equal to 5 and run this you can see we got an error assignment to constant variable so we cannot assign a new value in constant variable now let’s learn about the scope in Java JavaScript scope in JavaScript refers to the visibility of variables and functions within a program in JavaScript there are three type of a scope Global scope function scope and the third one is block scope so let’s learn about the global scope the global scope is the outermost scope in the JavaScript program variables and functions declared in the global scope are visible from anywhere in the program let’s understand it with one example if I write where x equal to hello greatest stack and here we create one function called example and in this one if if I try to print this message if I write console do log X and now we have to call this function example now you can see this message in the console tab hello greatest stack over here in this example we have declared a variable X outside of any function or block which makes it a global variable Global variables are accessible from anywhere in the script including inside a function and we have declared this outside of the function so we can access it within the function and outside of the function also if I simply add this here and it will also print this you can see Hello greatest stack two times the first one is printed using this console.log written inside the function and the second message is printed using this console.log x so this was the global scope now let’s understand what is the function scope so the function scope is created when a function is declared variables and functions declared in a functions scope are only ual within that function so let’s understand this function scope with one example here we will add function example here we will create one variable where FS function scope equal to hello greatest stch and if I try to display the output we will add console. log fs and now just call this function so now you can see this message hello greatest TCH because we are accessing this variable inside this function now if I try to access this FS outside of this function let’s copy this and paste it here outside of this function and try to run it we got an error FS is not defined why because we have defined this FS variable inside this function so it is a function scope variable and now we are trying to access this FS outside of this function it is not accessible so the variables and functions declared in a functions scope are only visible within that function now let’s understand the block scope so the block scope in JavaScript refers to the visibility of variables and functions within a block of code a block of code is a group of statement that are enclosed in a curly braces variables and functions declared in a block scope are only visible within that block let’s understand block scope with one example let’s create one function and in this one we will create one block true and here we are creating one block with this curly bres So within this if we will add one variable so let’s add the variable name block variable BV equal to create a stack and here if we try to display this console.log BV and just call this example now you can see this message greatest stack in the console tab here because we are accessing this variable inside this block now if I try to access this variable outside of this block it is declared inside this block and if I try to access here this block is closing here so let’s add this line here at line number n and now if I try to run you can see we got an error in line number nine BV is not defined because we are accessing this variable outside of this block let’s try to access this variable outside of this function only let’s remove it from here and add it here at the end and now you can see the error message at line number 12 BV is not defined because we are trying to access this variable outside of this block so the variable and functions declared in a block scope are only visible within that block so this was all about the variables and the scope in JavaScript data types in JavaScript data types is an important Concept in any programming language to perform any task with the data it is important to know its type data types in JavaScript are divided into two categories primitive data type and reference data type there are seven primitive data types in JavaScript which are a string number buo null undefined big int and symbol so let’s learn about the string data type in JavaScript a string is a sequence of zero or more characters a string starts and end with either a single quote or a double quote JavaScript strings are for storing and manipulating text for example if I write let first name equal to double code elone so here we are adding one name in double quote it is a string and the variable name is first name let me duplicate it here we will add last name and if I write the text in single quote musk it is also a string it is written in double quote and this is written in the single quote now let’s see another data type which is number number represents integer and floating Point numbers for example if I write let num equal to 100 in this statement we have declared one variable called num and initialized its value with the integer 100 let me change the value if I write 96.5 it is also a number type here we have stored the floating number if we write 96.0 then JavaScript will convert it into an integer number to use less memory so it will be saved only 96 let me show you that if I write console.log num so you can see 96 is printed here it is not printing 96.0 it is printing 96 only because the JavaScript is converting this floating number into an integer and if I type 96.5 it will be saved as 96.5 and if we change 96. it will be only 96 now let me tell take another example if I write let x equal to 10 so here I have stored one number in the X variable let me write console.log X here we will get 10 in this console tab we got 10 now if I add a single quote in this 10 now it will become string because we are adding single quote in this text now if I print this one you can see still it is displaying 10 but if you will check the data type it will be a string the value is 10 but the data type is a string to check the data type we have one operator called type of in front of this variable name if I write type of X you can see we got the data type string because this 10 is written inside the single quote if I change it and make double quote still it will be string you can see string here now if I remove this quote and if we only write 10 then it will be a number you can see it is number when we will add double quote or single quote it will be stored as a string now the next data type is Boolean the Boolean data type has two values true and false let’s understand it with one example if I write let learning equal to true and and let completed equal to false here we have stored Boolean data in the learning variable and completed variable now to check this one we will add console.log learning you can see true so it is display the value stored in this learning now to check the type of the data stored in this learning we will again use the type of operator type of learning so it is displaying the data type Boolean now let’s check the data type of this another variable which is completed just copy this one add it here here it will display the data type Boolean for the another variable called completed now if you want to display the value stored in this completed here I’m adding console.log completed and it is displaying false here which is the value stored in the completed variable and it is the type of the value which is Boolean so we have stored the true or false value directly but we can store the result of any expression for for example if I write let X = to 20 greater than 10 so the result of this is true 20 is greater than 10 it is true so now if you want to check the value stored in the X we will add console.log X and now you can see it is displaying true here we are writing 20 greater than 10 but the X has stored the result of this expression which is true now if I change if I write 20 less than 10 which is false so you can see the result in the console tab it is displaying false so we have stored the false in the X variable now let me show you the type of the data here we will add type of X and now it is displaying Boolean so this x has a store the Boolean data type next primitive data type is undefined if a variable is declared but the value is not assigned then the value of that variable will be undefined and the data type is also undefined let me show you this with one example let H we have declared a variable age but we have not assigned any value now we will check the value stored in this age let’s add console.log age here you can see the value is undefined now if you want to check the type of the data here we will add console.log type of age now you can see the value is also undefined and the type is also undefined if we add any value like this a is 30 now you can see the value is 30 and the type is number and when we remove it we have not assigned any value so the value is undefined and type is undefined so this was undefined data type next pleas primitive data type is null in the JavaScript null is a special data type that represents empty or unknown value let’s understand it with one example here if I write let number equal to null and now we will try to print the value here we will add console log number so you can see the result it is displaying null now we will try to display the type of the data so here in the next line we will add console.log type of number you can see the value is null but the type is object the type should be null but it says the type is object it is a known bug in JavaScript JavaScript defines that null is equal to undefined to check this one we will write console.log null comparison operator then undefined so we are comparing null with the undefined and here you can see we got the result true it means in JavaScript null is equal to undefined there are two other primitive data types which are symbol and B that we will study in our upcoming videos now let’s learn about the reference data type so the first reference data type is object in JavaScript an object is a collection of properties where each property is is defined as a key value pair so let me create one object here if I write let person equal to curlys that’s it so the following code defines an empty object this is the person object which is empty now let me display the data stored in this person object for that we will add console.log person that’s it now you can see we got the empty curly bles now to check the type of the data we will copy this one and here we will add type of person so you can see the result the data is empty in this curly Braes and the data type is object now let’s add some properties in this person object here we will add first [Applause] name last name and age let’s add 35 so you can see in the console tab the data type is object and this is the data stored in the person object first name Elon last name musk age 35 an object can store different data type in this person object the first name and the last name are string and this age is number so this person object can store different type of data it can also store another object our next reference data type is array arays are a type of object that stores a collection of values for example if I write let number we have have added five different number separated by comma in the square bracket so the following code creates an array of numbers now let’s print the value of this number we will add console.log number so in the console tab you can see this aray is printed 1 2 3 4 and 5 the same thing is printed here now if you want to check check the type so let’s add this line again and in this one we will add type of operator type of number now you can see in the console tab we got the type object so the array is also an object data type our next data types is function functions are a type of object that can be used to execute code for example here we will create one function to create a function we use the function keyword and the name of the function so let’s add the function name MSG that is for the message and in this one just add one console.log and here we will add one string hello greatest tag so we have declared one function with the function name MSG now if you want to check the type of the data here we will add console.log type of MSG that is function name and if I check this in the console tab you can see it is displaying function it says the type of data is function but it is also an object data type Javas script is a dynamically typed language so we can store different data type in the same variable for example if I write let X here we are not assigning any value so the data type will be undefined so let’s check this one type of X it is displaying undefined let’s check the value also if I write console.log X console.log type of X so it will display the value stored in the X and it will display the data type now you can see in the console tab it is displaying the value undefined and data type undefined now in the same variable we can store different data type here we have already declared the variable so we will just add X we are not declaring we are just assigning the value x equal to let’s say one string greatest tag so here we are adding one string in the X variable let’s try to to print this you can see in the console tab it is printing undefined and undefined from here now we have changed the data it is greatest tag which is string so you can see the value and the data type is a string now again we can change the type of the data we will simply store another data let’s add x equal to 100 so here we have stored the number let’s try to print this now you can see in the console tab we have the value 100 and we have the type number so earlier it was undefined then it is a string then it is number now let’s add one more example if I write X true and in the console tab you can see it is true and the data type is Boolean so the JavaScript is dynamically typed language so we can store different type of data in the same variable and in this one you can see the example also it is undefined it is string it is number it is Boolean so this was all about the data types in JavaScript operators in JavaScript operators in JavaScript are symbols that are used to perform operations on operants operant are the values and variables so let’s understand it with one example here if I write 10 + 20 here plus is an operator and 10 and 20 are operant here is the list of different operators that we will learn in this tutorial arithmetic operators assignment operator comparison operators logical operators and string operators now let’s learn arithmetic operators arithmetic operators are used to perform mathematical operations on operants there are multiple arithmetic operators so first one is addition here we will add let sum equal to 5 + 3 and console.log sum so in the console tab you can see we got the sum which is 8 5 + 3al 8 this is the addition operator now let’s learn the second one which is substraction here we will add substraction it will be x 5 – 3 three it will be X now you can see two in the console tab because 5 – 3 is 2 so this is the substraction now the next one is multiplication if I write five multiply 3 now you can see the result 15 now the next one is division operator for division views forward slash let’s add 15 ided 3 now you can see the result 5 15 / 3al to 5 now the next one is reminder or modulus here we will add modulus and to get the modulus we use percent symbol and and if I write 17 perc 4 now we will get the modulus 1 you can see when you divide 17 by 4 you will get the reminder 1 which is modulus now the next arithmetic operator is exponentiation when you write 2 to ^ 4 2 to the^ 5 that is exponential so to calculate the exponential here we will add X two double star and four so it means we will add 2 into 2 into 2 four times like this so what will be the result you can see in the console tab 16 so if you write dou star it will be exponentiation operator so these are arithmetic operators now let’s learn about the assignment operator assignment operators are used to assign values to variables we use equal sign to assign operator for example let X = to 5 here we are using equal sign which is the assignment operator and we write the value on the right side of the operator so this was the simple assignment M operator now we have other assignment operator also like addition assignment so let’s see that we have the x value 5 now we will add X Plus equal to 3 so if you simply add x = 3 it will replace the value in this x variable and the X will become three but here we are adding plus it means this three will be added in the existing value of this x so the current value of x is 5 and 5 + 3 will be 8 let’s check the output console. log X and in the console tab you can see the value8 so this was the addition assignment similarly we have the substraction assignment here we will add minus equal to 3 now we will get the output two you can see the output 2 now we have the multiplication here we will add multiply 3 so this three will be multiplied with the current value which is 5 5 into 3 and now you can see the output 15 next one is division assignment you can see this value here after that we have the modulus assignment you can see see the modulus 2 now the next one is exponentiation assignment dou star equal to 3 it means we are writing 5 to the^ 3 and it will be 5 * 5 * 5 so the result is 125 now let’s learn about increment and decrement operators the increment and decrement operators are used to increase or decrease the value of a variable by one suppose the variable value is five it will be incremented by 1 and it will become six or it will be decremented by one it will become four the increment operator is Plus+ and the decrement operator is minus minus increment and decrement operators can be used in two ways which is prefix and postfix so let’s learn prefix increment and decrement operator let me add one example here let a equal to 10 in the next line I’ll add console. log Plus+ a we are adding increment operator before the variable name which is a now you can see the output 11 because the value of a has been incremented by one now let me add one more line console.log a so in this line the value of a is incremented by 1 then it is printed 11 and in this line the current value of a is printed the current value is 11 in this example operator is placed before the variable and the value of the variable is increased before it is used now let’s see prefix decrement operator so for decrement we will add minus minus and in the console tab you can see the output 9 and 9 so it is decreasing the value of a by 1 then it is printed here and in the next line we are printing the current value of a which is 9 now let’s learn about the postfix increment and decrement operator in the postfix we add the operator after the variable so if I remove this and add Plus+ after a now you can see the output first it is printing 10 and after that 11 here we are adding A++ but still it is printing 10 because a is printed first and after that it is increasing the the a value by one now the next time I will print the a value it will display the updated value here it is displaying 11 in this example operator is placed after the variable and the value of the variable is used before it is incremented the same thing will happen with the decrement post fix operator if I run this one you can see current value of a is 10 and first it is printing the value 10 after that it is decreasing the value by one and if I print the new value of a it is N9 so this was the increment and decrement operator now let’s learn about comparison operator comparison operators compare two values and give back a Boolean value either true or false comparison operators are useful in decision- making and loop programming in JavaScript let’s see some example if I write like this it will be the less than operator it is greater than this will be less than or equal to this is greater or equal to this will be equal check it will check the equality of two values it will be inequality or not equal and it will give the flip value of the equal checks we will understand it with the example also and this one is the strict equality check it checks the data type also I will also explain it with example and it is the strict inequality or flipped value of the strict equality check now let’s understand these comparison operators with example here if I add let a = to 10 b equal to 20 and here we are adding less than operator you can see console. log a less than V so it will give the result true in this one it is checking a greater than b which is false a is 10 B is 20 so a greater than b is false so it will give the result false now it is a less equal to B so it will be true and this will be false a greater or equal to B it is false because a value is 10 now here we are checking a equal equal B it means a value is equal to B is not equal it is 10 and 20 so it will be false in this not equal we will get the flipped result of this equality check so the equality check was false so this will be true and this is the strict equality check and this is the strict unequality check so let’s print this one you can see the first one is true a less than b true a greater than b false a less than equal to B this true a greater equal to B it is false A = to B 10 = to 20 which is false a not equal to B so it will be true now in the next line we are adding a strict equal so A and B is 10 and 20 it is not equal so we will get false and it will be the opposite it result true now let’s understand it with other example if I remove this and here if I write like this 10 and it will be 10 so a is 10 as a string and B is 10 as a number now let me add one more thing here console.log a equal equal B now you can see the first one is true why a is 10 B is 10 then it is true now in the next line we are adding a triple equal to V it is giving false why first it will check the data type so in this one the data type is a string and the data type is number in the B variable then it is different so it is not equal so that’s why it is giving false and the last one is giving true because it will give the flipped value of this false our next topic is logical operators logical operators perform logical operations like and or not for logical and we use this symbol for logical or we use this symbol and for logical not we use this exclamation symbol so let’s learn about the logical and logical and evaluate op and return true only if all are true in this line you can see the first condition is true and the second is true and here we are adding logical and operator so both are true that’s why the result will be true now in this one the first one is true second one is false so both conditions are not true that’s why it is false here also one of the condition is false it is false here both conditions are false that’s why it is false only when both conditions are true then only the result will be true now let’s understand logical and operator with one example here I have added let X = to 5 and y equal to 10 and I’m adding X greater than 0 so this condition is true X is obviously greater than z y is also greater than zero then the first condition is true second is also true then the result will be true you can see the first result is true now in the second condition you can see X greater than 0 which is true y less than 0 which is false 10 less than 0 is false right then one of the condition is false that’s why the result is false now in The Third One X less than Z which is false then the result will be false and in the last one 5 less than 0 is false and Y isal to 10 which is 10 less than 0 which is false so both conditions are false that’s why the logic result is false so this was The Logical end now let’s learn about the logical or logical or returns true if one of the multiple operant is true if any one oper is true then it will return true so here you can see the first one is true true and second one is true so the output will be true first one is true second is false still the output is true first one is false second is true then the output is true in the last one first condition is false and second condition is also false then the result will be false so if all operant are false then the output will be false and if any one of the operant is true the result will be true now let’s understand this logical or with one example here we have the a value 5 b value 10 and a greater than Z true B greater than Z true so both conditions are true then result will be true now here the first one is true this is false then still it is true it is false it is true then still it is true now in the last one for first one is false second one is false so both operant are false so the result is false so this is the logical or operator now let’s learn about The Logical not logical not converts operator to Boolean and return flipped value let’s understand it with one example if I write let yes is equal to True let no equal to false we are adding two variable yes and no and yes is true no is false and if I try to print not yes not operator and yes then it will give the flipped result earlier it was true now it will display false you can see the first one is false here in the second one we are adding not no so the no value is false so the not no will be true you can see the not no is true so this is The Logical not operator our next topic is Javascript string operators in JavaScript you can also use plus operator to concatenate or join two or more strings let me explain this with one example if I write console.log and in this one in this one we will add two string let me add hello Plus World and let’s see the console tab you can see hello world is printed here if you need one space we will add it here now you can see it is printed with one space hello world we we can join the string using the addition assignment operator Also let’s see another example if I write let a equal to JavaScript and in the next line I will add a addition assignment operator plus equal to and here we will add another text so let’s add a space tutorial in the current value of a the current value is Javascript and in this JavaScript it will add this tutorial let’s print it in the console you can see this text JavaScript tutorial is printed in this console tab so this is how you can join or concatenate strings in JavaScript using the plus operator so this was the string operator in JavaScript there’s one more operator in JavaScript which is bitwise operator bitwise operators are rarely used in everyday programming that’s why we will skip this one our next topic is operator precedence operator precedence in JavaScript determines the order in which operators are passed concerning each other let me take one example let result equal to 2 + 3 * by 4 so what will be the output here if you add 2 + 3 it will be 5 and 5 * by 4 it will be 20 so this will be output or it will will be 4 * by 3 12 + 2 = 14 so which is the correct answer so the correct value is 14 let me show this result in console tab now in the console tab you can see the output 14 why because the 3 * by 4 is performing first and after that it is adding two so why multiplication is performed before addition it is because of the operator’s precedence value in this table you can see the Precedence of multiplication and precedence of addition so the higher precedence is performed first that’s why it is multiplying three and four after that it is adding two and the result is 14 so this was operator precedence now let’s learn about Operator associativity Operator associativity in JavaScript defines the order in which operators of the same precedence are evaluated there are two type of operator associativity left to right right to left in this table you can see the operator name and their associativity now let’s learn about the left to right associativity in left to right associativity operators are evaluated from left to right let’s take one example if I add let result equal to 4 – 2 – 1 in this example only substraction operator is used and its associativity is left to right as you can see in this table the expression 4 – 2 – 4 is evaluated from left to right first 4 minus 2 will be evaluated and it will give the result 2 then 2 – 1 will be evaluated and it will give the result one so let’s check the result in the console tab you can see the result one so this was left to right associativity now let’s learn about the right to left associativity in right to left associativity operators are evaluated from right to left for example let result equal to two exponentiation 3 exponentiation 2 in this example only exponentiation operator is used and its associativity is from right to left as you can see in this table first three exponentiation 2 is calculated resulting in N then 2 exponentiation 9 is evaluated and giving the result 500 12 so let’s see the result in the console tab here if I write log result you can see the result 512 so this was all about the JavaScript operators control flow statements in JavaScript control flow statements are used to control the flow of execution in JavaScript program they are used to make decisions execute loops and handle errors there are three type of control flow statements in JavaScript which is conditional statements loops and try catch statements so now let’s learn about conditional statements conditional statements are used to execute different code based on different condition the most common conditional statements in JavaScript are are if a statement else a statement and else if a statement if a statement in JavaScript is used to execute a block of code if a condition is true so let’s understand it with one example here we will add if and in this parenthesis we will add one condition condition will be true or false so we will add true in this block let’s add one line of code execute so in the console tab you can see this message execute in this example the condition is true that’s why it is executing this code and it is printing execute in this console tab now if I change it here we will add false and now in the console tab you can see nothing is printed why because if the condition is false then any code written within this block will be skipped it will not execute now let’s understand it with another example here we will add age greater than 18 and let’s add let age equal to 20 and and it will print one message you are an adult so here we have the age value 20 and the condition is age greater than 18 so you can see 20 is greater than 18 that’s why this block of code will be executed and we will see this message here now if we change the value of this age let’s add 16 now in the console tab you can see it is blank nothing is printed why because this condition is false 16 greater than 18 is false that’s why this code will not be executed let me comment this and we will take another example and here let’s understand with another example we will add let country equal to India and let age equal to 20 if age greater equal to 18 and operator country equal to India so this is the if statement where we are adding two conditions using the logical and operator here we are adding logical and that’s why if the first condition is true and second condition is true then only this complete line output will be true so you can see the age is 20 which is greater than 18 and country is India and here it is comparing with India so this condition is also true and this is also true then overall result is true so we can print any message console.log you can get a driver’s license now you can see it is printed here in this console tab you can get your driver license now if I change the age value to 17 now nothing is printed in this console tab it is empty so you can add this type of logical or logical and operator to get the true or false value and then if the value is true then only this code will be executed now let’s learn about the if Elsa statement if Elsa statement in JavaScript is a conditional statement that is used to execute a block of code if a condition is true and another block of code if the condition is false so let’s understand it with one example here we will add the same example here you can see if the condition is true then only this code will be executed now we have to add another statement that will be executed when the condition is false so here just add else in this else condition I will print another message console.log you a minor now you can see in in the console tab we got an message you are a minor why because the age is 18 so the if condition is false here we are adding 16 greater than 18 which is false so if it is false then else condition will be executed and if I change the value 19 you can see the message you are an adult the if condition is getting executed next conditional statement is else if so in this example we have one if condition and one else condition now we need another condition also so here we will add else if and in this one let’s add one condition check here we will add age greater equal to 16 it will be greater equal to 18 and in this else if let’s print one message console.log you are a teenager so what will happen in this program first it will check if it is 19 this if condition will be executed now if this condition is false suppose the value is 7 1 now it will jump to the next statement the first one is false it will come to the next statement which is else if and in this one it will check whether the condition is true or false if the condition is true then only this code will be executed else it will go to the another statement so here let’s check age is 17 and 17 is greater than 16 correct so that’s why this condition is true then this code will be ex uted now let’s check this one and you can see in the console tab we got the message you are a teenager it is printing from this console.log which is in the else if statement like this you can have multiple else if a statement suppose this is also false let’s add 15 age is 15 so this condition is false this condition is also false so it will execute the else condition condition else condition is ur minor you can see in the console tab the message Ur minor now you know the if statement else if statement and else statement now we will learn about this switch in JavaScript the switch statement in JavaScript is a conditional statement that is used to execute a block of code based on the value of an expression let’s understand the switch with one example here if we write let value is equal to 42 and then we will add the switch statement so this is the syntax to write this switcher statement in this one we will add type of value so it will get the type of this value variable and the type is number for now now in this case we will execute different message we can create multiple cases so in the first case let’s add number so if the type is number then we will print console.log number we can add multiple case so let’s duplicate it and here we will add string console.log string let’s add another one it will be Boolean console.log bullion in the default we will add console.log other now in this switch statement you can see the output is number why because we are adding value is equal to 42 which is is the number type and here it will check the case if it is number then it will print number now if we change the type if I add hello so the type of this variable is a string so it will check this case it is not correct then it will check this case so the type is a string correct that’s why it is printing this message now if I change it let’s add true so the type is Boolean so this case will be executed and it will print Boolean now if I add anything else let’s add one array now you can see other is printed here because this case is also false this is also false this is also false so it will print the default one so in this default we have added message other that’s why it is printing other in this console tab now let’s take another example of this switch case here we will add day name and the day name let’s add two suppose the day start with Sunday Monday Tuesday and the number is 1 2 3 for Sunday it is 1 Monday it is two so here we are adding let day name is equal to two now let’s add the switch statement went went in this one we have to pass the day name so let’s add switch day name as a key and here we will add different values so first value will be one and here day name is equal to Sunday now we will add second case case 2 so the day name will be Monday let’s add case three so we have added seven different Case Case 1 2 3 4 5 6 7 and name of the day wednessday Thursday Friday Saturday suppose we have entered Any number greater than 7 then we will display another message so here in this default we will add day name is equal to invalid day number now to print this we will add console.log let’s add the message the day is plus day name this is the string and this is the variable now in the console tab you can see the day is Monday why because we have added day name two now let’s change it here we will add five and we will check the console tab you can see the day is Thursday let’s add seven so it will check this case one then it will check two then it will check three so it is seven so it will come here case and the value is seven then day name will be Saturday and it will be printed using this console the day is Saturday so this is the switch case statement in the JavaScript now we will learn Turner operator it also works like if else a statement let me write the example of if else a stat M so here we have added let age equal to 20 if a greater than or equal to 18 so if this condition is true this code will be executed and if this condition is false then else statement will be executed now the same thing we can execute using the Turner operator for Turner operator we use this question mark now let’s see the Syntax for the Turner operator first we will add condition then question mark and after this question mark we will add the code that will be executed if the condition is true so here we will add value if true now we will add column and here we will add the code that will be executed if the condition is false value if false this is the syntax to use the Turner operator now let’s understand with example so here we will add the same thing let age is equal to 20 and now we will add the condition like this age greater equal to 18 question mark if it is greater then what we will print we will print Ur an adult this will be the message and if it is false this condition is false then we will print you are a minor we can directly write console.log and this message so it will be printed in the console tab so this will become so long that’s why here I’m adding let MSG is equal to this either this message or this message will be stored in this MSG now we will add console.log MSG let’s see the output in the console tab you are an adult now if I change the value it will be 16 now check this you are a minor so this is how the Turner operator is working same as the F statement so this was all about the conditional statements Loops in JavaScript in programming Loops are used to repeat a block of code for example if you want to display a message 100 times then you can use a loop first we will learn about the for Loop syntax of the for Loop is this one you have to add for then in this parenthesis we are adding the initial value of I after that we are checking the condition if this condition is true then only this code will be executed and after execution of this code written in this curly reses it will increase the value of I by 1 now let’s understand the for loop with one example suppose I want to print one message 10 times for that here let’s add console.log and in the message I will add greatest stag so I want to print this greatest stack 10 times let’s start it with one initial value of I is 1 and I want to print this for 10 times so here we will add less than equal to 10 this is simple now if I run this code you can see Greatest Tag is printed 10 times you can see 10 here we are printing the same message 10 time that’s why the browser will collapse it and display only one line and here it will display 10 it is printed 10 times now let’s take the another example of for loop I want to print number from 1 to 10 for that this for condition will be same here we will just add I so first what will happen the I value will be one and it will be printed using this console. log I after that it will increase the value so the I value will be 2 and it is less than 10 right then it will print two again it will increase the value that will be I3 and IAL to 3 is less than 10 so 3 will be printed so like this it will be printed up to 10 now run this code and you can see 1 2 3 up to 10 is printed in this console tab we can use Loops for printing the data of an array let’s take another example let me comment it and here I will add let coding equal to one array and in this array I will add JavaScript python C++ now I want to print the JavaScript Python and CPP using for Loop to get the element we use the index so index I start with zero JavaScript is at zero index python have index one CPP have index two so let’s write the for Loop here we will add for let’s add let I is equal to 0 because index starts with zero now I will be less than the length of array so this is the array dot length so AR length is three maximum index value is two that’s why I’m adding I less than coding do length that is 3 I Less Than 3 after that we will add i++ and in this C adds we will add the code that has to be executed every time so here we will add console.log coding and I first it will execute coding zero then coding one and coding two so coding zero will display JavaScript coding 1 will display Python and coding two will display CPP so you can see the output in this console tab JavaScript Python and CPP so you can use the loop on ADD also we can create another loop inside a loop let’s see another example here we already have this code this is the first Loop and let me make it small I’ll add one to five and it will print the number from 1 to 5 and after that we will add another loop inside this Loop here we will add for and here we will add another variable name let’s add let Jal to 1 so initial value is 1 next we will run this Loop for three times so here we will add J less than equal to 3 then increase the value of J and in this we will print another message let’s add console.log and here we will add one message inner loop plus J now you can see the output in the console tab first it will execute this code and after that it will come to this for Loop now this for Loop will be executed for three times and in three times it will print inner loop one inner loop two inner loop three here we will add a space so you can see inner loop 1 2 3 now again it will increase the value of I so I will be two and this will be printed console. log I so 2 will be printed in the console tab you can see two is printed here and after this again this for Loop will be executed and it will again print from the 1 to 3 you can see 1 2 three now again the I value will be increased by one it will be three and three is printed here and again it will execute this inner loop now you can see the message inner loop 1 2 3 again the outer loop will be executed console. log I I will be 4 so this is how you can use another loop inside a loop now we will learn while loop syntax of while loop let’s add V and in this parenthesis we will add condition then in this curly Braes we will add the code that has to be repeated so this is the syntax of while loop which is very simple so in this one we have to add one condition and this code will be executed until the condition is true when the condition is false it will stop the loop now let’s understand the Y loop with one example we will print number from 0 to 10 so here let’s add console.log let’s add I and we have to declare this I so here we will add let I equal to 0 because we have to print the number from 0 to 10 now in this condition we will add I less than equal to 10 so first it will check the I value I value is zero so if the value is less than 10 then it will print the value of I now it will print the same value again and again so we have to increase the value so in the next line we will add i++ so first it will print the value then it will increase the value now you can see the output 0 1 2 up to 10 so this while loop is repeating this code until the I value is less than or equal to 10 suppose the I value is 10 so 10 less than equal to 10 is true it will print this value that is printed here now it will increase the value by 1 so I will become 11 now it will again go to this condition and 11 is less than equal to 10 that is false once it is false then it will stop this Loop next we will learn do while loop do while loop is also very simple so this is the Syntax for do while loop first it will execute the code written in this do statement and after that it will check the condition if the condition is true then it will again execute this code and when the condition is false it will stop this Loop now let’s understand it with one example let’s write one code to print a number from 1 to five using do while loop so here we will add let IAL to 1 and it will print using console tab console.log I and here it will check the condition we will add I less than equal to 5 here we have to increase the value of I so let’s add i++ now you can see the output in the console tab 1 2 3 4 5 so first the I value is 1 then it will come to this statement and it will print the value of I 1 then it will increase the value by 1 so it will become two so 2 is less than equal to 5 that is true so again it will print the value so it will be printed here then it will become three and 3 is less than equal to 5 that is also true again three will be printed here like this it will print one to five series now let’s change the value of I to 10 if I add IAL to 10 you can see the output 10 is printed here why it is printed because do Loop will execute the code first time then only it will check the condition so first it will print the value of I I isal to 10 so console. log I will be printed here 10 then it will increase the value 11 then the value of I will be checked here I less than equal to 5 which is false so it will not execute the code again but the first time it will be printed so this was for Loop while loop and do while loop apart from this there are some other Loops also like for off for in that we will study in advanced JavaScript now we will learn about break and continue statement in JavaScript the break statement is used to terminate the loop immediately let’s understand this with one example let’s take one example of for Loop for printing 1 to five number this for Loop is printing number from 1 to 5 you can see in the console tab now if I add one if condition here before printing this number here we will add if I comparison operator three when the I value is three then we will add break so you can see what will happen when it will get the break statement it will terminate the loop it will stop the loop you can see in the output only one and two is printed first time the I value will be printed then second time the I value will be printed that will be two then third time I will be three and here it will be checked if I is equal to 3 it will get this break statement and after that it will terminate the loop only IAL to 1 and two is printed here so this is how we use the break to terminate the loop or exit the loop now we will learn about the continue the continue statement is used to skip the current iteration of the loop and the control flow of the program goes to the next iteration let’s see the example here if I write continue then what will happen first the I value will be one so it will not be executed then I will be two it will not be executed then I value will be three once the I value is three it will get this continuous statement when it will get the continuous statement it will skip the remaining code of this for Loop it will directly come to the next iteration it will increase the value of I by 1 so I will be for so the four will be printed now you can see the output 1 2 4 5 3 is not printed because when the I value is three it will skip this part and the I will become four then again four will be printed so this is how break and continue statement works so this was all about the for Loop while loop do while loop break and continue in this tutorial we will learn about function in JavaScript a function is a block of code that performs the specific task functions in JavaScript are reusable block of code that can be called from anywhere in your program here is the syntax to declare a function a function can be defined using the function keyword followed by the function name the body of a function is written within this curly process now let’s create a function to print a text we will use the function keyword and the function name is GRE to print any text we will add console.log and message in the double code now we need to call this function to execute the code written in this function for calling this function we will use the function name and parenthesis so simply we will add great and this parenthesis so this estate will evoke the function or call this function after that you can see the output in the console tab hello Greatest Tag is printed here so this is the function declaration using the function keyword and the function name this is the body of function where we will add the code that will be executed within the function and this code is for calling this function or evoke the function now we will learn about parameters and arguments parameters are the variable that are declared in the function definition while the arguments are the value that are passed to the function when it is called let’s see one example of function with parameters we will create one function with the function keyword and the function name is gr and in this one we will add two parameters first name comma last name so this first name and last name are variable that are declared while declaring this function this is known as parameter now we will add the code in the body of this function here we will add console.log and we will add the text hello plus there will be first name then we will add plus and one space within double quote then again we will add plus and last name so it will print hello first name and last name in the console tab so right now we have declared the function with two parameters now we have to call this function while calling this function we have to pass two values that will be arguments so to call this function we will add the function name GRE and with this function name we have to add two values so let’s add first value Elon comma musk so we are passing two values when calling this gr function now you can see the output in the console tab here it is printing hello Elon Musk let’s add a space here now it looks good hello Elon Musk is printed in this console tab we can pass any data type as argument so let’s add another data type I will add 200 that will be number here also we will add 100 now see the output you can see it is printing hello to 200 and 100 so we can pass any data type as argument while calling the function we can pass less or more arguments while calling a function if we pass less arguments then the rest of the parameters will be undefined if you pass more arguments then additional arguments will be ignored let’s see one example if I just pass GRE alone and comment this first call here you can see the output it is saying hello Elon and undefined because we are passing only one argument and here we have two parameters first name and last name so this alone will be stored in this first name so it will print hello and the first name is Elon and in the second parameter which is last name we are not passing any argument so it will be un defined that’s why it is printing hello Elon undefined the last name is undefined so we can pass less argument now let’s see another example if you pass more arguments here if I add Alon comma musk comma Mr now see the output here it is printing hello Elon Musk so the first argument will be stored in the first parameter which is first name second argument will be stored in the second parameter which is last name and this third parameter will be ignored because we have only two parameters here so it will only print this hello and the first name Elon and last name musk the third argument will be ignored now let’s learn about default parameters default parameters in JavaScript are parameters that have a default value this means that if the argument is not passed to the function the default value will be used let’s see one example of default parameters here we will create one function write the function name sum and in this sum function we will add two parameters which is X and Y now in this body of function we will add console.log and it will log the X + Y it will add the X and Y value and it will display in the console tab now to call this function we will add function name and parenthesis but here you can see we have two parameters X and Y so when calling this function we have to pass two arguments also so let’s add two values 10A 15 15 so this 10 will be stored in x 15 will be stored in y and this console. log will display 10 + 15 that will be 25 you can see in the console tab it is printing 25 10 + 15 now you can see if I remove 15 from here and we are just passing 10 10 will be stored in X and Y will be undefined and here we are printing x + y so let’s see what will be output here it is printing n n why it is because here we are adding 10 plus undefined x + y will be 10 plus undefined that’s why it is printing NN that means not a number we cannot add the undefined n number so it is printing an N here we are passing only one parameter and you want this function to work for that we can add Y is equal to 0 suppose we have added y value zero then you can see the output in the console tab it is printing 10 let’s see if I add 50 we are passing 50 in X and Y default value is zero so x + y that means 50 + 0 that will be 50 you can see the output 50 is printed so 0 is the default value of this y parameter and here if we pass two numbers 50 + 30 then it will use 30 in this y you can see the output 50 + 30 80 is printed here because we are passing two arguments 50 50 will be stored in x 30 will be stored in y so this was the default parameters in Javas script now we will learn about function return the return statement can be used to return the value when the function is called the return statement donates that the function has ended any code after return is not executed let’s see one example if I create one function and function name is ADD and in this one we will add two parameters A and B now we can add return A+ B so this function will return the addition of A and B now to call this function we will add the function name add and in this one we have to add two values as argument so we will add 10 and 20 so this will call this function and this function will return the addition of 10 + 20 so we can store this result so here let’s add one variable with the let keyword let result equal to add function so the return of this add function will be assigned in this result variable now we can print this result we will add console do log the sum is result now you can see the output in the console tab it is displaying the sum is 30 if we add 10 and 40 you can see the output in console tab the sum is 50 so this return statement will return the value if we add any code after this return a statement like a multip by B this code will not be executed return statement denotes that the function has ended any code after this return statement will not be executed in JavaScript a function can return another function Also let’s see one example here if we create one function with the function name fn1 so this is the first function here I’m adding one parameter X in this function one we will create another function let’s create function fn2 and this will accept one parameter y now in this second function we will add return X multiply y so so the function two will return the multiplication of X and Y next after this function two we will add return FN 2 so when we will call this function one it will execute this function two also and then it will return this function two so function one is returning another function that is function two to call this function we will add fn1 parenthesis and we will pass one argument so let’s add three so here we are calling function one and passing one argument let’s store its value in one variable we will add let result is equal to function one and try to print this result console DOT log result so you can see the output in the console tab here it is displaying one function so you can see when I am calling this function one it is returning the function two and that function two is stored in this result now the function two is stored in this result so we can simply call this result like this result for the second function also we need one argument so we will add two and let’s print this one we will add console.log and print this result two you can see the output it is displaying six because in function one I passing three that will be X and function two I’m passing two that will be y and x * by y will be 3 * 2 is = to 6 let’s understand this example again again here we have the function one this function one has return a statement and this return a statement is actually returning the function fn2 which is declared here so the function is returning another function now we can store the return value in any variable so here we have called and stored the return of the function one in result with this console log we can see what is stored in this result so in this result function two is a stored so to call this function two we will add result and we will pass one argument so this was another example of return a statement in JavaScript function so this was all about function in this video we will learn callbacks in JavaScript a callback is a function passed as an argument to another function a callback function can run after another function has finished let’s understand the callbacks with one example I’m creating one function and the function name is display and this display function will display the message in the console tab so here we will add console.log and let’s add result and this result is parameter so here we have declared One display function that will only display the result in the console tab we are not performing any calculation in this function now we will create another function let’s add the function keyword and the function name is add this add function will have three parameter let’s add num one then num two and the third one will be one function let’s add my call back in this add function we will add let sum is equal to num one plus num two so this sum variable will store the value of num 1 + num 2 next we will add this call back and and in this call back we will add Su now we will call this add function so just add the function name which is ADD and parenthesis and this function has three parameters so we will pass three argument so first one will be one number that we want to add again we will add another number 1020 and in the next parameter we will pass one function so we have already created this display function so we will pass this display function in this add function when you pass a function as an argument remember do not use the parenthesis we will simply add the function name there is no parenthesis required so let’s understand this code here we have declared one function that will just display one message in the console then we have another function that have three parameters s it will add the two number and store the value in some variable now to print this sum in console we need to call this display function so when calling this add function we are passing the two numbers 10 and 20 that will be added and we are passing this display function as argument and this function will be here in my callback this display function also accept one argument so here I adding my callback and the value which is sum so this my callback will call this display function so let’s see the output in the console tab you can see it is printing 30 we are calling add function and in this add function we have not added console.log the console.log is added in the another function called display and we are passing this display function as argument in the add function function let’s change the value if I write 20 + 30 and now again check the output you can see it is displaying 50 that is 20 + 30 so when we are passing one function as an argument to another function that is known as callback function in JavaScript now let’s learn about Anonymous functions Anonymous function in JavaScript are functions that are not declared with a name here is the Syntax for anonymous function just write the function keyword and parenthesis and add your code within the curly Braes we can add parameters also in Anonymous function so this is the syntax to create Anonymous function we are not adding any function name we are just adding function keyword and parenthesis and curly Braes now let’s see one example of anonymous function here we will create one function with the function keyword this function will have two parameters X and Y now this function will return the value of x + y here I’m creating one function without any name so it will not be stored on our memory so to access this function we can store this function in any variable so let’s add let keyword to create one variable and the variable name is sum sum is equal to function here we have declared one function and assigned this function in a variable called sum this is known as function expression to call this function we can use the sum variable here we will add sum and this function accept two argument so we will add the two two value in this parenthesis 10 and 15 now to print this value in the console tab we will add console.log and write this sum and two parameters now you can see the output in the console tab it is printing 25 let’s change the value here we will add 10 and 30 now again you can see the output 40 so let’s understand this example again here I’m creating one function without any name and assigning this function in variable called sum to access this function or call this function we can use this sum variable and this function accept two argument so with this sum we are passing two argument 10 and 30 this 10 will be stored in X and 30 will be stored in y so it will return the X x + y value that will be 40 that will be printed in our console tab now let’s see another example of anonymous functions here we will create one function with the function keyword and write the parenthesis and within the curly braces we will add console.log and one message welcome to greatest de here we have declared one function without any name but how to execute the code written in this function as you know to call any function we write the function name and parenthesis so this will call or execute the function we will add the same thing with this Anonymous function also we will trap this Anonymous function in a parenthesis like this we have wrapped it in this bracket and now we will add this parenthesis that will execute this function now you can see in the console tab it is printing welcome to greatest stack the function is executed immediately when the script runs and it logs the message welcome to greatest T to the console now let’s see another example of anonymous function here we will add set timeout function and time set time out is built-in method in JavaScript that accept one function and time in milliseconds so here let’s add 2,000 milliseconds and here we will create one function so here we can add one Anonymous function let’s add function keyword then parenthesis and curly Braes and in this curly Braes we can add the code that will be be executed within this function so let’s add console.log hello creest stag here I’m adding an anonymous function that display the message hello greatest tack in console and here I’m adding 2,000 milliseconds so it will execute this function after 2,000 milliseconds that is 2 seconds let’s see the output in the console tab you can see it is blank but after 2 second it display the message hello greater stack now increase the time if I add 5,000 milliseconds that will be 5 seconds and run the code again you can see the console is blank and after 5 Seconds it will print hello greatest stag you can see it is printing hello great stack in the console we can write like this so it will be clear now you can see we have declared one function without any name so this is another example of anonymous functions now we will learn about recursive functions in JavaScript a recursive function in JavaScript is a function that calls itself let’s create one function and the function name is my function and within this function we can write the code and after that we will call the same function here we will add my function and parenthesis so in this one you can see we have declared one function with the name my function and within this function we are calling the same function my function parenthesis now to evoke this function we will add it here outside of this function here my function is recursive function because it is calling itself inside the function a de cursive function must have a condition to stop calling itself otherwise the function will be calling itself infinitely to prevent infinite recursion we can use if else statement or any condition statement so here if I add if if condition and within this condition we will call this recursive function and else stop calling recursion so this is just one example how we can create one recursive function and call the recursive function and how to prevent the recursive function for infinite recursion we can add the if Els condition or any other conditional statements of JavaScript now let’s see one example I want to print numbers in descending order so here we will create one function and let’s add the function name countdown so this countown function will accept one number so here we will add num to call this function we will add the function name countdown and we will pass any number let’s add 10 so this will call this countdown function and pass the number 10 in this num now to print this number we will add console.log num so this will will be printed in the console tab now I want to print 10 9 8 7 like this so we have to decrease the number so after printing the number in console we will decrease its value by one so simply we can add num minus minus so it will decrease the value by 1 if the number is 10 it will become 9 so after decreasing the number again we have to print it so to print the number again we can call this function again let’s add countdown num so this countdown num will again a start from here and it will again print this but this countdown will be running infinitely so to prevent the infinite recursion here we will add if num is greater or equal to Z so when the number is greater or equal to Z then only it will call the function again now you can see the output it is printing 10 987 65 4 3 2 1 0 it is printing the number from 10 to 0 Let’s understand this code again here we have declared one function and in this function it is printing the number and it will decrease the number by one and after that it will check if the number is greater or equal to zero then it will call this function again so this countdown function is calling itself this is known as recursive function so this is all about recursive function callback function and Anonymous functions in JavaScript object in JavaScript JavaScript object is a non-primitive data type that allows you to store multiple collections of data let’s see the syntax to declared an object we will use const keyword then object name so this is an object in this we can add the data in key value paired we will add key 1 value one we will add the comma to separate the data we will add another key key2 and value two we can use the let keyword also to declare one object but it is good practice to use the const keyword let’s see one example if I write the object name person and in this person object we will add the name of the person so first we will add first name and in the first name we will add Elon add one comma then we will add the last name the value is musk and we will add one more information age so here we have created one object with the object name person in this object we have three properties now let’s check the type of this person we will add console.log type of person now you can see in the console tab it is printing object so the type of the person is an object now if we want to print the complete object we will add console.log person in this console you can see it is printing the object that we have created it is printing age 35 first name and last name any object can store two things which is properties and methods in this person object data is stored in key value pairs first name is the key Elon is the value age is key 35 is value these key value pairs are called properties key is always stored as a string here if I write this name in double quote still it will be correct you can see there is no error in the output you can see it is displaying simply first name so by default it will store it as a string in the value we can add any data type we can add a string number arrays Boolean function and we can store an object also when we declare a function as has a value in key value pair then it is known as methods now let’s learn how to access the properties of an object we can access the values of a property by using its key name so the first way of accessing the property is using dot notation we can write object name dot key so it will give the value stored in the key value pair of the object let’s access the value stored in this person object here we have the console.log person and if you want to access the name stored in the first name so we will add person. first name and we will check the console you can see it is printing Elon so we can access the property using dot notation let’s add the age here if you want to access the age object name and key so it is displaying the value in the console you can see it is printing 35 the second way of accessing the properties of an object is using bracket notation so in this example here we will remove this Dot and add a square bracket and we will add this text in double quote as a string now you can see the console tab it is printing 35 so we we can access the property by using braet notation and in this braet we have to add the key name with double quote or single quote let’s add the first name so you can see the first name in the console Alon keys in object are stored as a string so we can add this key in double code like this and we can add a space Also here we are adding first space name like this now if you want to access the value stored in the first name we will add console.log and object name and if you use dot here DOT first name it will give an error we cannot access this property by using do notation in this case we have to use the bracket notation only and in this bracket notation will add the string in double code or single code then you can see it will display the name it is displaying the name alone in the console tab so the bracket notation is also useful to access the properties of an object now let’s see how to update the properties of an object so we have this object person and in this one if I want to update the first name so the first name is Elon and I want to change it so we can add the object name that is person and write the key that will be first name and we can assign a new value or a new data so here we will add Mr Elon Mr Elon so this line will update the first name in the object called person now you can see the output it is displaying Mr Elon because here we are printing person. first name here we have declared one object with the person and here the first name is Elon and in this line we are updating the first name with the new name which is Mr Elon and Mr Elon is printed using this console.log next we will learn how to add a new properties in the object so here we have the object with three properties and now I want to add one more property so for that we will add the object name so the object name is person then we will add the key so key is company so this line will add a new property in the person object now if you want to display the object just add console.log and object name now you can see the console tab it is displaying the object with four properties age company first name last name so we have added one new property company and it is displaying in this object next we will learn how to delete one property from the object so let’s use the same example and here we will add the delete keyword delete then write the object name and key so let’s delete the age that’s it we are adding delete keyword then object name and key now if you want to check let’s see the console tab here you can see it is displaying only three property which is company first name and last name age property is missing because we have deleted age property from this object this is how you can access the properties of an object you can update the property you can delete the property and you can add a new property as I have already discussed in value we can store any type of data so we can store one object also that is nested object so let’s take the same example in this one we will add one more property here we will add address and this address will contain another object that’s it we will add the data in key value pair in this example you can see we have an object called person and in this object we have three properties then we have added one more properties and this property is having one another object that is known as nested object and in this object also we have added the data in key value pairs you can see Street city state country and zip code now to access the data stored in the nested object we can use the same dot notation let’s add console.log write the first object name person and in this object we have the address we will add address and from the address we can access CT now you can see the console tab it is printing Austin now if you want to access ZIP code right person address ZIP code now you can see it is displaying zip code in this console so so this is how you can access the properties of the nested object now we will learn how to check if a property exist in an object to check if a property exist in an object you can use the in operator we can write property name in object name here we have the person object so let’s see one example to check if the property exist in this person we will add age in person it returns true if the property exist in the object so let’s print this in console tab we will add console.log we have to add this age in quotes now you can see in the console it is printing true because age exist in this person now if you want to check first name is exist or not so here we will add first name in person so it will display true because we have the first name in the person object now if you will add country country in person now you can see it is displaying false because in this person object we don’t have any property with the key name country now if you want to display all properties and values of an object without knowing the property name then you can use foreign Loop foreign Loop allows you to access each property and value of an object without knowing the specific name of the property for example we will add for and in this one we will add one variable so let’s declare one variable with the let keyw word and we’ll add the variable name prop that is properties and prop in object name person now we can print this prop so let’s add console.log prop in the console you can see it is printing first name last name and age because in this person object we have three keys first name last name and age so using the for in Loop you can access all properties of an object now if you want to access the values stored in this key we can use the bracket notation as we have already discussed to access the value we use the object name like person and bracket notation and in this one we will add the key so let’s add H so it will display the value so here we will add the same thing let’s add person Square bracket and prop so you can see the output in console tab it is displaying the values only the values are Elon Musk and 35 now if you want to display both key and value so let’s add prop plus and here we will add colum now you can see the output in the console tab it is displaying both key and values stored in this person first name Elon last name musk is 35 so using the for in Loop you can access all the properties of an object there are multiple ways to create an object in JavaScript this was the example to create an object with object literal let’s see another example where we will create an object with the new keyword for that we will add const [Music] person new object so this is the another way to create an object if you want to add some data in this object we can add the object name and key and assign one value so it will add this data in this person object let’s duplicate it and we will add another data last name age now if you want to display this person object just add console.log person you can see in the console tab it is displaying one object with the data Age first name last name so you can see we have created one object with the new keyword and then we have added these data in this person object we can add these data while creating an object Also let’s see I will remove these things remove it from here and in this object just add curly Braes and within this curly Braes write the data in key value pair and here it will be comma now it will create the same thing you can see the output it is same still it is displaying the object with three properties first name last name and AG so this was all about JavaScript object and their properties in this video we will learn about JavaScript object methods JavaScript method is an object property that contains a function definition let’s create one object with the const keyword here we will add the object name person and in this object we will add two properties first name and last name let me create one more property here and I will add the property name GD you can call it property name or key in this gr property we will declare one function to declare a function we use function keyword then name of the function so let me write the function name g and in this function we will print one message using the console log hello world so in this one you can see we have the third property with the function definition this is called as object methods so this is the method of the person object now to call this method we will add the object name that is person and then write the method name GRE and write the parenthesis also now you can see the console tab it will display the output hello world so in the person object we have created one property with the function definition that is known as method and we are calling this method using the object name do method method name parenthesis here we have declared one regular function we can add the anonymous function Also let’s remove this name and we can write like this here we have used function expression to define a function and assign it to the GD property of the person object and still it will display the same message in the console tab hello world we can declare a function outside of the object and assign it to an object as a method here is one example let me remove this function from here and here we have one object with two properties now we will declare one function function name is grd and console.log hello world next we will assign this function inside this person object so here we will add person dot any key name so we will add the key name greeting is equal to greet let me add T it will be correct so in this line I’m assigning this greet in this person greeting now to display the output we will add the person dot greeting parenthesis now you can see the output it is displaying hello world so let’s understand this example again here we have created one object and the object name is person where we have only two properties now we have declared one function and assigning this greet function in this person object the property name or key name is greeting we are calling this method using person. greeting parenthesis now if you want to display this person object simply we will add console.log person now in the console tab you can see it will display the object and in this object you can see we have the first name then this greeting property which is the method in this greeting we have the function definition so this is how you can assign one function inside an object as a method es6 provides us one more way to declare a method for an object let me remove it and in this object we can simply add gr and curly Braes and write the code so this is one more way to declare one function in inside the object as a method we can access this method using the person dot GRE now you can see it will display the message hello world in the console tab now we will learn about JavaScript this keyword to access the other properties of an object within a method of the same object we can use this ke key word let’s see the same example one object with the name person and we have two properties first name and last name now to access the first name we use to write object name do the key name or first name so this is how you can access the property of an object but when we need to access the first name within the method so in this one let’s create one method here we will add one method G one Anonymous function and message console.log hello now in this method if I want to display the first name so here we will add plus this DOT first name so when we need to access the property of an object outside of the object we use the object name and key so we are adding person do first name but here we are accessing the first name inside this method and this method is in this person object so this keyword refers to the same object which is person so we don’t need to write the object name we can simply write this keyword do first name so this will print hello and the first name now to call this method we will add the object name Person dot gr let’s see the output in the console tab it is printing hello Elon let me add a space here now you can see it is printing hello Elon in the console tab so we can use this keyword to access the properties of the same object within the method so when we use this keyword within a method it refers to the same object now let’s define a method that Returns the full name of the person object by containing its first name and last name so remove it and let’s remove this method also and here we will add another method get full name one function and in this function we will add return this function will return the first name and last name to access the property we will add this DOT first name then we will add space so let’s add double quote then Plus this do last name it will access the last name so in this method you can see it is returning this do first name so it will return this value Elon and here this do last name it will return this value musk now to call this method we will add person dot get full name this method is returning some value so we can print it using console.log let’s add console.log person. get full name now you can see the output in the console tab it is printing Elon Musk so it is returning the full name by containing first name and last name let’s understand this example again here we have an object with the name Person where we have two properties first name and last name and one method this method Returns the first name and last name of the person now we are calling this method so it will display the full name which is Elon Musk we can use this keyword outside of the method also but it will refer to the other object let’s remove all these things and here simply add console.log this so here you can see the output it is display Ling window object so if we use this keyword alone or inside a function then it will refer to the global object that is window object or when we use this keyword in the event then it will refer to the element that receive the event this keyword is not a variable so we cannot change the value of this so this is all about JavaScript method and this keyword in this tutorial you will learn about JavaScript Constructor function and and how to use the new keyword to create an object in JavaScript Constructor function is used to create objects let me create an object we will add the const keyword then object name person and in this object we will add properties so the first property is first name and the second property last name this example create a person object with two properties first name and last name but this syntax is used when you have to create single object in programming you often need to create many similar objects like person to do that you can use a Constructor function let me create one Constructor function for that we will add function keyword and then the name of the function person then parenthesis and in this curly braces we will add properties so let’s add this DOT first name and value Elon again this Dot last name and value Constructor function is similar as a regular function but it is good practice to capitalize the first letter of the Constructor function so you can see here I have added capital P in this person a Constructor function should be called only with the new operator we can use the new operator to create an object from a Constructor function till now we have not created any object we have just created one Constructor function to create a new object we use the new operator so let’s see how to create an object using this Constructor function let’s add the con keyword then we can write any name of the object so let’s add the person one this is the object name here let’s add new operator and write the function name person so this line will create one new object that is person one using the Constructor function we can create multiple objects so let’s add one more line here we will add person two so here we are creating another object with the name Person two with this person Constructor function now if you want to see what is stored in the person one console.log person one and see the output in the console tab so you can see the person one is one object with the two properties first name and last name now let’s see the second object also so we will add console.log person two so we are printing both person one and person two in the console so let’s see the output here you can see both output is same when a new object is created using the Constructor function this keyword will refer to the newly created object so in this example here we are creating one new object person one with the new operator and this Constructor function so this keyword will refer to the newly created object which is person one and this first name and last name will be added in this person one as a property so in this example person one and person two object have same property value but we can create multiple object of the same type with different property value also using Constructor function parameters so as you know the parameters in the function here we will add parameters in this Constructor function also so in this function let’s add first last in this Constructor function we are adding two parameters first and last and this first will be stored in this first name this last will be stored in this last name now when calling this Constructor function we have to pass two arguments here we are creating object by calling this Constructor function so to call this Constructor function we have to pass two arguments so let’s pass two value Alon musk for creating this person to object we will pass another argument let’s add another name billgates so in this example here we have one Constructor function with two parameters so to call this Constructor function we have to pass two arguments so this Elon will be here in this first and this first will be stored as a value in this first name property this mask will go here in the last and this last will be stored as the value in this last name property so when we are creating person one it will create one object with the property first name and last name and the value is Elon Musk and when we’ll create the person two object it will also create the object but the value will be different that will be buil gets now let’s see the person one and person two object in the console tab so you can see the output here in this console so in the first object you can see first name Elon last name musk and in the second object we have first name will last name gets so using the Constructor function we can create multiple object of the same type now let’s see how to add properties and methods in an objects so first let’s add one property in person one object so removing this console and here I will add person one to add a new property in this person one just add Dot and the property name age and write the value let’s add 52 now we can print this in the console let’s add console.log person one you can see in the console tab here we have three properties in this person one object which is first name last name and age and the age value is 52 that we have added here person 1. AG is equal to 52 now if I simply want to print the age here we will add console.log person one do age so you can see the console tab it is only printing the value stored in this age property that is 52 now if I try to access the age from the person two let’s see what will happen here I’m adding person to. age and see the output in the console tab it is displaying undefined because we have added this age property only in the person one object we have not added in the person two object that’s why person 2.as will display undefined now let’s see how to add one method in the person two so let’s scroll and here we will add person two dot method name we will add gr and declare one function as we have already studied method is a function decaration inside the object property so here in this person two object we are adding one method with the name gr and declaring one function and let’s say this function will log one message hello great stack we have to write it in codes so we have added one method in the person two object now let’s access this method here we will add person 2 dot GD from person 2 we are calling this GRE method now let’s see the output in the console tab it is printing hello great stack in the console tab so this is the example to add a method in the object now let me remove this and you can see in this Constructor function I have added added only two properties now let’s see how to add one method in the Constructor function so here let’s add one comma and here we will add this dot name of the method get full name and here we will declare one function so this method will return some value so return this DOT first name then we will return the last name Also let’s add one space plus and this do last name so here I’m adding get full name and this method will return first name plus last name that will return the full name name so we have just created The Constructor function now we have to create object also so let me add the same example again I will add person one and person two so we have created person one and person two object using the new operator and Constructor function now let’s see how to access the get full name method so to access the full name just we will add person 1 dot get full name the method name now this method is returning some value so we can print it using log console.log person 1.g full name now you can see the output in the console tab it is printing Elon Musk now let’s access the person two full name and you can see the output billgates the problem with this Constructor function is is that when we create new object using this Constructor function the same method will be created in all the objects created using this Constructor function which is not memory efficient to resolve this we can use the Prototype of the object so that all objects created from this person Constructor function will share this same method so this is all about JavaScript Constructor function in this tutorial you will learn about JavaScript object prototype in JavaScript every function and object has its own property called prototype let’s create one object const person and this person will have name Elon so this is one simple object with only one property that is name but this person object has one more property called prototype let’s see this person object in the console we will add console.log person and you can see in the console tab here it is displaying one object name Elon right but if I expand it you can see the property name Elon but here we have one more property called prototype and the Prototype is also an object a prototype itself is also another object so the Prototype has its own prototype let’s expand this prototype again and expand any of this you can see here again we have the Prototype let’s expand another one here also we have prototype so the Prototype has its own prototype this create a prototype chain now let’s learn prototype inheritance we can use the prototype to add properties and methods to a Constructor function and objects inherit the properties and methods from a prototype let’s see the previous example of Constructor function so this is one Constructor function with two parameters and the two properties first name and last name now previously we were adding like person one that is one object and in this object we can add new property like this person. AG so it will add a new property in the person one object but here we want to add one property in the Constructor function like we have the person Constructor function so we cannot add one property like this in the Constructor function and we cannot add a method in the Constructor function like this after Declaration of the Constructor function we cannot add the extra Properties or method like this to add the another property or method in the Constructor function after declaring we can use the Prototype here we have only two property in this Constructor function so let’s add one more property so to add one property in this Constructor function we will add the function name person then prototype like this and in this prototype we will add one new property name so let’s add the property name gender and the value is male so using this we can add one new property in the person Constructor function now let me create object also so I will use the const keyword and object name so the object name is person one and create an object using new operator and the function name and pass two values and we will create one more object so duplicate this it will be person two and different value so we have two object person one and person two now let’s see whether the newly added property is available in the person one and person two or not so let’s add console.log person one object and and see the output in the console tab here it is displaying first name Elon last name musk here we have only two properties but we have added the another one gender which is not available here but if I expand it and come to the Prototype here we have the Prototype and open this prototype here you can see our newly added property gender male in this prototype so you can see how you can add a new property in the protot prototype and this prototype property will be inherited by all the object now let’s see the output for the person one. GN Zender and see the output it is displaying male because the object is inheriting the properties of the Prototype now let’s see the output when we access the person two for the second person object let’s access the Ender and you can see it is displaying name male again here we have added gender property in the person Constructor function using prototype and this person one and person two objects inherit the gender property from The Constructor function prototype gender property is not available in the person one and person two object you can see in the console but still we can access it because it is added in the Prototype which is here now let’s see how to add one method in the Constructor function so here we have added one gender property so instead of this we will add one method let’s add method with the name get full name and this method will be a function definition so in this function we will return the full name so write return this DOT first name and space this dot last name so in this person Constructor function we are adding one method using the Prototype and this method name is get full name this method will return the first name and last name of the person so let’s see the output of the person one in the console tab you can see it is displaying first name and last name in this console but if I expand it here you can see we have the Prototype and if I expand this prototype you can see in the person one prototype it is displaying get full name method you can see the get full name method is here so this get full name method is not added in this person one or person two this person one and person two object is inheriting this method from the Prototype of the Constructor function so we can access it like this get full name person 1.g full name let’s see the output it is printing Elon Musk now we can access this get full name from the person two also and see the output it is displaying billgates let’s understand this example again here we have created one Constructor function with only two properties after Declaration of the Constructor function we cannot directly add new property or method in this function but to add the new property or method we will use the Prototype so we are adding person. prototype and the method name method is a function declaration so we are adding function and this function will return the first name and last name now here we are creating two objects with the Constructor function person one and person two now this person one and person two does not have the get full name but still we can access the get full name method from person one and person two because it is inheriting the Prototype of the Constructor function so we can access person 2.get full name and we can also access person 1.g full name now let’s see what will happen if I change the Prototype value so let’s create one Constructor function here we will add one property Elon mask and in this one we will add one new property using prototype so we will add person do prototype and the new property name age is equal to 25 so we have added one new property in the Prototype that is age is equal to 25 now we will create one object so to create an object we will use the const keyword and the object name it is person one and new then Constructor function so this will create one new object that is person one so here we have created one new object called person one after creating this object let’s change the value of this property so in the next line we will add person do prototype is equal to age 52 like this earlier we have added age 25 and here we are changing the Prototype property age 52 so after changing again we are creating one new object const person two new and Constructor function so before changing the property we have created one person one object and after changing the Prototype we have created person two object now let’s see the output in the console tab so we will add log person one and person two and you can see it in the console tab it is displaying name Elon Musk in both object but if I try to access age and age in the second object so you can see the output for the person one it is displaying is 25 and for person two it is displaying is 52 because if a prototype value is changed then all the new objects will have the change property value and all the previously created objects will have the previous value so in this example you can see here we have the property value 25 and created one object person one in this person one object A’s value will be 25 and before creating person two we have changed the property so this person two will have the updated property value that will be 52 that’s why it is printing 25 for the person one age and 52 for the person 2 Age so this this was all about JavaScript prototype in this tutorial you will learn about object destructuring object D structuring in JavaScript is a feature that allows you to extract the properties of an object into variables this can be useful for assigning the properties of an object to variables in single statement let’s understand it with one example we will add one object with the name person here we have created one person object with two properties first name and last name to aore these properties value in a variable we used to write person DOT first name this is for accessing the first name of this person and to it in variable we used to write let and one variable name like f name is equal to person. first name like this if I want to store the last name we will add another variable name L name Person dot last name so this is the previous syntax to store the object properties value in a variable but es6 introduces the object D structuring syntax that provides an alternative way to assign properties to an object variables here is the Syntax for object D structuring we will add L and in this curly Braes we will add property name and value another property name and value and here we will add the object name that’s it so let’s assign the properties of this person object in variables using the object D structuring here we will add person and here we will add the property name so the property name is first name and this first name will be stored in the variable called f name now add one comma and write the another property name and for this property name again we need one variable so the variable name is last name so this is the simple syntax of DS structuring we can write the property name and value to store the object properties value in variables now if I check the value stored in this F name variable or L name variable we will just add log F name you can see it is displaying alone if I I add L name here will be capital n and you can see the output musk we can further simplify this syntax suppose you want to add the variable name same as the object’s property name like object property name is first name and last name and our variable name is also first name and last name then here we don’t have to write the variable name just write first name and last name and then object now to print this we will add console.log first name it is printed here in this console now let’s add last name you can see the last name in this console so this is the simple syntax of object destructuring here in this object we have only two properties but what will happen if I add one more property in this object destructuring syntax let’s add one age that is not available in this person object then what will happen let’s see the output if I add console.log age it is printing undefined because this age property is not available in this person so when you assign a property that does not exist in an object to a variable using the object D structuring the variable is set to undefined now in this object D structuring we can add the default values also suppose here we don’t have the age value so we can add like this age is equal to 18 so this is the default value of the age variable if the property is available in this object it will display the actual value and if it is not available it will display this default value 18 so you can see the output it is displaying 18 because the default value for the age is 18 now suppose this age is available here in this object we are adding age 52 now what will be the output you can see the output it is displaying 52 because it will ignore the default value here we already have age declared in the person object so this age variable will store the actual value of the property which is 52 so this is all about object D structuring now let’s learn about object literal syntax extensions in es6 to create one object we used to write like this const person and first name and last name so this is the object literal syntax to create an object with the key value pairs but here if I typ one variable let first name equal to Elon and last name m here we have two variables first name last name so we can simply add first name comma last name we don’t have to write the key values in this object we will simply add the variable name and this person will store this information as key value pair now if you try to print this person let’s add console.log person you can see it is displaying first name Elon last name musk so we are just adding the variable name in this person object and this person will store the variable name and value also as a key value pair so this is all about objects in JavaScript in this video we will learn about JavaScript class classes are one of the feature introduced in es6 version of JavaScript JavaScript class is a template for creating objects to create a class we use class keyword then we write the name of the class within the class we create one Constructor method you should always add a method with the name Constructor within the class the first letter of the class name should be in capital letter JavaScript class is similar to the JavaScript Constructor function to create a Constructor function in JavaScript we use to write function and name of the function I’m adding person in this function we will add here we will add the code to initialize the property value of an object after creating the Constructor function we create object we can write any object name person one new keyword and Constructor function and pass two values here so this is for creating one new object to display the object created using this Constructor function we used to write console.log person one you can see the output in this console tab it is displaying one object with the property name and age now we can create the object using class also so now let’s create the class to create a class we use to write class keyword then class name I’m adding the class name person and in this class name we have to add one Constructor method and this Constructor method is used to initialize the value of the object so let me add this here here we will add two parameters so this is one class with the name person and this line will create one object with this class now let’s duplicate it we’ll create another object with the name Person two and we will pass another value so we have two objects person one and person two now if you want to display the object in console tab you can write console.log and you can see the output it is displaying here one object with two properties name and age and the name is Elon Musk and age is 52 now let’s print second object which is person two you can see the output in the console tab it is displaying another object object with the name billgates and age 67 this Constructor method initialize the property of the object JavaScript automatically calls the Constructor method when you create an object using the class now let’s learn about JavaScript class methods we can add any number of methods in JavaScript class so let me remove this second person and in this class after this Constructor we can add any method so let’s add one method with the name greet and this greet method will return text hello this do name it will return hello and name of the person now I want to display this person one object so here I will add console.log person one and in the console tab you can see one object with two properties name Elon mask is 52 now let’s expand it and here you can see prototype and in this prototype you can see this GRE method in this prototype of the object so we can call this GRE method from this person one object so in this console.log I will add G and you can see the output it is displaying hello Elon Musk because we are calling the Greet method from the object and this greet method is returning the text hello and the name so that’s why it is displaying hello Elon Musk we can add any number of methods so let’s add another method here here I will add a new method change name this change name method will update the name of the person in the object so here we will add new name and then this do name is equal to new name so in this method we are adding one parameter so when we will call this method we have to pass one argument let me remove this console.log and here I will call the change name method on person one object so just add person one dot change name and we have to pass one argument so let’s add a new name I will add my name here AAS now we can print the object let’s add console.log person one you can see one object name aenas age 52 now if you want to print the name only here we will add person 1. name it is printing the name in the console tab so in the JavaScript class you can add any number of method now let’s learn about gets and Setters in JavaScript Getters and Setters are a special methods in JavaScript that allow you to control how properties are accessed and modified they are defined using G and set keyword now let’s understand the getter method a getter is a method that is called when a property is accessed it can be used to do things like validate the value of property or convert it into different format so let’s see this example here we have one class with only one method great and this method is returning hello and the name here we have created one object using this class this code will call the Greet method from the person one object and display the return value in the console so while calling this great method we used to write this parenthesis but when we clear it as a geted method so here we will add get space and the method name that’s it just add the get keyword and after that here you don’t need to write the parenthesis simply add gr person one. greet and save the changes you can see the output it is still displaying the message hello Elon Musk so we have just added this get keyword in front of this method name and we can call it directly without adding parenthesis now let’s understand the seter method with one example here we will change the method I will add change name new name this do name is equal to new name to call this method we need to write person one dot change name and pass one argument like this but here we will add set keyword in front of this method just add set then we don’t need to write this parenthesis and pass the argument simply we will add person one do Setter method name and assign one value using assignment operator like this and see the output here I’m displaying the person one object it is displaying one object and name is AAS age 52 like this so we add this set keyword to Define one Setter method we can call this method on object and assign one value with assignment operator a Setter is a method that is called when a property is modified it can be used to do things like update the value of the property or perform some other action we can use the same method as getter and Setter let’s see one example let me change the method name it will be person name name and here I’m adding set now we will add get this will be getter method and I’m adding the method name same as the setter method here also person name and this will return return this dot name so you can see here we have declared one class in this class we have one Setter method and one getter method and both method name is same person name and person name now to call this getter method we’ll simply add console.log person one do person name so it will return the name of the person you can see the output it is displaying the name now we can update the name using this Setter method so let’s add person one dot person name and just assign one value after that again we will call this get method that will displ play the name so you can see the output first it is displaying the name Elon and after that it is displaying the name ainash so we have the same method name as getter and Setter to call the getter method we are simply adding the object name and Method name and to call this Setter method we are adding object name and Method name and assigning one value that’s it when we assign any value it will call the setter method and update the properties value let’s learn about JavaScript class expression a class expression provides you an alternative way to define a new class it is similar to a function expression but it uses the class keyword instead of the function keyword class expression can be named or unnamed if they are named the name can be used to refer the class later if they are unnamed they can only be referred by the variable that they are assigned to so let’s define one class expression we will add the class keyword in this class we will declare one Constructor method this Constructor method will initialize the object property property name is name here we will add name and in this class we will add one method method name is get name it will return the name now we will assign this class in a variable let’s add let keyword person is equal to class A Class expression does not require an identifier after the class keyword you can use a class expression in a variable declaration now we can create an object so let’s add cost person one new person we can refer this class with this variable and here we will add one [Applause] argument now we can display our object in the console tab so let’s add console.log person one you can see the output in this console here we have one object with the name Elon Musk so this was the class expression in JavaScript in this video we will learn about JavaScript class inheritance JavaScript class inheritance allows you to create a new class on the basis of already existing class using class inheritance a class can inherit all the methods and properties of another class inheritance is a useful feature that allows the code reusability to create a class inheritance we use the extend keyword so let’s create one class write the class name Person add one Constructor method and add one method GRE console.log hello and name here I have created one class now I will create another class that will inherit all the methods of the person class so here we will create another class and the class name is a student then write the extends it will extend person so we are creating another class with the name a student this a student class will inherit all the method and properties from this person class in this new class we have not added anything but let’s create one object here we will add con student one this is the object name is equal to new student and we have to pass one value Peter so we have created one object with the name a student one and we are passing one value in this student but this student don’t have the Constructor and here we have added extends keyword so it will inherit all the method of this person class and it will pass this page Peter here in this Constructor and the name will become Peter and we can also call this greet method so let’s try to call this greet method we’ll add a student one do greet you can see the output it is displaying hello Peter so this property name is available in this person class this method is also available in this person class but we are creating the object object with the a student class and calling this method from the object of a student class so we can call the method and properties of the parent class it means a student class is inheriting all the method and properties of the person class now let’s learn about JavaScript super method the super method used inside a child class donates its pent class in this student class let me create one Constructor add one parameter and in this Constructor we will call Super here this super method inside the student class refers to the person class when we create one object using the student class it will call this Constructor method automatically then it will call this super and then the super will call this Constructor from the parent class which is person class and pass this name here in this Constructor then the argument will be stored in the person’s name still it will display the same output you can see in the console hello Peter let’s understand this example again here we have created one person class and we have another class with the name student and this student class class inherits the property of the person class so this is the parent class this is child class in this child class I’m adding super so this super refers to the parent class which is person class and it will pass this argument in the pent class so this was the Super method in JavaScript now let’s understand what is Method or property overwriting or ping method suppose the parent class and child class has the same method or property name in this case when we call the method or property of an object of the child class it will override the method or property of the parent class this is known as method overriding or cying method let’s understand the method overriding with one example here we have the parent class and this is the child class in this one let’s create the same method greet and in this greet method we will add console.log hello student plus this dot name and in this one we will add hello person this do name so you can see in this parent class and child class we have the same method name which is GRE in the parent GRE it prints hello person and name and in child class this greet method prints hello student and name now if we call the Greet method from the object created using child class then it will call the method of the child class you you can see the output in the console tab it is displaying hello student Peter it means it is calling this greet method from the child class so the method of the child class override the method of the parent class this is known as method overriding now let’s learn about JavaScript static methods static methods are bound to a class not to the instance of the class you cannot call the static method on an object it can be called only on the class so let’s declare one class class name is person and in this one let’s declare one method this method will display only text hello on the console now in front of this method if I add static it will become the static method now we cannot call this greet method on the object created using the person class we can call this greet method only on the person class let me make it capital P here the name of the class should just start with capital letter now let’s create one object here we will add const person one is equal to new person Peter and if I try to access the GRE method from the object object name is person one dot GRE it will display one error you can see the console tab it is giving an error now if I add person. greet I’m adding the class name and greet you can see the output here it is displaying hello now if you want to use these object properties inside this static method then you can pass the object as a parameter so let’s take another example here we have the person class then we have the St method in this a static method we will add one parameter X and in this console.log I will add hello space X do name so it will display the name from the object now we can call this greet method from the person class and we have to pass the object let’s pass this person one object here and now you can see the output it is displaying hello Peter because here I’m adding hello then object then property name so from this person object it will get the property name name is equal to name so the name will be Peter and here I’m adding text hello so hello Peter is printed in this console so this is the static method in the JavaScript now we will learn about JavaScript private methods private methods are accessible only within the class it means we cannot call the private methods outside of the Class by default methods of a class are public to make a method private we need to start the method name with the hash tag so let’s take one example I will add class person Constructor first name and last name we have two parameters this DOT first name will be first name then this do last name it will be last name now let’s create one method in this class method name is full name and it will return this DOT first name then a space this do last name so it will return the full name now let’s create one object using this person class I will add const person one is equal to new person and here we have to pass two argument Peter and let’s add anything B so we have created one object with the name person one now let’s see if I add person one dot full name we can call this method right and it is returning one value so we can add console.log person. full name you can see the console tab it is displaying Peter V it is returning the full name now if I add hashtag here so this method will become private method now we cannot access this private method outside of this class you can see the output it is giving an error now let’s see how to access this private method inside the class so in this class only we will create another method let’s create one method called display here we have display method and within this display method I will add console.log and here we can call this method but to call this method we have to add this this dot full name this will refer to the object and this is the private method with the hashtag now we can call this display method outside of the class so simply add person one 1. display and it will display the output here in this console tab it is displaying Peter B so let’s understand this example again here we have declared one class with the name person in this one we have this Constructor that will initialize the object properties then we have this private method and this method name I have added has tag that’s why it becomes private method now we cannot call this private method outside of the class we can call this method inside of this class so within this class we are calling this method here and to call this method within the class we need to add this keyword this dot method name with the hashtag so like this we can call the private method within the class now let’s learn about private static method this is the private method now we can can add the static keyword like this so it will become private static method and we cannot call the static method on the object we can call the static method only on the class so here we have to pass one object while calling this method so here we are calling this method so in this one we will pass the object so we will refer the object with this keyword we will pass the object and here we will add one parameter and from this parameter it will get the first name and last name it means it will get the first name and last name from the object that we are passing through this keyword while calling this private static method now you know we cannot call this a static method on the object we can call it on the class so instead of this keyword we will add class name person person dot has full name now you can see the output it is displaying Peter B let’s understand this example again here we have declared one class in this class we have one static private method now to call this a static private method we will use the class name dot method name with the hashtag and to get the object’s properties we are passing the object as argument here we are calling display method from the object this display method will call this class and this static method that is a static and private method so we can access the estatic private method using the class name person now we have completed class in JavaScript now we will learn about document object model the document object model is an API for manipulating HTML documents the Dom provide functions that allow you to add remove and modify part of the document effectively the Dom represents an HTML document as a tree of nodes in this HTML code you can see this is the node this HTML tag is a node this head tag is also one node this title tag is a node this text Greatest Tag is also one node this body tag is a node this comment is a node and this P tag is also a node now let’s understand about the node type so this one is the document type node these HTML head title body these are the element type node and these text are the text node and this is the comment node now let’s learn about node relationship any node has relationship to another nodes in the Dom tree and it is same as described in the traditional family tree for example this body is the child node of this HTML node and this HTML node is the parent node of this body node this body node is the sibling of this head node because they share the same immediate pent which is HTML element now let’s add some other content within this body here we will add one div and add this P tag within this div let’s duplicate this so we have four P tag in this div so this div element is the pent node of these P tag and the P tag is the child node of this div this one is the first child and this one is the last child the second p is the next sibling of the first one this third p is the next sibling of the second one and the fourth one is the next sibling of the third one in same way you can say the first one is the previous sibling of this second P the second p is the previous sibling of third p and the third p is the previous sibling of fourth p now let’s learn about selecting elements using Dom to get elements in JavaScript there are various method in Dom so the first one is get element by ID method get element by ID method returns an element object that represents an HTML element the get element by ID is only available on the document object let’s understand this with one example here I will remove this comment and I will add only one text in P tag and for this P let’s add one ID so I am adding the ID message and in this P we have the text JavaScript Dom now let’s add the JavaScript in this HTML page using the script tag within this script tag we can add our JavaScript code here we will add one variable with the name MSG which is message and we can write document dot get elementy ID and here we have to add the ID of this element which is message so this document. get element by ID will select this element and it will be stored in this message variable now we can print it let’s add console.log MSG here you can see the output in console tab P ID message JavaScript Dom so this element is printed in this console because I’m adding console.log MSG so in this MSG variable we have stored this element which is in the P tag if the document has no element with the specified ID then it will return null Suppose there is no element with this ID on the web page then it will return null you can see null and if there is multiple element with the same ID it will return only first element let’s duplicate it and in this one we will only write JavaScript now you can see the output in console it is still printing ID message JavaScript Dom so it will select the first element with this message ID because the ID of element is unique with the HML document the document. getet element by ID is a quick way to access an element now we will learn about get Elements by name method every element on HTML document may have a name attribute multiple HTML elements can share the same value of the name attribute let’s take one example here we will create one input field and in this input field I will add the type radio and we will add one name attribute name will be language and value will be JavaScript we can add another input field with the same name attribute and value will be something else python in this HTML code you can see we have two elements with the name attribute and we can select this element using this name so in this sub script we will add let BTN is equal to document do get Elements by name and in this one we will add language because the the name value is language now we can print this let’s add console.log BTN and you can see the output in the console tab here we have the node list that contains two input field you can see input and input so get Elements by name returns one list of nodes now we will learn about get Elements by tag name the get Elements by tag name method accepts a tag name and return a live HTML collection of elements so let’s understand it with one example in this HTML we will add one title in H1 so the text is first heading let’s duplicate it this is second this is third this is fourth we have four text here in the heading tag now we can select the element using the tag name which is H1 so here in this sub script we will add one variable with the name heading is equal to document dot get Elements by tag name and here we will add the tag name which is H1 now we will print it using console log heading so you can see the output on the console tab it is returning the collection of four HTML elements you can see H1 H1 H1 four times so this get Elements by tag name return the collection of HTML elements now we will learn about get Elements by class name the get Elements by class name method returns an aray like of object of the child elements with a specified class name the get Elements by class name method is available on the document element or any other element also so let’s understand it with one example here we will add one class name in the first title so the class name is message in the second one we will add the class name message and in the third one also we will add the same class name message let’s delete the fourth one now we can select these elements with the class name in this script let’s add let MSG is equal to document dot get elements by class name and here we will add that class name which is message now we will check the output in console MSG and you can see the output here it is returning the collection of three HTML element with the class name message you can see H1 do message H1 do message H1 do message so it is returning all the HTML elements with the same class name now let’s come back to the code and here we have added document. get Elements by class name we can add this get Elements by class name on any element also so let’s see the example here I will add one div and insert these two title in this div and for this div we will add one ID let’s add the ID container so total we have three headings with class name message but these two headings are included in this div with the ID container now we will add the get Elements by class name over this container so we have to store this container in one variable so let’s add let cont is equal to document do get element by ID and the ID is container now we can write cont here in sh of document we will add cont which is container and get Elements by class name now it will only give the elements within this container you can see the output here we have only two elements HTML collection 2 we have two HTML elements in this collection H1 do message H1 do message so this get Elements by class name will return the collection of HTML elements with the same class name on the document or within the element now let’s learn about query selector and query selector all method the query selector method allow you to select the first element that matches one or more CSS selector the query selector is a method of element interface we can apply this on element also here we will add one variable let MSG is equal to document dot query selector and in this query selector we have to add the CSS selector so in CSS to select this title we used to write Dot message because it’s a class name so we used to write do message to select this element in the CSS file so we have to add the same thing here we have to add the CSS selector in this quy selector that’s it so here we will print console.log MSG so first let’s see the HTML code here we have one title with this message another title with this message and third title with this message so total we we have three title with this message class name now let’s see the output in console tab here it is displaying only first element H1 class name message first heading so let’s come back here you can see we have added query selected only so it will return only first element now we will add query selected all after adding query selected all you can see it will display all the elements we have node list of three element which is H1 message H1 message and H1 message so it is returning all three headings and if I remove this all and write query selector only it will only return the first element here we have added quy selector all on document we can use the quy selector all on any element also so let’s add cont for container is equal to document do get element by ID here we will add this ID container now we will add this query selector over this container so just add container do query selector so it will give only two elements which is here second heading and third heading now you can see the output in console tab here it is displaying node list 2 it is displaying Two element so it is selecting only two elements which is in the container with the class name message now let’s come back to the previous example document do query selector all now let’s see what we can add in this query selector so we can add the class name using Dot so we can add the ID also we will add the ID and we can write this container we will add hashtag and this container because we used to write like this for CSS selector hashtag container because here we have the ID container so we can add the hashtag to select the element with the ID now we can add like this directly div so it will select this div element if we just write H1 so so it will select all the heading element with H1 tag we can write like this also div and H1 so it will select the heading within this div you can see the output here we have 2 H1 only now come back and we can select the multiple element like this div also and H1 also so it will select all the div element and all the H1 element by adding one comma you can see here we have four element node list four one is div with the container ID and three H1 tag with the class name message so basically we can add all the CSS selected in this query selector and query selector all method now we will learn about traversing elements to understand how to get the pent element how to get child elements and how to get the siblings of an element to get the parent node of the ESP specified node in the Dom tree we can use the parent node property in this body let’s create some HTML elements We’ll add one div with the ID title and within this div We’ll add one text NP tag welcome to greatest tag and for this P let’s add one class name text so we have one parent element and one child element now we will try to get the parent element using this child element so here in this script we will add let txt is equal to document dot query selector and we will add dot T text so it will select this P element now we have to get the parent so we will add console.log then txt which is the child element dot parent node this one just add this parent node and it will display the parent element of this child element so now let’s see the output in the console tab here you can see it is displaying div class title which is the pent element now let’s learn how to get the child elements we will learn about how to get the first child Element last child element and all children of the a specified element so here we will add another example just remove it and within this let’s create multiple P tag we have four text here Greatest Tag one two three and four so we have four title welcome to greatest tag 1 2 3 4 so now we’ll get the child element using this parent element now Within in this script first we will select this parent element so let parent is equal to document do query selector and write the query selector title so it will select the div now we have to get the first child last child and all the children of this div so here we add console.log and this parent then we will add first child now you can see the output in console tab here it is displaying # text because here we have some space so so this space is also one empty text node if we remove this and write it in the same line now you can see the output in console tab it is displaying the first title which is welcome to greatest tag one and if I add a space here it will display one text node now I want my text like this and I want to display the first element so here we will just just add first element child like this parent. first element child now you can see the output it will display the first element welcome to greatest tag one the first title in P tag similarly we can add last element child like this and see the output it is displaying well welcome to greatest tack 4 right so it is giving the last element which is welcome to greatest tack four now if you want to get all the child elements just add child nodes that’s it after adding this come back to the web page and here you can see we have node list text again P again one text again P so we have the empty text node then P tag let’s come back and here if I remove this a space and write everything in the same line like this now you can see it will only display four element which is 4 P element so we got the child nodes of this div now we will learn about how to select the next sibling and previous siblings of an element so in this example in this second P tag we will add one class name let’s add class name second like this so it’s easy to select this element and according to this element we will find the previous siblings and next siblings so here we will add second here also second so it will select this welcome to Greatest Tag 2 now to get the previous sibling here we will add this element then Dot and write previous element sibling that’s it you can see the output it is displaying welcome to greatest tack 1 so we are finding the previous sibling of Welcome to greatest tack 2 now just come back and here we will add next so it should give this welcome to greatest tag three because we are selecting this second one and we are adding next siblings so it will display third now let’s see the output H is dis playing Welcome to greatest Attack 3 so this is how you can select the previous siblings and next siblings now let’s learn how to manipulate the HTML elements so the first one we will learn is create element to create an HTML element we use the create element method the document. create element accept an HTML tag name and return a new node with the element type so let’s understand it with one example here we can add document dot create element and in this one we have to add one HTML tag so let’s add the div tag so it will create one div element we can store it in any variable so we’ll add let div is equal to document. create element div so it will create one div element now we can print it let’s add console.log div you can see the output on the web page it is displaying this div this div is empty right now so let’s come back here in the next line we will add div div dot inner HTML we will learn inner HTML also so here we can write any HTML code we will add one P tag and in this P we will add welcome to greatest tag and close this P now we’ll see the output here you can see one div and here we have one text in this we have one div tag and within this div we have P tag and the text is welcome to greatest tag so you can see using this document. create element we can create One D element or any HTML element and we can add any HTML code within this element and we can print it and we can also add this element on our web page so to add this element on our web page here let’s add document dot body we will add this element on the body so here we will add body dot app and child we will learn the app and child later so to insert this newly created div in this body we are adding appen child div so after adding this come back to the web page you can see we have text here welcome to greatest tack right so this is added us using this appen child div that we have newly created within this body you can see we have not added any text in div or P tag we are creating this element using this document. create element if I change it welcome to greatest tag two you can see it will be deflected here welcome to Greatest Tag 2 now we can add the ID or class name anything in this newly created element so here let’s add div. ID is equal to title let’s see here we have this div with the ID title now we can add the class name also just write div. class name title and you can see the output here D class title so we can create a new element using document. Create element and we can add the content here we can add the ID we can add the class name or any other attribute next we will learn append child method we use app and child method to add a node to the end of the list of child nodes of a a specific parent node the append child can be used to move an existing child node to a new position within the document so let’s create some HTML elements here here we will add one UL tag with the ID menu so we can easily select it here we will add some content in lii home second one is about third one is blog right you can see these elements on the web page home about blog let’s come back let me add one more here we will add project now within this script we will add let menu is equal to document do get element y ID and the ID is menu so it will select the UL element now we have to create one element and we will add that element in this UL so here let’s add let list is equal to document dot create element and the element tag name is is lii so it will create one lii element and its name is list so in this list we will add inner stml and through this inner HTML we will add one text contact like this now we can use menu do appen child list so this is the element which is here ul and this epen child will add this list at the end of this list in this list we have home about blog project so it will add the newly created list item after this project so here we have created one list item and the text is contact so this contact will be added after this project you can see on the web page here we have home about blog project and after this project we have contact that we have created using this create element and added using appen child in this UL so this newly created list will be added at the end of this list next we will learn about text content to get the text content of a node and its descendants you can use use the text content property so let’s see one example here we have the same HTML elements and this a script we have added this line that will select this UL element and after that remove this and here we will just add console. log menu so it will display the complete menu in the console tab now we just want these text so here we will add menu dot text content that’s it menu do text content and see the output in the console tab here it is displaying home about blog and project so it will ignore the HTML tag and display only text now let’s see one more thing here if I write inner text we are adding inner text and see the output still it is displaying home about blog and project but there is one difference this inner text is following the CSS also in this last one if I add a style display none so it will be hidden from the web page you can see that is not visible so this inner text will return only visible text you can see here we have home about blog and these home about blog is here on the web page but we have one more element here project which is invisible but if I write text content it will display all the HTML text content you can see on the web page we have home about blog only but here it is displaying home about blog and project so this text content is displaying all the text inside that element and inner text is displaying visual text only now we can use the text content to insert the text also let’s add menu dot text content is equal to hello so in this menu right now we have these list so it will remove this list and it will add hello let’s see the output here you can see we have only Hello in this web page so we can read and add the text using this text content on the web page next we will learn about iner HTML so inner HTML is used to add the HTML code on the web page so here we have added textt content so instead of this we will add inner HTML and see the output on the web page you can see we have hello so it is in the normal text so here if I write H1 it will add this hello text in heading so so it is in heading style hello so this inner HTML accept the HTML tags and add the text on the web page but instead of this inner HTML we will add text content now you can see what will happen it will add this as a plain text H1 is also displaying here and if I add in our HTML it will add this text and this hello text will be in the heading Style you can see this hello text on the web page next one is after method we can use after method to insert one or more nodes after the element so this is the Syntax for after method we have to add the element name then after method and we have to pass a new node that we want to add after that particular element suppose we have this menu element so we can write this menu then after method in this one we can pass a new element and we can create a new element using the create element method this after method can accept multiple nodes so we can add multiple element after this menu it can also add a string after the element so we can add multiple string s str1 s Str 2 like that we can add multiple string after this menu element so so this is the use of this after method now let’s learn about append method so this append method is also similar as append child but in the append method we can add multiple elements this is the Syntax for append methods we have to add the parent element then append then we have to pass a new element that we want to add in that parent element so this new node or new element will be added in the parent element at the end of the list of childs so what’s the difference between append and append child so this appen will accept multiple nodes and it can add string also the next one is prend Method so this is the Syntax for prepend method parent node. prepend and new nodes so it will add the new node as a first child in this parent node so this is the prepend method the the next one is insert adjacent HTML so this is the Syntax for insert adjacent HTML here we have to add one element then insert adjacent HTML method and here we have to give position and text so suppose we will add this element menu and we want to add one text at the end of this list so here we have to give the position so the position can be before begin after begin before end and after end so suppose we add before begin so this element is starting from here so this before begin position means it will add the new node before this ul and if we add after begin it will add it here at this position and if we add position before end so this is the end so it will add before end here it will be added in this line and if we add after end so it will be added after closing of this UL so let’s test it here we will add any one position I will add before end let’s add before end and here let’s add lii contact like this so here I’m adding one html text and this is the position and this is the element where we want to add this so you can see the output on the web page the contact is added here now let’s come back and if I add after begin so it will be added here at this line because this is a starting of this element and it will be added here you can see the first one is contact and after that home so this is how this insert adjacent HTML works now the next one is replace child here is the Syntax for the replace child method replace child method is used to replace the child element with the new one so we can use this syntax we will add the parent node then replace child method here we have to add the old child that we want to replace and here we have to add a new child that will be replaced on the place of old child next one is clone node method we can use clone node method to clone an element here is the Syntax for clone node method we will add the original node then clone node so this new node will have the another copy of this existing node if I add menu so this new node will have one copy of this menu element let’s print this one here we will add console.log new node you can see the output it is displaying ulli menu now let’s come back and here we can pass the argument so if I WR true it will clone this descendants also this UL element and these Li elements Also let’s come back you can see we have ul and all these Li and if I remove it or write false by default it is false we don’t need to write but if I write false you can see here we only have UL element and if I remove move it still it will be only ul and if I write true it will clone the element and all the child element also you can see ul and all three lii so this is the Clone node method next one is remove child method to remove the child element of a node we can use remove child method here is the Syntax for remove child method here we have to add the pent element and then write the element that we want to remove from the pent element so here let’s add menu and from this menu suppose I want to remove this last one so here we will add menu dot last child element so it will remove this blog you can see on the web page here we have home about blog is missing if I write menu DOT first element child so it will remove the first element which is home you can see on the web page here we have about and blog so this is the remove child method next one is insert before method we can use insert before method to insert a new node before an existing node as a child node of a parent node here is the Syntax for insert before method we have to add one pent element then this insert before method and it will accept two arguments in this one we have to add the new element that we want to add and we have to add the existing element before that existing element this new element will be added we have the pent element menu so we will add menu here and we want to add the new element before this lii that home link so here we’ll add menu DOT first element child so this new node will be added before this home so this is the insert before method so these are the methods to manipulate the HTML elements now we will learn about attribute methods so let’s understand what is attributes here I will add one HTML element input type is text we will add one ID so let’s add the ID username and we can add the placeholder also username so in this HTML tag we have added three attributes which is this one this one and and this one this is the attribute name and this is the attribute value the ID is the attribute name username is the attribute value this placeholder is the attribute name and username is the attribute value now how we can get the attributes of any HTML element using JavaScript so let’s add one script tag here where we will add our JavaScript code first we have to select this element so we can use any method to select the element let input box is equal to document. get element y ID I’m using get element by ID method and we will add this ID username after selecting the element we can find the attributes available in this HTML element so to get the attribut we will just add the element which is input box and after that just add attributes that’s it it will give all the attributes available in this HTML element so to print this in console we will add console. log and add this code inputbox do attributes after writing this let’s come back to the web page and uh you can see the console tab it is displaying type then ID then placeholder so we have three attributes in this HTML element now we have some attribute methods to get the attribute value and to set the attribute of any HTML we can check for some attribute whether it is available or not and we can also remove the attribute using the attribute methods so let’s see the first method which is get attribute so instead of this we will add the element which is input box and here we will add get attribute and in this get attribute we have to add one argument so we will add the attribute name so here we have the attribute name type so just add type like this and after that let’s come back to the web page you can see here is displaying TT so we can read the value of the attribute using the get attribute method let’s take another example here I will add this placeholder write this placeholder here now it will display the value written in this placeholder attribute so come back to the web page here you can see it is displaying username this username text is available in the placeholder attribute so this was the first method get attribute to read the attribute value now we will learn about second method which is set attribute so let’s remove this one here we will add the element which is input box on this input box we will apply set attribute and the set attribute will accept two argument so the first argument will be attribute name and the second argument will be attribute value like this here we will add the name comma value like this so let’s remove this here and here we will add any attribute name so let me add the class so the attribute name is class and here we will add one value let’s add the class name user like this so it will add one attribute which is class and the value is user now to see the updated input let’s add console.log and here we’ll add input box so it will display this complete element on the console so let’s come back to the web page here in this console you can see we have the input element with the type text ID username placeholder username and there’s one more attribute which is class user that we have added using this input. attribute class user so this was the set attribute method now we will learn about next one which is has attribute so it will tell us whether this attribute is available on the element or not it will result in true or false so here we will add another example we will add the element input box then has attribute and this will accept only one argument so in this one let’s let add class and it will return one true or false value so we can directly print this one so just add console.log input box has attribute class so you can see in this input field we have the type ID and placeholder we don’t have class here so it should return false let’s see the output you can see it is displaying false now let’s come back and instead of this class we will add ID so it will return true let’s come back to the web page you can see it is displaying true in this console so this has attribute will return true or false value if the attribute name is available in the input field it will return true if this attribute name is is not available in the input field then it will return false so using this has attribute we can check the availability of that particular attribute on the element next we will learn about another method which is remove attribute that will remove the attribute from the element so in this one we will add element then remove attribute and in this remove attribute we will add one attribute name that we want to remove so here we have type ID and placeholder so let’s try to remove this placeholder just copy this one paste it here so this remove attribute will remove this placeholder from this input element now we will just print this input element in the console we will add console.log input box and now we will see the output in console here we we have the input element and in this input element we have type text ID username but here we don’t have the placeholder because in this code we have added remove attribute placeholder so it will remove this placeholder attribute from this element so these are all four attribute methods now we will learn about manipulating elements a style to manipulate the style of the element we have the property called Style and we can use this a style property to get or set the inline style of an element so here we have the HTML element which is input and in this one we don’t have any inline style so let’s add one style here and here we will add the background color value is red and let’s add one more CSS property here that will be for font size 20 pixel so in this HTML element we have added the inline CSS in this one we have added the background color and font size now to get these inline CSS we can use the style property on this element so here let’s add the element which is input box do style so it will return the CSS properties available in this input field in the inline CSS it is returning some value so we can add console.log and this code now you can see the output in the console tab in this console you can see it is displaying background color and font size because here we have only two inline CSS properties which is background color and font size so this element do style will return the inline CSS available in the element now if if you want to return the background color value or the font size value then we can write input box style dot background color like this after adding this come back to the web page here you can see it is displaying red background color value is red now if you want to see the value of this font size here we will add font size and you can see the output here in the console tab it is displaying 20 pixel so we can get the property name also and value also now we can use this style property to set the style of the element so let’s add input box and on this input box we will add a style and in this a style let’s add one new CSS property let’s add padding padding is equal to 10 pixel after adding this we will display this input in the console so we will add console.log input box so it will display this input field in the console tab where it will add the padding also so let’s come back here you can see we have this input element in this one we have the style background color then font size and after that you can see this padding let’s select this one here you can see padding and the padding value is 10 pixel so using this style property we can get the inline CSS and we can also set the inline CSS now we have one more option to add the inline style in the HTML element that is using CSS Tex text so here we will add the element then style then CSS text and in this CSS text we can add the CSS so let’s add width 200 pixel after adding this let’s print this element in the console you can see the output here on the web page it is displaying this element with the style width 200 pixel here we have only one CSS property which is width 200 pixel let’s come back to the web page we have added CSS text with 200 pixel so it will override the existing inline CSS you can see we already have background color font size but it is not available on the web page why because we are adding width 200 pixel using this CSS text so it will override completely it will remove this and add this one but if you want to keep the existing CSS also and add this one also then you can use the concatenate to perform the concatenate we will just add plus before this assignment operator like this after adding this again come back to the web page now you can see in this input field we have the multiple CSS properties which is background color then we have font size and width also so after adding this concatenate we can use the existing inline CSS also and we can add a new inline CSS using this CSS text we can add multiple CSS properties at the same time you can see we have added width so we’ll add more CSS properties just add semicolon and add another CSS property let’s add height height will be 100 pixel now we will come back to the web page you can see height is also applied in this input field you can see it in the console also here we have height 100 pixel so using this CSS text we can add multiple CSS properties in the HTML element as a inline CSS so this was the use of CSS text for modifying the inline CSS of the HTML element now we will learn about get computed style method currently we have learned how to modify and get the inline CSS properties of the HTML element using JavaScript now how to get the CSS properties written in the external CSS so let’s remove the CSS from here remove this inline CSS and we will add the CSS properties in this head here we will add style tag within this style we will add the CSS selector input and for this input we will add the background let’s add the background color red and font size 12 pixel so we have added two CSS properties for this input element now how to get these CSS properties to get the CSS properties of this input element we will use get computed style method so let’s see the syntax first this computed style method is a window object so we will add window do get computor style and in this one we will add the element we can add one more argument that will be C element so this is the Syntax for get computed style in this one we will add the element if you want to get the CSS property of the element and if you want to get the CSS properties of the seudo element then you have to add the element and it C2 element and now let’s see the example for this input field so here we will add window do get computered style and in this one we will just pass to the element which is input box now it will return the CSS properties available on this input field so we can print it using console console. log and add this one now let’s come back to the web page to see the console tab here it is displaying all the CSS properties that are applied by default on the element in this one we will find the background color also you can see the background color here and there will be font size also it is here font size so now we can get the value of the particular CSS property so from this input box we will add font size now it will display the value of this font size you can see it is displaying 12 pixel that we have added here in external CSS now let’s add the background color we are adding this window. get computed style then passing this element and from this element we’ll get the value of this background color let’s come back to the web page here is displaying the color now let’s come back in this one we will add one more property let’s add the width of 300 pixel and here we will add dot width then we will see the output it is displaying 300 pixel so using the git computer style method we can read all the CSS properties applied on any HTML element now we will learn about class name property class name property return a list of classes separated by space so let’s take one example here we will add one title in H1 tag so let’s add the text greatest T and and with this H1 we will add one ID to select this element we will add the ID title and let’s add some class name also so let’s add the class main the first class name let’s add one more class name which is message so in this one we have added two classes which is Main and message now to get the class name of this element we will use the class name property of JavaScript so let’s add the JavaScript here in this script tag first we have to select the element so let’s add the variable with the name title and select the element using document. get element by ID and write the ID title after that we will add title dot class name that’s it it will return the list of classes available on this element so it is returning some value then we can print this one in console let’s add console.log title dot class name that’s it now we will come back to the web page now it is displaying the classes available on this element which is Main and message so we have two classes we can use this class name property to add a new class also so let’s come back here and here we will add title dot class name is equal to new so this will add one class name which is new in this element let’s remove this class name here we will display the complete element in the console using this console.log title let’s see the element here you can see it is displaying this HTML element with ID title and class new we have only one class which is new but in this HTML you can see we have already added Main and message so this will override these classes here we have two classes that will be removed and this new will be added in this class but if you want to keep the existing class also and new one also then you can use the concatenate using this plus and this assignment operator after adding this here we will add a space and let’s come back to the web page now you can see the same element H1 here and in this element we have class main message and new so we have total three class here so using this class name we can read the class name of the HTML element and we can add a new class also now we will learn about class list property class list return the collection of CSS classes so let’s see if we add class list and it is returning some value so we will print this one title. classlist like this we are just adding title. class list and you can see we already have Main and message class in this element now we will come back to the web page in this one you can see we have a list where we have Main and message class so we have two classes so this class list is returning the collection of classes available in any HTML element so this was the first use of this class list to display or get the class list of any HTML element now we can use this class list to add the class to remove the class so let’s understand how we can add a new class using this class list so in this title element we will add classlist do add like this we are adding class list do add and in this one we can add a new class just add new like this that’s it after adding this we will display this complete element in console tab we are displaying this title let’s come back to the web page here you can see we have this element with three classes main then message then new let’s change the size so you can see we have total three classes main message and new now let’s come back if I add multiple classes we’ll just add a comma and add a new class name like new two so we are adding another class name like this we can add multiple classes using this class list you can see we have more class name here main message new and new to so using this class list. add we can add a new class name in the stml element now we can use this class list to remove any class so instead of this add just type remove class list. remove and what we will remove we already have Main and message so let’s remove this message write it here in a quote and come back to the web page here you can see in this element we only have one class which is main now just come back and we can remove both classes so let’s add comma and write main so it will remove the another class also we can type multiple class name here and it will remove all that classes from that element you can see this element in this element we don’t have any class we have the class attribute name here but we don’t have any value in this class next we can use this class list to replace any class so instead of this remove we will add replace and to replace this one we have to add the existing class name and new class name so in this HTML element we have message so write message here and we are adding a new class name instead of this message so we’ll add MSG so instead of this message we will replace it with MSG now just come back to the web page you can see the output in console here we have class name Main and MSG so we are replacing this message class with MSG class using this class list. replace place now we have one more option to check whether the class is available or not for that here we will add class list do contains and in this one we will add any class name so this message is here we are adding message so this will return the value either true or false if this message is available in this element then it will return true if it is not available it will return false so we’ll just print this one remove it from here add it in console and come back to the web page you can see it is printing true because this message class is available in this element so we are adding class list do contains and class name this class name is available in the element that’s why it is returning true suppose we add MSG and this MSG is not available in this element then it should return false you can see the output it is false now we have one more thing which is toggle let’s see this example here we will remove this one we will just print this complete element in console and here let’s add title dot class list. toggle and in this toggle we can add any class name suppose we add message what will happen if this message class is available in the element it will remove it this toggle means if the class name is available it will remove it and if it is not available then it will add that class name in the element so what will be the output this message is already there and we are adding toggle message so it will remove this message let’s see the output in console here you can see class main here we have only one class which is main so this toggle removed this message class now instead of this message we will add new so what will happen this new is not available here so it will add this new in this element let’s come back to the web page again and now you can see we have total three class in this element which is main message and new so using this class list. toggle we can add and remove the class from the element if the class name is already there it will remove it and if it is not there it will add the class so this was all about class list property in JavaScript now we will learn about JavaScript events an event is an action that occurs in the web browser when we click on the web page that is a click event when we move cursor over the web page that is mouse move event and when the web page loads that is a load event like that we have multiple type of events in JavaScript let’s create some HTML elements here I will create one div with the ID container and within this container we will create one button with the button tag and button type will be button and here we will add the text click here now we will come back to the web page here you can see this button click here if I click here nothing is happening because we have not added anything so let’s come back you can see we have added the button and clicked on this button but when we click on this button we are actually clicking on the button this div this body and this HTML and this document also so when we click on any element actually we are clicking on the all the patent elements also that means this di with the ID container then body then HTML and this document and in modern browser this click goes up to window object there are two event models that is event bubbling and event capturing so when we click on the button click a start from the button then goes to div then goes to body then goes to HTML and then goes to document so the event flows from the most specific element to the least specific element that is event bubbling but when the event start from the least a specific element it means it starts from the document then event flow to HTML then it flows to body then it flows to div with the ID container then it comes to the Target element which is button so this event model is known as event capturing when the event starts at the least specific element and flows towards the most specific element we may respond to these events by creating event handlers an event handler is a piece of code that will be executed when the event occurs so when we click on this button we will add some code that will be executed after clicking on this button so that code is known as event handler and event handler is also known as event listener so there are three ways to assign event handlers so first one is using HTML attribute for each event there is event handler and their name typically begins with on so let’s see the example we have click event and for this click event we have the event handler on click like this so let’s assign this on click in this HTML element as an attribute so in this HTML element we will add on click so this is the event handler of the click event and within this quote we can write the JavaScript so let’s add a simple JavaScript line console.log so it will log one message in the console of the browser in this one let’s add some text here we cannot add double code because we have already used so I’ll add single quote button clicked so this button clicked message will be printed in the console when we click on this button so let’s see this on the web page this console is Ed right now and if I click on this button that is here in top left corner you can see this message button clicked this event handler attribute can call one function also so let me remove this HTML code we have added event handler which is on click and this on click will call one function so here let’s create one function in a script tag in this script We’ll add one function with the name display MSG that will display message here we will add console.log button clicked let’s add some more text button clicked from FN which means button clicked from function now we will call this function when we click on the button so in this attribute we will call this function write this function here so this is a function call now let’s come back and you can see this console is empty and if I click on this button again you can see the message here it is saying button clicked from FN it means button clicked from function now just come back when the event occurs the web browser passes an event object to the event handler so to understand this one let’s remove this function here and we will add JavaScript code in this attribute so here let’s add console.log and when we click on the button the JavaScript will pass the event object so we can write that event object here event now we can see what is there in this event object let’s see the output so you can see here we have one object now this event object has some properties that we can access so from this event we can find the type event. type let’s see it is displaying the event type event type is Click let’s come back we can add the target so we will get the target element on which the event occurs when we clicked on the button it is displaying the entire button element with all the attributes so it is giving the target element we can also use this keyword inside the event handler and this keyword inside the event handler refers to the Target element let’s see the example example here in this event handler we will try to print this this keyword will refer to the Target element let’s see the output when we click on the button you can see again we got the target element which is button so this keyword inside the event handler refers to the Target element from this keyword we can find the properties of this element so let’s add one ID here I will add the ID is equal to BTN and here we will add this do ID so when we will click on the button it should display the ID value let’s see if I click on the button it is displaying BTN now just come back and instead of this do ID we can simply add ID from the event handler we can directly access the elements property so we are adding console.log ID so it should display this ID value let’s see if I click on the button we got the ID value which is BTN if I write type which is here we will get button it’s here so this was the first method to add the event handler in HTML as HTML attributes now the second method is adding event handler name in the JavaScript so let’s remove this on click from here we have one button let’s remove this type also it will be simple so we we have one button with the ID BTN now we will add the script where we will add the JavaScript So within this script first we have to select this button so let’s add let BTN is equal to document. get element y ID and we will add the ID BTN so we have selected this button element now on this BTN we can add the event handler just add on click and now we can add the code that will be executed when we click on the button so here we’ll create one function and within this function We’ll add console do log and this will print message button clicked after that let’s come back to the web page click on the button and you can see the output in the console button clicked let’s come back you can see here we have the HTML element and in this one we have added the JavaScript in this JavaScript we have added on click event handler name and added one function that will dis play one message here also we can write this keyword that will refer to the Target element and from this we can find the ID this do ID let’s see it is BTN now to remove the event handler we will simply add element which is BTN do onclick and assign null that’s it it when we assign null in this event handler it will remove the event handler so this was the second method to assign the event handler now we will learn the Third Way of assigning event handler so in JavaScript we have two methods with the name add event listener and remove event listener these are two methods that handles the event ad event listener will register an event handler and remove event EV listener will remove an event handler so let’s see the example of add event listener the add event listener accept three arguments the first one will be event and the second one will be one function this function will be executed when the event fires and the third argument is use capture so the third option is optional because by default it is false this use capture is a Boolean value it can be true or false so by default it will be false and we can remove it it is related to the event bubbling and event capturing so let’s ignore that third parameter we will pass to argument event and one function so let’s see one example so let’s try to add this add event list on this button remove it here we will add BTN do add event listener and we will pass first argument which is event so the event will be click we are adding The Click event then a comma here let’s define one function here I’m adding function like this so this is the function defition within this curly Braes we can add the code that will be executed so here let’s add console.log and message button clicked so we have selected the button using get element by ID then on this button we are adding add event listener method that will assign the event handler so in this event listener we are adding first parameter and second parameter first parameter is event so the event is click and the second parameter is a function so we have declared one function here this function will print one message in the console tab when we will click on the button let’s see this output on web page click on this button and you can see the message button clicked as I already said when the event occurs the JavaScript passes the event object to the event handler so in this one we can pass the event object and we can find the type from this event event. type let’s see the output if I click on the button we got event type which is Click now instead of adding this Anonymous function we can add the external named function also so let’s remove it here we can add our second parameter before adding that second parameter let’s create one function with the name display message and this display message will log one message message button clicked now we can refer this display message function here like this after adding this let’s come back and if I click on the button again you can see the message button clicked so we can add the event name and one function it can be a Anonymous function or it can be a named external function we can refer to that external named function with the function name without the parenthesis so this was add event listener method now we will learn the remove event listener method the remove event listener removes an event listener that was added using add event listener so here we have added the event listener using add event listener method now we can remove it using BTN dot remove event listener again we have to pass the same arguments just copy and paste it here so this remove event listener will remove the event listener that was added using this add event listener you can see here I have added the external named function if I add one Anonymous function here then we cannot remove move that event listener using this method so we have to use the external named function when we want to add the event listener and remove the event listener now let’s know about some of the useful JavaScript events so the first one is mouse move event Mouse move event fires repeatedly when you move the mouse cursor around the element and second one is mouse down event when you press the mouse button on the element this event will fire next one is mouse up when you release the mouse button on the element then this event will fire next event is mouse over event when the mouse cursor move from outside to inside the boundaries of the element then Mouse over event occurs next one is mouse out when the mouse cursor is over an element then moves to another element then Mouse out event occurs next one is key down event key down event fires when you press the key on the keyboard and it fires repeatedly while you are holding down the key next one is key up event this key up event files when you release a key on keyboard next one is key press so the key press event occurs with when you press a character keyboard like ABC it files repeatedly while you hold down the key on the keyboard next one is scroll so a scroll event occurs when you scroll a document or an element the scroll event fires we will see more examples of events when we will create the JavaScript projects now we have completed the basic of JavaScript next we will create some JavaScript projects in this video we are going to learn how to create a Notes app using HTML CSS and JavaScript here on my computer screen you can see one button create nodes if I click here it will open one input box and here we can type our text note this is note one so you can add your text note in this white box and if I click on this button again it will again open a new input box where we can add another note and if I click on this delete icon it will delete this note we can delete all the nodes and let’s add the text again two so we have added two notes here this is Note One Note Two And if I close this browser and open the browser again let’s see you can see this note is still displaying here because we have added the local storage that will store the notes in the browser so we will create this note app that will store the text note in the browser using HTML CSS and JavaScript so let’s start this video here I have this folder called Notes app in this one I have one HML file one CSS file and another folder called images in this images folder I have some icons that I will be using on this web page you can find these images download link in the video description let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added margin padding font family and box sizing these CSS properties are applicable for all the HTML elements in this HTML file I have added this title that is the title for the web page then we have added the link tag with the file name style. CSS so it will connect the HTML and CSS file next we have to add the HTML codes in the body tag that will be displayed on our web page so within this body let’s create one div with the class name container now in this container we will add one title in H1 so here we are adding one title notes and after this title there will be one button so let’s add one button and in this button we will add the button text create notes after adding this let’s come back to the folder and open this HTML file with any web browser so you can see this text here notes and create notes button now I will close this browser and I will open it with the visual studio code extension called live server so it will refresh the web page automatically whenever we will add any changes in the code file you can see the same web page but the order has been changed now we have to add some CSS so just come back and copy this class name container and come back to the CSS file within this CSS file let’s add do container and here we have to add the width then we will add minimum um height and in the background we will add the linear gradient color so let’s add the background linear gradient and two color codes then we will add color that will be white and let’s add some space from the top padding top and padding left that will be spaced from the left side after writing this you can see the changes in this web page the text color is white and the background color is linear gradient now let’s come back and uh with this text we have to add one icon also so just in front of this notes we will add one IMG tag so here we will add IMG and SRC and file name images SL the file name is noes. PNG and in this button also we will add one icon so here also let’s add this IMG tag and replace the file path so it is edit.png so we have added two icons with the tag in the nodes and create nodes button you can see this icon and this edit icon in the button now we have to add the CSS for these icons and font size so let’s come back after this container again add container and H1 for the title here we will add display Flex align items Center then font size will be 35 pixel and font weight 600 now within this H1 we have added one icon with the IMG tag so we are adding IMG here and for this image we will set the width it will be 60 pixel so this size for the note icon looks good next we will Design the button so let’s come back and here we will add container then button and in this button we have image so for this image again we will add the width 25 pixel and margin from the right side this will be H pixel let’s copy container and button now we will Design this button using CSS so let’s add display then align items background will be linear gradient two color code button text color will be white and uh font size outline zero and Border zero border radius will be 40 pixel let’s add some padding that will be space inside the button 15 pixel from top and bottom and 25 pixel from left and right side then margin that will be space outside of the button 30 pixel 0 and 20 pixel cursor will be pointer so after adding this you can see this create notes button looks good next we have to add one input box where we can type the text note so let’s come back and uh after this button we will add one tip with a class name nodes container and in this one let’s add one P tag in this P we will add content editable true and we will add one class name also so the class name is input box so it is not visible here because we have not added any text in this P tag so let’s come back and we have we have the input box just copy this one and come to the CSS file write this input box with the dot and here we will add position relative width will be 100% And the maximum width will be 500 pixel then mean height background will be white so we have added width and height in this P then we will add the color padding of 20 pixel margin 20 pixel and zero then let’s add outline none border radius 5 pixel so that the corners will be round after adding this the input box looks good and in this input box we can type anything now we need uh delete icon also so let’s come back and uh before closing of this P tag here we will add a space and before closing of this P tag we will add one IMG tag write the file path images SL delete.png it is delete icon and you can see this icon here next we have to set the size and position for this delete icon let’s come back here we will add this input box then IMG for this image width will be very small 25 pixel Position will be absolute then it will be at bottom 15 pixel space from the bottom and 15 pixel space from the right side cursor will be pointer after adding this you can see perfect position for this delete icon now this input box is displaying by default so we have to to hide this input box and it will be displayed whenever we will click on the create note button and every time you will click on the create noes button it will run a JavaScript and that JavaScript will display the input box so let’s come back and here we have the P you can delete this P tag or command it let me commment this one so it will be disabled and right now you can see we have the text and button we don’t have any input box now we will display the input box with the help of JavaScript so let’s come back and here we’ll click on this icon to create a new file and write the file name script.js so this is our new file script.js next we have to connect this script file with the HTML file so let me come back to the HTML file and just above this closing body tag we will add script SRC and the file name which is script.js now the HTML file and JavaScript file are connected let me open the folder again and here you can see one new file which is a script.js in the same place where we have added HTML and CSS file now let’s come back to the JavaScript and here we will add some variables so let’s add const nodes container con nodes container equal to document. quy selector do nodes container now we will duplicate this line it will be create BTN and here we will add the class name BTN and uh in this button we will add one class name class BTN after that we will add one more variable let nodes equal to document dot query selector all dot input box so here we have added three variables notes container which is for this notes container class name then create button which is for this create button and then we have added another one notes that is for this one input box this input box is not there but we will add it using JavaScript so we will add the multiple P tag with the class name input box so here I’m adding query selected all that will select all the nodes after that let’s add one function then I will explain you each line here we have added create button add event listener it means whenever we will click on the button that is here BTN so it will execute these codes and first it will create one variable called input box and it will store one element document do create element by P so it will create one p element and it will store it as input box then it will create another element with the IMG tag and it will be stored as IMG now in the P element which is input box it will add one class name called input box then in this P element we will add one more thing which is content editable true so we are adding input box set attribute content editable true so it will add one P tag then in the P tag it will add one class name input box then it will add one attribute content editable true and after that we have added img.src we have created one more element IMG and in this Source we will add one file path that is for the delete icon images /d delete.png so it will add this image IMG srz images /d delete.png now we have to display it so we have to display this in the notes container so you can see we have added noes container do appendchild input box it means this input box will be displayed inside this noes container and after that we have added the and child IMG it means this image will be displayed inside this P tag which is input box so after adding this let’s come back to the web page and click on this button you can see it is adding one new input box with the delete icon and we can type anything in this input field it is working now click again it will display the another input field now if I click on this delete button nothing is happening so we have to add one more thing this delete functionality so let’s come back and here we will add this one notes container add event listener again we will add the click event then function if e do Target dot tag name if the target is IMG then e do Target dot so we have added nodes container event listener click so when we will click within this notes container and if the target element is IMG then it will remove that parent element so let’s come back click on this button it will display one input box and here we have the delete button let’s click on this delete icon and it will remove that pent element let’s click again and click on this delete you can see it is deleting the parent element so it will hide that input field this delete is working fine and we can also write something here hello this is new video right now we have added two notes and if I refresh the website you can see it will be disappeared because we have not stored these things in the browser so we have to add the local storage that will store the notes in our browser every time we will open the browser it will be stored and displayed as it is so let’s come back after these variables let’s add some space and here we will add one function update a storage data storage and after that we will add local storage do set item and write the name noes and what we have to store here we will store noes container do inner HTML so whatever is written in the noes container inner HTML that will be stored in the browser with the name notes so whenever we will call this update a storage it will update the data in our browser so let’s copy this one and add it here after deleting it it should be updated so in the next line we will add update a storage next we need one more thing if we write anything in the P then also it should update the data in the browser so here we will add the another condition which is L if here we will add nodes equal to document do query selected all input box now for all the nodes it should update the data in browser so here we will add noes dot for each n sort for the nodes ENT do on key up equal to function and here we will update a storage so it will update the storage when we will start typing edit anything in the P tag next we need one more thing when we close the browser and open the browser it should check the local storage and if there is any data in the local storage then it should display that particular data as a note so let’s come back here at the top after this variables let’s add function so notes notes container do iner HTML equal to local storage dot get item and the item name is notes so if this notes is there in the browser then it will be displayed on our web page just we have to call this function so notes just copy this one paste it here so notes will call this function and it will display this local storage in the container HTML so let’s see how it works if I refresh the web page you can see it is still displaying the note one and Note 2 let’s delete the note one here we have this is Note 2 let’s refresh the website you can see still it is displaying Note 2 so this local storage is working next we will add the one more last thing here will add here we are adding document do add event listener key down event and if the event key is enter Then document. exe command is insert line break and event prevent default it means when we will click entered in our keyboard then it will add one line break in the P tag and it will prevent the default feature of the enter key now let’s see here we will create a new note note one enter line 2 Enter line three refresh the web page you can see it is displaying as it is so finally we have completed this online note app using HTML CSS and JavaScript with the local storage in this video we will create a very useful JavaScript project which is simple quiz app you can create this squiz app or website with the help of HTML CSS and JavaScript let’s see how this squiz app works you can see this question here then we have four options if I select the wrong answer you can see it will become red and the correct answer will become green and now we cannot change our selection now we will click on the next button and if I select the another option let’s select this one and if it is correct then it will be highlighted with the green color and now we cannot click another option we have to click next and here if we will click on this one if it is correct it will become green and let’s click on the next one and now we will select any wrong answer so you can see it is displaying the red color and the correct answer is highlighted with the green color I have added only four questions here if I click on the next button you can see it will display our score you scored two out of four because we have given only two correct answers let’s click on this button play again and if I select the correct answer and again this one this and this one and click on the next you can see it is giving the correct score which is four out of four we will create the squee app using HTML CSS and JavaScript and I will explain you step by step now let’s start this tutorial to create the JavaScript quiz app here in this folder I have one HTML file one CSS file and let me open these files with my code editor which which is Visual Studio code you can use any code editor if you don’t know how to create the HTML and CSS file I will add the video link in the description this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added the margin padding font family and box sizing these CSS properties are applicable for all the HTML element in this HTML file I have added this link tag with the file name style. CSS so it will connect the HTML and CSS file and here we have the the title quiz app easy tutorials next in this body tag we will add one D with the class name app next we will add the CSS so come to the CSS file and here first we will add the dark color on the complete web page so we will add body tag and for this body let’s add one background here we will add one color code and next we will add the CSS for the app so just copy this one add it here in this CSS file with the dot because it is a class name here we will add background so the background will be white after that we will add the width 90% and maximum width will be 600 pixel then we will add the margin 100 pixel from top left right Auto and zero from the bottom then border radius so the Border radius will be 10 pixel so the coordinates will be round by 10 pixel after that we will add the padding of 30 pixel that will be a space inside the box after adding this let’s come back to the folder and open this HTML file with any web browser so you can see this color on the complete web page and here we have the box in the white color I will close this browser and I will open this browser with the visual Studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file so you can see the same web page again but the URL has been changed after that let’s come back and uh within this app we have to add one title so here we will add one title in H1 simple quiz and after that we will add one another div with the class name quiz and within this we will add one question in H2 so let’s add the H2 and here we will add one ID so the ID is question and let’s add any text here so we will add question goes here like this and now you can see this text simple question and question goes here after that we will add some options for the particular question so here we will add one div with the ID answer buttons and within this answer buttons we will add four buttons so let’s create the first one and in this one we will add the class name BTN and here we will add the answers so let’s add the text answer one now we will duplicate this button and we will change the text 2 3 and four and the class name is same after adding this you can see four buttons here after this question answer 1 2 3 4 next we have to design this using CSS so let’s come back and uh here we have the class name quiz so just copy this one and come to the CSS file before the squeeze we have the text in H1 so we will add the CSS for that text so let’s add do app and H1 where we have added the text so for this one we will increase the font size then we will change the color font weight and border bottom then we will add the padding at the bottom now you can see this line here after this text after that we will add that class name quiz and for this quiz we will add the padding it will be 20 pixel and zero after that in this squeeze also we have text which is the question in H2 so here we will add do quiz and H2 so for this question we will add font size so the font size will be 18 pixel then we will change the color and font weight and uh here we have added font weight it will be font size font size 25 pixel now it is good next we will Design these buttons which is answer button so for this button we have added the class name BTN so come to the CSS file here we will add the CSS for BTN so for this button we will add the background so the background will be white after that we will add the color that will be the text color and font weight font weight will be 500 then width will be 100% so it will be full width and border of one pixel solid and this color then we will add the padding that will be a space inside the button and margin 10 pixel from top and bottom and zero from left and right after this padding and margin we will add text align left and uh border radius will be 4 pixel and cursor pointer you can see these buttons looks good next we have to add the hover effect on these buttons so let’s come back here we will add this one and hover we will add the background this will be the background color code and after that we will add the color that will be the text color white and in this one we will add the transition all 0.3 seconds now if I take cursor you can see the background becomes black and the text becomes White next we have to add one more thing which is the next button at the bottom of these answers so let’s come back and uh here after this button and this tib here we will add another button and with this button we will add the ID next BTN and the button text is next after adding this you can see next button at the bottom so we will add the CSS for this next button so let me come back and copy this ID add it here in the CSS file with the has tag because it is an ID here we will add the background then color font weight and width width will be small 150 pixel then we will add the border border will be zero and padding of 10 pixel then margin 20 pixel Auto and zero border radius will be same which is 4 pixel and cursor pointer after adding this you can see this next button here but we have to move it in this Center so here we will add display block and now you can see it is horizontally centered right now this button is displaying so we have to hide this button and this button will be displayed once we will select any option from these answers so let’s come back and here we will add none so the button will be hidden you can see that button is hidden next we have to add the JavaScript to display the correct questions and we can select the answers so let’s come back back and here we will create a new file click on this icon and write the file name script.js this is the script file here we will add our JavaScript next we have to connect this script file with the HML so let’s come back and above this closing body tag here we will add a script tag script SRC equal to script. JS now our HTML file and JavaScript file are connected here we can add our JavaScript so in this Javascript file first we have to set the questions so here we will add const in this Con we will add the name of the variable so it is questions equal to here we have to add the questions so let’s add the first one like this question and write the question text then we have to add the options for this question so here we will add answers here I have added the first answer and correct is equal to false because it is a incorrect answer let’s duplicate it and we will add the other answers here and the second answer is correct so here we will add true so this is the first question and the list of answers now we’ll add the other questions in the same format so here let’s add one comma and we can add this second question here so you can just copy this one and paste here and update the text so I have updated all these questions and answers you can see in front of the correct answers I have added true and other are false here also I have added true and these three answers are false after that we will add another variables in this HTML file I have added this ID question and answer button and next button so we will add the variables for all these three elements so come to the script file here we will add const question element equal to document. get element by ID question which is this one next we will add the variable for this one duplicate this line add this ID here and here we will add the answer button now duplicate this and it will be next button and the ID which is next BTN now whenever we will start the quiz and give the answers the question number and the score will be changing so we will create variables to store the question index and score so here we will add let current question index so the index will start from the zero then we will add let score equal to zero next we will add one function and let me write the code then I will explain you here I have added one function start quiz so when we will start the quiz it should reset the current question index zero and score zero when we will start the quiz here we are adding inner HTML next because at the end we will change the text to the restart or replay so when we will start the quiz again the button should be next and after that we are calling this function so questions so it will set the index zero score0 and set the text next for the next button then only it will call the another function so question that will display the questions now we’ll create this function here in this so function I have added let current question equal to questions. current index so if you will see this list list of questions here we have the first set of question and answer then second then third and fourth so we will get the first question if we’ll add the index zero we will get the second question when we will add the index one so that is written here questions and index number so that will be the current question and we need the question number also so if the index is zero question number will be one if the index is one question number will be two so here I have added + one that will be the question number then in the question element which is this one this is the question element so here we will update the text with the inner HTML so we are adding question element inner HTML equal to question number then one dot and after that the current question and current question dot question so the current question will be this one and here we have the question this one so we will get this text so after adding this we have to display the answer from the current question set so here we will add the code to display the answers so let’s add current question dot answers dot for each here I have added current question do answers so it will come here suppose the current question is this one and it will go here answers and in this answers we have the text and correct so we have to display these text in the buttons so we will add document. create element and the tag name button so it will create one one button tag and we will save it as a variable called button and in this button we have to add one text so to add the text we will add inner HTML and in this inner HTML we will add the answer. text so answer is this one answer. text so it will add the first one then we will add the second one like that so it will add the text in the button then in the button we have to add one class name so we are adding button. class list do add and the class name BTN so it will add this BTN class name in this button after that we have to display this button inside the div which is here answer buttons this div is here so we have to display that button inside this div so we are adding answer button do appen child button so after adding this it will display the question with the question number and it will display the answer now we have to call this a start quiz function to display the output so let’s copy this one and add it here at the bottom start quiz so it will call this a start quiz function and it will set the current index z a score 0 and button text next then it will call the so questions and this so questions will display the question with the question number and uh it will display the answers in the button so after adding this let’s come back to the website and here you can see it is displaying the question with the question number one then we have the previous text that we have added in the HTML file which is Answer 1 2 3 4 then we have our answers that we have added with the variable here you can see the answers for the first question Sark blue whale elephant and jff so you can see these answers here but we have not added click function here right right now so now let’s come back and we have to hide these things to hide these things we have to reset the previous questions and answers so let’s come back and uh here we will add one function before displaying the question here we will add one function reset a state that will reset the previous question and answer now we have to Define this function so let’s add it here function reset state in this reset State let’s add the next button dot style do display it will be none then we will add while answer button it will will be buttons s and here also we will add buttons in this one so answer buttons DOT first child so suppose it has a child element then we have to remove that here we will add answer buttons dot remove child answer buttons DOT first child so it will remove all the previous answers and here also we have added answer button it will answer buttons yes answer buttons do app and child so after adding this let’s come back and here you can see the first question with the question number and list of options and if I click here nothing is happening next we have to add the click function on these answers so let’s come back here we will add button dot add event listener click and here we have to add one function name so when we will click on the answer button it will call this function select answer and before this click event we will add if answer dot correct so if it has some value then it will add button dot data set dot correct equal to answer dot correct so it will add the true or false in this data set correct from here this false true it will add in this button data set now we will add the function which is Select answer so let’s define this function above this a start quiz so here we will add function so when we will click on that uh button it will add the selected button element in this variable selected vtn and then it will check the selected vtn and data set true so if the data set is true then it will add the class name correct and if it is not true then it will add the class name incorrect now for these class name we have to add the background color so we will change the background color for the correct and incorrect class name so let’s come back to the CSS file here we will add correct and background in this background we will add one color code now we will add the background for the incorrect class name Incorrect and this background color after adding this let me come back to the website and if I click on the first one you can see the background becomes red because it is incorrect if I click on the second one you can see it becomes red because it is correct and if I click on the third one you can see it is red and the fourth one is red now we can click on any number of times so we have to disable the click after selecting one answer and when we will select the wrong answer it should automatically highlight the correct answer with the green color so to add that one let’s come back here in the subscript after that we will add so here we have added aray from answer buttons children for each so for each button it will check the data set if it is true then it will add the class name correct suppose we have selected the wrong answer then it will go and check the other answers and if it is true then it it will add the green color with this class name correct and after that it will disable the button so we cannot click on the any button and after that it will display the next button so here we are adding next button style. display block so it will again display the next button so that we can go to the next question so after adding this let’s come back to the website and if I click on the first one which is the wrong answer you can see the second one becomes green because the second answer is correct and it is displaying the next button and now we cannot click on the any other button let’s refresh the website and if I click on the correct answer it is displaying the green color here and now we cannot select any other next we have to hide the hover effect when we select the button so let’s come back and uh in this CSS file here we have added BTN hover so in this one we will add one more thing h and uh not disabled so the hover effect will work when the button is not disabled and when the button is disabled the hover effect will not work and we will add one more thing here we will add BTN disabled and uh cursor no drop after adding this let’s come back and refresh the website if I click here you can see we will not get the hover effect now and the cursor becomes red we cannot click on any button we can just click on the next button we have to add one more thing when we will select the correct answer the score should be increased so let’s come back and here we have added the class name correct in this one so here only we will add one more thing score Plus+ so it will increase the score by one next we will add the function for the next button so here we will add next button do add event listener and the event is click here we will add add a function and in this one we will add if it will check the current index if the current index is less than the length of the question it means the number of question is four then the question length is four so if the index is less than that then here we will add one function handle next button or else it will add a start quiz suppose if there is no question and we will click on that button so it will restart the quiz and here we have to Define this function handle next button so above this one here we will add function handle next button and in this one we will add current question index Plus+ it will increase the question index y1 when we will click on the next button and again we will add if current question index less than question length then so question function with the updated question index else it will display the score so score so if there is another question it will display the another question and if it is not there then it will display the score when we’ll click on the next button next we have to Define this function so cord so here let’s add function sour score and in this one let’s add reset state that we have already created to display the score we have to call this reset function and instead of question we have to display the score so we are displaying the question in the question element so in this one we will add inner HTML and let’s add the text in backtick here we will add us code so it will display the escore out of the length of question and after that we will add next button dot inard HTML equal to play again and uh next button will be block so let’s add next button do style do display block after adding this let’s come back to the website again and let’s select the correct answer next again correct answer next again we will click here next and here next you can see us code four out of four and we are getting the button play play again it will restart the quiz let’s click the wrong answer it will display the correct one let’s click next and wrong answer so we have selected two wrong answers let’s click again click here it is also wrong and if we click here on the correct one so you can see the score one out of four because we have selected only one correct answer out of four and we are getting play again so finally this quiz app is working you can update your question in this JavaScript and you can create your own quiz app or quiz website using HTML CSS and JavaScript in this video we are going to learn how to add the validation in contact form using JavaScript so here you can see I have created a contact form where you can see the input field for the name phone number email ID and message and at the end we have the submit button if I click on the submit button you can see it is giving an error name is required and there was one more error message at the bottom called please fix error to submit first we have to fix the error which is in the name field so here we have to enter the name because right now the name field is empty so let’s add anything here if I write like this still we are getting an error write full name because we have to add the first and last name so let’s add a space and write full name like this now you can see a green check icon that means this input field is correct so after adding the correct data in this name input field let’s click on the submit button again so it is giving error in the phone number field and here it is saying phone number is required so let’s add some characters here if I write like this it is saying phone number should be 10 digits so let’s add any 10 digit number here so so now you can see check mark it means this input field is correct after that if I click on the submit button again it is giving an error in email field so here also we have to add the email ID so let’s add the email ID like this so right now this is not the correct format so that’s why it is saying email invalid so we have to add the email in proper email format so if I write like this now you can see a check mark let’s click on the submit button again and it is giving an error 30 more characters required because we have added the limit minimum 30 colors should be there in the message box so here let’s add any message you can see as I’m writing the text here it is decreasing the required character right now it is saying 16 more characters required after writing minimum 30 characters in this message field we will get this check mark now we can submit this form so let’s click here and you can see it will submit the form so without collecting all the fields this form will not be submitted and once we will collect all the input fields and click on submit button this form will work so we will learn how to add this validation in form using JavaScript now let’s start this tutorial to add validation on contact form using JavaScript I have already already created multiple tutorials about creating a contact form using HTML and CSS that’s why in this video I’m not going to design this form you can go to the video description and download this HTML and CSS form and in this video we will only talk about the validation so let’s come back to the folder and here you can see I have this HTML and CSS file that you can also download from the video description once you will open these files with the code editor you will see this HTML file where I have added the container and then we have the form tag and in this form we have added this icon and here we have added the font awesome link that’s why we have added this font awesome icon then we have the input group and in this one we have the input field for the name this is for the phone number this is for the email and this one is for the text box and after that we have the button and you will get this CSS file also where we have added all the CSS for the design of the form once you will open this HTML file with B browser you will get this form like this next we will display the error message on this form so let’s come back to the code and here you can see we have added the input field for the name so just below this input field we will add one span tag and in this span let’s add one ID also so I will add the ID name error and in this name error let’s add a error name is required like this simply we will add the span tag in all the input group just below the input field so here also we will add this fan tag and this is for the phone number so we will add the ID phone error and here also one message phone is required let’s copy this one and add it just after this input field for the email here we will add the ID email error and we will add the message email is required and uh after that we will add one span here this is for the message error message is required like this and uh we will add one message after this submit button also so here also we will add a span and we will add the ID submit error and one message please fix error so we have added these error message in this HTML file and let’s refresh our website and now you can see these message here at the end of all the input fields and one error message at the bottom left corner of this form so we have to change the position and color for these error message for that we will come back to the HTML file and here you can see we have the class name called input group and in this input group we have the span tag where we have added the error message so let’s add this class name in the CSS file and here we will add the span and for this aspan we have to set the position Position will be absolute then we will add the bottom bottom will be 12 pixel and right 17 pixel we will add the font size it will be 14 pixel and color so the color will be red because it’s an error so you can see the position has been changed for these error message we have to add the Cs for this one also which is for the submit error let’s come back and here you can see we have added the ID called submit error so let’s copy this ID write it here with the hashtag because it is an ID and here we will add color red that’s it so this message is also in the red color so we have added the position and color for the error message but right now this message is displaying by default but we have to display this message after validation using JavaScript so we will remove these error messages for now and it will be displayed later let’s come back and come to the HTML file and just remove this message span tag will be there we have to remove the message only let’s remove all the error message like this it’s done again you can see the simple contact form now we have to add the JavaScript file so here we will create a new file go to files new file and uh save this file as uh script.js make sure the file name should be JS so we have created a new file and uh next we have to come to the HTML file and just at the bottom before this closing body tag we will add a script a script open and closing tag write SRC and write the file name that we have just created which is script.js so it will connect the Javascript file with the HTML file next we have to add the variable for all these ID that we have written here in this HTML file so let’s come to the script file this is the script.js and here we will create variable so let’s add where name error equal to document dot get element by ID and in this ID we will add the ID that we have added in the HTML file so you can see we have added the ID called name error just copy this one and place it here so this is the first variable just duplicate this one and change the name it will be phone error this is for the email error this is message error and this one for the submit error and here also we will change the ID so we have added these variables next we have to add the function that will validate the input box so let’s come back to the stml file and here we have the input field for the name in this one we will add one ID so let’s add one ID called contact name and we will add one event so it is on key up on key up equal to and here we will add one function name so let’s add any function name validate name like this so here we have added one ID and one function next we have to Define this function that we have added here so just copy this function and come to the script file here we will add function write the function name like this so this function will be executed whenever we will start typing anything in the input field so here we will add one variable and write name equal to document Dot get element by ID and in this ID we will add the ID that we have just created which is contact name copy this one add it here at the end we will add dot value so this variable called name Will store the content written in the input box which is for the name so it will take the value of the input field and now we will add the condition so here we will add if name Dot this will check whether this name length is zero it means the input field is empty so it will display an error called name is required and where this error message will be displayed it will be displayed in the variable called name error and this name error is for the ID called name error that we have added here in this span tag so in this span tag we will see this message called name is required when the length is zero it means the input box is empty next we will add the another condition here we are adding this condition so this expression is exactly checking the first character should be alphabet and after that there will be one space and after that it could be any character A to Z here we are adding exclamation it means value is not matching with this expression then it will give an error so what will be the error just copy this one paste it here and here we will add write full name like this and one more thing once it will give an error it will return false like this and we will add this return false in this if condition also so whenever there will be an error it will return false in this condition also if it will give an error it will return false if there is no error then what will happen it will display a success message so let’s add name error dot inner HTML equal to and in this one let’s add valid like this Suppose there is no no error then it will say valid and then it will return true like this it is not and it will be a dollar sign like this so again refresh the website and you can see if I write a first name and write anything in the second name it will say valid you you can see the message has been changed to valid so instead of valid we want to display a check sign so you can see in the HTML file we have added this font awesome link so we can add the font awesome icons so let’s come to the font awesome website here we will search for one icon so let’s go to the icon and search for check we’ll click on this one check Circle copy this and come back to the script file and in this script instead of this valid we will add this HTML code like this and we will change the color also so it is in the it tag you can see it is in the it tag so we have to use this it tag in the CSS file just come to the CSS and copy this input group span and uh in this Supan we have the it tag for the icon and here we will add the color so let’s add the color of this one after adding this color come to the web page and here we will add one name now you can see a green color of check sign so it is working fine next we will add the validation for the phone number field so let’s come back again come to the HTML file and as you can see we have added the ID in the name field and one function so same thing we will do in the phone number field so just copy it here so this is for the phone number field so it will be contact phone ID is contact phone and here we will add validate phone like this come to the script file and let’s copy this one paste it here instead of validate name we will add validate phone this is for the phone number validation and again we have to add the variable so let me just copy this one only paste it here it will be phone equal to document. G by ID contact phone ID is contact phone so this phone will store the value written in the phone number input field next we have to add the condition to check the phone number so here let me write the condition then I will explain to you so you can see here we have added phone. length equal to Z so it will check whether the phone number field is empty then it will display and eror phone number is required next it will check the length of the phone number if it is not equal to 10 then it will display an error phone number should be 10 digits in this condition it is checking the phone num should be 0 to9 and for 10 characters and if it is not like that then it will display an error called only digits and if there is no error like this then it will display a check icon and it will return true so after adding this let’s check the phone number field come back to the web page and here if I write you can see phone number should be 10 digits so let’s add more digits and now you can see a check icon you can see if I add any character like this Zed y anything it is saying only digits please so we need to add digits and if we add 10 digits it is fine so this phone number validation is also working now let’s come back and we will add the validation in this email field so let me just copy this one and paste it here in this email input field write the ID contact email and this is validate email next we will add the script so let’s copy this one it will be validate email then copy this paste it here it will be email document. get elment by ID contact email so it will store the value written in the email input field and now we will check the conditions for so in this validate email function we are adding this variable that will get the value of the input box and then it will check the length if it is zero it means it is empty so it will display an error email is required and return false next if there is some value then it will check this condition and here it is saying it should be any alphabet it may contain a DOT or underscore or the siphon and it can also contain any number and after that there should be one at theate after at theate there will be some alphabets and then one dot and after that dot there will be another alphabet it could be 2 three or four characters so if the email format is not matching with this one then it will display an error called email invalid and return false and if there is no such error then it will display the check icon and return true here we will remove this and save this file let’s refresh the website again and if I write uh correct email here now you can see it is displaying a check icon it means the email ID is valid next we have to add the validation for the message box let’s come back and here we will add one ID and one function copy and paste it here write the ID called Contact message and this is validate message now let’s come back to the script file and copy this one here we will add validate message and in this one again we will add one variable so it will store the value written in the message box and after that we will add one variable where we will add any number required equal to so if we want 30 characters then we will add 30 characters is required and here let’s add another variable and it is left left equal to required minus message do length so it will give the value how much characters is left and now we will add the condition if left greater than zero it will be giving an error message message error dot inard HTML and then it will return false and if there is no such error and the character is more than 30 then it will display a check sign just copy this one paste it here and here we will add message error. innerhtml that’s it here it will be this one message refresh the website and now you can see if I write something 29 more characters required if I delete this one it will display 30 more characters required and if we write some text here and now you can see the error message has gone and we will get the check icon so this message box validation is also working fine next we have to add the validation when we will click the submit button so let’s come back in this button we will add onclick and here let’s add return space and one function validate form next we have to Define this function called validate form in the JavaScript so let’s copy this one come back to the Javascript file and here we will add a function validate form and in this one first it will check all the functions that we have added in the different input field so here we will add if exclamation validate name then we will add exclamation validate phone in the series wise we are adding so this condition we check if any of these are false then it will display an error message so here we will add submit error dot inner HTML and one message like this and after that it will also return false after adding this again refresh the website and simply click on the submit button and you can see here it is displaying please fix error to submit so M submit but right now this error message will be displayed continuously so we have to hide this message after a few seconds so let’s come back and here we will add submit error dot style do display it will be block so it will be visible and here we will add set timeout display none so after 3 second it it will hide the error message which is please fix error to submit so this message will be displayed for 3 second and after 3 second it will be hidden because we are adding display none in the set timeout and it will return false so it will not submit the form so let’s check this one and if I click here you can see this message will be hidden after some time you can see this message is hidden so this complete form is working fine right now let me check check all these input field and if I write a name here then we will add one phone number and any email ID and message after collecting all the input field if I click on sub MIT it will submit the form successfully without any error message so it is working fine so we have completed this form validation using JavaScript in this video we are going to learn how to create an image gallery that will slide horizontally using Mouse wheel usually when we rotate the mouse wheel the web page scroll down or a scroll up but if I take cursor over this image gallery and rotate the mouse wheel it will scroll the gallery horizontally either in the left side or right side in this image gallery we have added two control icons also that is for the backward and forward we can click on these icons to scroll the gallery to the left side or right side we have added one more effect if I take cursor over this image you can see the image becomes colorful all the images are gray right now when we take cursor it becomes colorful and you can see the image size is also increasing when we take cursor so we will create this horizontal scroll with mouse wheel using HTML CSS and very simple JavaScript this will be very good JavaScript mini project for your resume now let’s start the video here I have this folder and in this folder I have one HTML file one CSS file and another folder called images and here you can see some images and two icons you can find all these images download link in the video description now I will open these files with my code editor which is Visual Studio code so this is the HTML file where I have added the basic HTML structure and this one is the CSS file in this HTML file I have added this title then this link tag that will connect the CSS file now we will add the code within this body tag so here we will create one div with the class name gallery and within this Gallery we will create another div and in this div we will add span and inside this span we will add the first image with the IMG tag here we will add the file path of the image it is images / image1.png Let’s duplicate this line and we will add the another image image 2 and three after that let me open this web page with browser so you can see three images on this web page now let’s come back and here we will copy this class name and come back to the CSS file here first we will add the Cs for the body and here in this body we will add the background after that add that class name Gallery here we will add the width it will be 900 pixel and display Flex after that we will add gallery and div for this div let’s add the width of 100% display grid and grid template column Auto auto auto so we will get three image in one row after that we will add grid gap of 20 pixel and padding of 10 pixel then we have the IMG tag so here we will add gallery div and IMG width will be 100% for the image now you can see perfect size for these images next we will add three more images so let’s come back and duplicate this div and replace the image file name it is 456 so we have total six images you can see the images size becomes small so let’s come back and here we will add Flex none now you can see it is perfect size for the image and you can see the horizontal scrolling here the complete website is scrolling so let’s come back and uh here in this Gallery we have to add overflow X scroll now only this Gallery will scroll the gallery width is 900 pixel and it is scrolling inside that div next we have to hide this horizontal scroll bar so let’s come back and here we will add gallery and webkit scroll bar display none so that horizontal scroll bar is hidden but we cannot scroll it with the mouse wheel so let’s come back and uh Above This Gallery we will add another div with the class name Gallery WAP and in this one we will add one image and file name back do PNG then another file name next. PNG here we will add ID back BTN and next vtn and let’s remove it and add it here within these images so first we have the back arrow then all images and again next Arrow you can see the back arrow at the top and the next Arrow at the bottom here we will add gallery W display Flex align item Center and justify content Center then we will add the margin of 10% Auto you can see it is horizontally centered now just come back and copy this ID back vtn then next vdn we are adding hashtag because it’s an ID here we will add the width 50 pixel cursor pointer and margin 40 pixel now the size for the icons are perfect next we will add the hover effect on these images so let’s come back and here we will add gallery div IMG and hover and uh let’s add filter gray SK zero the G scale will be zero and come here and we will add cursor pointer and transform scale 1.1 so it will increase the size just copy this filter gray scale and add it here and let’s add 100% so the default gray scale will be 100% so the image will be gray let’s add the transition transform 0.5 seconds so it will take5 seconds to increase the size you can see the size is increasing and the image becomes colorful when we take cursor so we have added the hover effect after that we have to enable the horizontal scroll using Mouse wheel so just come back and here above this closing body tag we will add a script tag in this script tag we will add the JavaScript so here we will add let scroll container equal to document dot query select and we will select this one do Gallery so we are selecting this class name after that we will add let back vtn equal to document. get element by ID because we have the ID here back vtn so write it here now duplicate this line and it will be next vtn so we have selected the gallery div then next vtn and back vtn after that let’s call copy this one add it here here we will add add event listener and it will be wheel so it is wheel event then we will add this Arrow function and when we will rotate the wheel this function will be executed so here we will add EVT do prevent default it will prevent the default feature that scroll the web page down or up next we will add the scroll container scroll left plus equal to EVT dot Delta y after that come back to the website and if I take cursor over this image and rotate the mouse wheel this slider is scrolling we can scroll in the left direction or right direction you can see this image gallery is scrolling horizontally with the mouse field now we will add the click feature on this back arrow and next Arrow so let’s come back and hit we will add next BTN do event listener click because we will add the click function here also we will add the arrow function and this function will be executed when we will click on the icon here we will add scroll container do scroll left plus equal to 900 because the width is 900 for the gallery again duplicate it and here we will add back BTN and it will be minus equal to 900 that’s it after that let’s come back and if I click on the back button it is a scrolling the gallery to the left side and if I click on the right button it is a scrolling the gallery to the right side but when we click on these icons it immediately scroll it by 900 that’s why we cannot see the scroll animation so let’s come back and here we will add scroll container dot Style dot scroll behavior and we will add the scroll Behavior smooth let’s copy it and paste it here same thing now just come back and if I click here you can see it will scroll smoothly you can see this Gallery is scrolling horizontally when we click on these next or previous button and we can scroll it using the mouse wheel also but you can see this mouse wheel scroll is not smooth right now so let’s come back and uh here copy and paste it in this V event and here we will add Auto that’s it after adding this let’s come back now if we rotate the mouse wheel this Gallery is scrolling smoothly and when we click on the icon here also it is scrolling smoothly and we have the hover effect also so finally we have completed this beautiful image gallery that scroll horizontally using the mouse wheel in this video we will learn to make a digital clock using JavaScript let’s check the current time in my laptop at the bottom right corner so the time is exactly same as the time displaying on my website we will Design This digital clock using HTML and CSS then we will update the local time using JavaScript this is very useful JavaScript project for your job portfolio so let’s start to make this digital clock using JavaScript a step by step here I have this folder and in this folder I have added one index.html file one style. CSS file let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added the margin padding font family and box sizing these CSS properties are applicable for all the HTML elements in this HTML file I have added this title digital clock using JavaScript e tutorials and then I have added this link tag that will connect the HTML and CSS file because here I have added hdf style.css now we will add the code within the body tag so so here let’s create one div with the class name hero and now we will add the CSS for this class name write this class name here in this CSS file and here we will add the width height main height will be 100 VH then we will add the background and in this background we will add the linear gradient color here we will add one angle and two color code then we will add the color this will be the white color and let’s add the position relative after adding this let me come back to the folder and open this HTML file with any web browser so you can see this gradient color on the complete web page let me close this browser and I will open it with the visual studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file and save the code file so you can see the same web page again with the gradient color now let’s come back and within this div with the class name hero here we will create another di with the class name container inside this container we will create another with the class name clock and in this clock let’s add the time like this save this and open the web page you can see this time here at the top left corner 0 so let’s add some CSS let’s come back and here we have the class name container just add it here in this CSS file and here we will add the CSS for this content container we will add the width it will be 800 pixel and then we will add the height height will be 180 pixel after that we will add the position absolute top 50% left 50% and transform translate – 50% and – 50% so that this element will be in the center of the web page for now here we will add one background so let’s add the background red and open the web page so you can see this red color of box in the center of the web page now we’ll remove this color let’s come back to the HTML file and here we have the class name clock so let’s add the CSS for this clock here we will add the width and height 100% after that we will add the background and in the background we will add some color with less opacity so we will add rgba so this is the color code for the background then we will add the Border radius of 10 pixel and uh let’s add display Flex align items Center and justify content Center so that the text inside this clock will be in the center and after that come back to the web page you can see this color in this box now we will add two other elements that is a square and circle so let’s come back we will add the element with the help of cudio elements so here in this container we will add two cudio elements which which is before and after so add this container then write double column before and in this before we will add content content will be empty then let’s add the width and height width will be 180 pixel and height also same 180 pixel then we will add the background here we will add one color code then border radius will be 5 pixel very small and Position will be absolute left Min – 50 pixel and top also Min – 50 pixel then right Z index minus one after adding this you can see one element at the top left side of this horizontal box now we will create another element that that will be one Circle so let’s come back and duplicate this one here we will add after this is same content width height and we will change the background color and here we will add border radius of 50% so that it will be a circle Position will be absolute and here it will be on right side so right minus 30 pixel and it will be at the bottom so write bottom minus 50 pixel that’s it now you can see one Circle in the right side next we have to make this horizontal box blur so let’s come back and here we have the clock so in this clock we will add backdrop filter blood it will be 40 pixel after that you can see the web page it looks good next we have to change the size for this text and we will add the name also like minutes second hours so let’s come back and uh here let’s remove this one instead of writing the text directly we will add one span tag and in this span first we will add 0 0 Let’s duplicate it here we will add the column after updating this you can see again it is same we have just added the span tag for each number let’s come back here we have the span inside this clock so come to the CSS file let’s add dot clock and a span so for each a span we will increase the font size so let’s add the font size 80 pixel we will add the width 11 10 pixel and uh display will be inline block and text align Center and P relative after that you can see some space between these numbers and the font size is also increased next we will add the name like hours minutes and seconds so let’s come back to the code again and let’s copy this clock span and write the sudo element after and this after let’s add the content in this content it will be empty font size 16 pixel position absolute bottom – 5 pixel and left 50% transform translate x – 50% in this content we can add the text so let’s add ours it will be 16 pixel PX and after applying this you can see we have the text here hours hours hours like this and we have to remove this hours and it will be different in the first one we will add hours then minutes and seconds to change this one we will come back to the the HTML file and in this HTML file let’s add some IDs in the first span we will add the ID HRS for the RS then in the second number here we will add ID Min n that is for minutes and in the last one we will add the ID SEC for the seconds and let’s come back to the CSS file and remove this content from here remove this and here at the end we will add that ID like HRS and here we will add sudo element after write content ours duplicate this line it will be minute and second and here also minutes and seconds after adding this let’s come back to the website so you can see in the first number we are getting hours then in the second one minutes and last one seconds next we have to update the time and uh to add the current time we need to add the JavaScript so let’s come back to the HTML file and here at the bottom just above this closing body tag we will add a script open and closing tag and within this script we will add all our JavaScript code so here we will add let HRS equal to document. getet element by ID and the ID is HRS that is from here let’s duplicate it it will be minute and second to get the date and time we need to use the JavaScript object called date so here let’s add let current time equal to new date and if we print this current time let’s add console.log current time you will see the local time and date let’s come back to the website and open the console here you can see it is displaying Tuesday May 30 2013 and this is the time so it is our local time now we have to get the time only we have to remove the date and day so let’s come back here you can use the JavaScript methods get hours get minutes and get seconds to get the hours minutes and seconds from this time so let me show you here we will add current time dot get ours and open the web page you can see it is displaying the hours 15 if we come back and add get minutes it will display the minutes in current time 37 and like that we can get the seconds also so let’s display all those things here we will add HRS do inner HTML equal to current time dot get hours so it will display the hours of current time duplicate this it will be minutes Min and it will be seconds second and here also we will update the methods get minutes and another method called get seconds so after updating this let’s come back to the website you can see the current time here which is 15 38 and 39 let me show you my laptop current time it is same 1538 but you can see this time is not updating so we have to update it it at every second for that we will use the set interval so let’s come back and we will add all those things in a set interval here we will add comma 1000 milliseconds that means 1 second and and within this we will add all these code so it will execute this code at every 1 second now just come back to the website again and you can see this seconds is increasing and this minute is also increasing right now it is displaying only one digit so suppose you have the numbers less than 10 we can add one zero in front of that number for that let’s come back to the JavaScript again and here we will add one if condition so we will add the inline if condition copy this and here we will add plus this one and here we will add the condition if less than 10 if it is less than 10 then it will add one zero or if it is not less than 10 then it will be empty like this so we have to add the same thing in the other one here and here and update the methods it will be minutes minutes and seconds after updating this let’s come back to the website again and finally you can see it will display the double digit in the numbers now you will see it is starting from 0 1 02 03 like that so finally we have completed our digital clock using HTML CSS and jav JavaScript in this video we will create a product page design that you can use on e-commerce website here I have added a product image on the left side and product details on the right side in this product image we have some control buttons when I click here you can see the product image is changing in the product detail section you can see the product name price and offer after after that we have some select option for variable products we can select the size and color of the product then we have input field to select the product quantity and at the bottom you can see by now button we will create this product page design using HTML CSS and JavaScript here in this folder I have created one index.html file one style. CSS file and you can see another folder with some images you can find all the images download link in the video description let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added basic HTML structures and this one is the CSS file and I have connected this CSS file with this link tag in the HTML file now we will add code in the body tag so here we will create one dip with the class name container in this container we will create another div and let’s add the class name product in this product we have to create two columns so first we will create the left TI with the class name Gallery where we will add the product image gallery and let’s add another div with the class name details where we will add the product details like product title description and buttons next we will add the image in the first div which is image gallery so here we will add one IMG tag write the file path of the image so this is the images / image 1.png after adding this let’s come back to the folder and open our HTML file with any web browser so you can see this image on the web page let me close this browser and I will open this browser with the visual studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file and save the code file so you can see the same B page page again now let’s come back and we will add the CSS so let’s copy this container write it here in the CSS file here we will add some CSS properties like width then we will add Min height then we will add the background in this background we will add one color code let’s add the display Flex align items Center justify content Center so that the product will be in the center of the web page let’s copy this class name product write it here so for this product we will add the width it will be 90% and maximum width will be 750 pixel then we will add display Flex so left and right column will be side by side now we will add the CSS for this gallery and details so let’s add this Gallery here so for this Gallery we will add Flex basis 47% it means width is 47% after that we will add the background so this is the color code now in this Gallery we have one image so again write this one then write IMG tag so for this image we will add the width it will be 100% and display it will be block let’s add some padding from the top 100 pixel and after adding this again refresh the website you can see this image on the web page next we will add the CSS for the right column which is details so here we have details just copy this one write it here in this CSS file so for this one we will add the flex bases 53% it is width 53% so now we will add the background it is white and we will add some padding it is 40 pixel and let’s add the padding from left side it will be 60 pixel now you can see this white color in the right side and in the left side you can see this image now we have to increase the size for the left one so here in this Gallery we will add transform scale 1.08 so it will increase the size let’s add the Box Shadow also so here we will add box Shadow next we will add the same box shadow in the second column which is details so just copy this one and paste it here after adding this let’s come back to the website again you can see the size for the left column is increased and you can see the shadow also now we will add some details in the second column so here in this second div we will add space and here we will add one title in H1 it will be the name of the product casual t-shirt next we will add another text in H2 so it will be the price of the product again we will add H3 and here let’s add the discount 30% off after that we will add some description in P tag so this is the description after adding this you can see this title and description on the web page so we have to design these things so just copy this class name details WR it here and here in this details we have the first title in H1 so for this H1 we will add this color code and we will add the font size you can see different size for this text again write this class name then write H2 for the second Title Here we will add another color and font size it will be 30 pixel and we will also change the font weight 600 let’s add this class name again and here we will add H3 for the discount so in this one we will add color and margin from the bottom to add some space at the bottom so you can see these titles looks good next we will add the CSS for this description for that we will come back back and here in this details here only we will add font size it will be 13 pixel and we will change the font weight let’s add the color after adding this this description is also looking good next we have to add some radio buttons where we can select the size and color so let’s come back and after this P we will add one form tag and in this form we will add one div so let’s add the div with the size select and in this size select first we have to add one text in P tag it is size then we will add one label in this label we have to add the four it will be small and inside this label we will add one input field so in this input field input type will be radio so it will be a radio button then we will add the name let’s add size and in this ID we will add the same thing which is here for this ID and for should be shame after that we will add a span and in this span we will add s s means small let’s duplicate this label and change the ID and for so this will be medium and here also medium this will be M duplicate again and write large and ID also large and a span L again we will add this one then right extra large for Excel let’s duplicate again and this is the last option dou x large double XL after adding this again refresh the website you can see this text size then we have the radio buttons for SML Xcel and double XEL you can select these radio buttons now let’s come back to design this one we will copy this form here we will add details form so for this form we will add the font size it will be 15 pixel then we will add the font weight then we have the size select so let’s copy this one write it here size select in this one we will add display Flex so that the text and radio buttons will be in the same horizontal line aligned items will be Center and some margin from the top to add some space again copy this one here we will add P so for this P tag we will add the width it will be 70 pixel now you can see this size here then we have some space and after that these radio buttons and text next we have to change the color of these text which is SM L XL so let’s come back and copy this one here we will add input then checked so if the input is checked we have to change the color of the span text so here we will add plus span and color we will add this blue color and we will also increase the font weight it is 600 so you can see when I select any radio button the color for the label text is changing and the font weight is also changing next we have to hide these radio buttons there will be only text copy this size select input and just add display none so it will be hidden you can see we have only text here and we can click over these text to select any radio button that is invisible so again come back here we will add site select then a span so for this span we have to add some space so first we will add some padding then margin from the right side and we will add the cursor pointer so it looks good and we can click on any text to select this one and the color and font weight is changing when we select any size so we have completed this size select let’s come back and after closing of this div which is for the size select or you can add it here just above this closing form tag here we will add one div with the class name color select where we will add radio buttons to select the color so in this one again we will add text in P tag it is color then we will add label for let’s add red color and in this for again we will add input input type will be radio then we will add name in this name we will add color and let’s add the ID red for and this ID should be same after that again we have to add one span and in this span we will add one class name so it is color one after adding this let’s duplicate this complete label total we have four colors so let’s change the color it is green and here also green and in this span we will add the class name color two now for the third one we will add blue and ID also blue this is color three now for the fourth we will add for pink ID pink and class name color four after adding this let’s refresh the website again you can see this color and then we have four radio buttons now we have to align all these in same horizontal line so again come back let’s copy this class name color select write it here in the CSS file and for this color select we will add display Flex then align items Center and some space from the top again WR this class name and in this one we have P tag so we will add width 75 pixel you can see it is in the same horizontal line we have some space after this color next we have to add different color with the each radio buttons so let’s come back and in this CSS file we will add this class name again then write span so for this span let’s add display it will be inline block then we will add width and height it will be 15 pixel after that we will add border radius it will be 50% so that it will be a circle after that we will add some spad so we will add margin right 15 pixel and cursor will be pointer now we have to add different color in each as span so we have added class name color 1 2 3 4 so for all these span we will add different color so here we will add color one and write background it will be R let’s duplicate it and we will change the class name color 2 3 4 and for all these class name we will add different color now we have added different background in all the span again refresh the website and here you can see we have different color circle with the each radio buttons next we will hide these radio buttons only color will be visual so let’s come back and copy this class name color select then input here we will add display none that’s it so it will be hidden you can see we have colors here now we have to select the color so let’s come back and here we will add color select input checked so whenever the input button is checked we will Design the span so here we will add plus a span transform scale 0.7 so it will reduce this size size then we will add box shadow in this Shadow we will add two Shadow this will be in the white color and again we will add the same thing let’s add a comma and write another Shadow so here we will add black color and it will be 6 pixel so after adding this again refresh the website and you can see see when we click on any color there is one circle around it so this select option is working next we will come back to the HTML file and here before this closing form tag here we will create another div with the class name quantity select inside this div we will add one title in ptag it is quantity and again we will add one input field and input type will be number and value it will be one after adding this let’s refresh the website you can see this quantity and this input field with the value one and we can increase and decrease this value with these Arrow let’s come back and copy this class name quantity select write it here in the CSS file here again we will add display Flex align items Center and some space so margin top 20 pixel WR this class name again then write p and for this P we will add width it will be 75 pixel you can see it is in the same horizontal line next we will Design This input field let’s come back and here we will add quantity select input so for this input field we will add the background this is the color code for the background then we will add border it will be zero and outline it will be zero let’s add some padding inside this input field then we will add width it will be 50 pixel and B radius it will be 12 pixel you can see this input field looks good we can increase and decrease the value by clicking on this up and down buttons after adding these input fields we will add one submit button or a buy button let’s come back and just above this closing form tag we will add one button and button text will be by now you can see this button here next we will Design This so let’s come back to the CSS file here we will add form button in this button we will add the background this color code then we have to change the button text color after that increase the font size of this button text then width it will be 100% and some padding it is 10 pixel and Border radius will be 30 pixel after that we will add border zero and outline Z then we will add margin from the top to add some space from the top and box Shadow here we will add this box shadow then cursor pointer after adding this again refresh the website and you can see this button looks good so we have added all the contents in the product detail section now we will add controls option in the gallery where we will click and change the gallery image so let’s come back and in this Gallery after this image we will add one div with the class name controls inside this div we will add three asan and with this span we will add the class name BTN just duplicate it so we have three span here with the class name BTN next we have to design this one so copy this class name controls write it here in this CSS file here we will add position Position will be absolute then bottom it will be 40 pixel and right it will be 20 pixel so this control buttons will be in the bottom right side of the gallery here we will add BTN so for this span we will add display block and we will add the width and height 10 pixel then we will add border radius 50% so that it will be one small circle then we will add the background so in this background we will add the color code in RGV it will be white colored with 50% opacity then we will add some margin and cursor it will be pointer so here in this controls we have added position absolute so we will add position relative in this gallery you can see we have added Gallery over here at the top so in this one we will add position relative so this control buttons will be in the gallery only after adding this position relative again refresh the website and you can see these three Circle in this product Gallery next we have to add one color in the first one so it will look active so let’s come back and here in this first button we will add one one more class name active after adding this let’s come back to the CSS file at the bottom we will add BTN do active and here just we will change the color let’s add the background and this color code after adding this again refresh the website you can see this blue color in the first dot next we have to add the click function whenever we will click on any other dot the image should change so for that we will add the JavaScript so let’s come back and here in this HTML file we have to add the click feature on this span where we have added class name BTN and we will change the image in this IMG tag so here in this IMG tag we will add one ID also so let’s add the ID product IMG after adding this let’s come back at the bottom just above the closing body tag here we will add a script tag where we will add the JavaScript inside this we will add let product IMG equal to document. get element by ID and you already know the ID which is product IMG next we will add the let BTN equal to document Dot get Elements by class name because we have added the class name BTN in all the span after that we have to add the click feature on the button so here we will add BTN 0. on click equal to function and inside this function we will add the product img.src because we have to change the image so let’s add product img.src equal to the file path of the image so let’s come back to our folder you can see we have one folder called images and inside this folder we have the image called image 1.png 2.png and image 3.png so this is our file path so let’s come back and here we will add images SL image 1 do PNG so this is the first image after adding this let’s duplicate this one and here we will add BTN 1 and BTN 2 for the second button and third button and we will change the image also it is image 2.png and image 3.png after adding this let’s refresh the website again and if I click on the second button you can see the image is changing if I click on the third one image is changing right now the image is changing when we click on these dot but the color is not changing for the dot which is active so we have to change this one we have to change the active color for the circle so let’s come back and here we have added the class name active so we have to remove this class name through JavaScript and this class name will be added in the particular Circle where we will click to remove remve this one we will add for BT of BTN bt. classlist do remove and inside this remove we will add the class name which is active so it will remove the active class name from all the circles so after removing the class name we have to add this class name on the particular Circle where we have clicked for that here we will add this do class list do add and the class name which is active so first it is removing the class name from all the circle and adding the class name on the particular Circle let me copy this one and add it in all the function just copy and paste in the second and third one that’s it again refresh the website and you can see if I click on any Circle the image is changing and the color is also changing when we click on the second one the second Circle becomes blue when we click on the third one then third circle becomes blue so finally we have created this image gallery and product description for this product page I hope this JavaScript course will be helpful for you if you have any question you can ask me in the comment section please like and share this tutorial and also subscribe my channel greatest Tech to watch more videos like this one thank you so much for watching this video

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • Learn Git – The Full Course

    Learn Git – The Full Course

    The source provides a comprehensive guide to using Git for version control, aimed at both beginners and more experienced developers. It covers fundamental concepts like repositories, commits, branching, merging, and rebasing, emphasizing practical workflows and best practices. The material explores advanced topics such as resolving conflicts, stashing changes, and using git bisect for debugging. Furthermore, it explains the importance of clean commit history and strategies for achieving it, including squashing. Finally, the lesson introduces worktrees and the power that git has to offer.

    Git Mastery: A Comprehensive Study Guide

    Quiz

    Instructions: Answer the following questions in 2-3 sentences each.

    1. What was the primary motivation behind Linus Torvalds creating Git, and how long did it take him to develop the initial version?
    2. Explain the difference between “porcelain” and “plumbing” commands in Git, providing an example of each.
    3. Describe the three primary states a file can be in within a Git repository.
    4. Why is it important to stage changes using git add before committing them?
    5. Explain why Git is considered a “distributed version control system” and what a “remote” repository is in that context.
    6. Explain how Git optimizes storage despite storing complete snapshots of files with each commit.
    7. What is the purpose of the .gitignore file, and how does it help manage a Git repository?
    8. Explain the difference between git reset and git revert in terms of their impact on the repository’s history.
    9. Describe the purpose of git rebase and how it differs from git merge.
    10. Explain what a Git Tag is and how it’s different from a branch.

    Quiz Answer Key

    1. Linus Torvalds created Git in response to a license dispute with BitKeeper. He created the original version of Git in just five days after Linux lost access to bitkeeper.
    2. “Porcelain” commands are high-level commands used for everyday tasks like git commit, while “plumbing” commands are low-level tools for internal operations, such as git hash-object. Porcelain is what you will use 99% of the time.
    3. A file can be in one of three states: untracked, staged, or committed. Untracked files are not known to Git, staged files are ready to be committed, and committed files are part of the repository’s history.
    4. Staging allows you to select specific changes for a commit, rather than including every modified file. The index is the name for the staging area.
    5. In a distributed version control system, every user has a complete copy of the repository, which is called a “remote.”
    6. Git uses compression and de-duplication to optimize storage. Git compresses each commit to make it smaller and de-duplicates files that are the same across commits.
    7. The .gitignore file specifies intentionally untracked files that Git should ignore. This helps prevent unnecessary files, such as build artifacts or temporary files, from being added to the repository.
    8. git reset moves the current branch to a previous commit. It essentially throws commits away. git revert creates a new commit that undoes the changes of a previous commit, preserving history.
    9. git rebase moves a branch onto another branch, rewriting the commit history. It’s usually good to use git rebase in a private local branch.
    10. Git Tags are immutable pointers to a specific commit. They’re often used to mark release versions.

    Essay Questions

    Instructions: Answer the following essay questions in a well-structured format with supporting evidence from the source material.

    1. Discuss the significance of understanding Git’s underlying plumbing and porcelain commands for effective version control. How does knowledge of both aspects contribute to a developer’s proficiency with Git?
    2. Explore the workflow of Git from modifying a file to having it reflected in the remote repository.
    3. Analyze the various methods of undoing changes in Git, such as reset, revert, and reflog. How do these commands differ, and in what scenarios is each most appropriate?
    4. Explain the relationship between Git and GitHub, clarifying the distinct roles and functionalities of each. How does GitHub enhance collaboration and version control for software development teams?
    5. Describe and contrast different strategies for merging changes in Git, including merge commits, rebasing, and cherry-picking. What are the advantages and disadvantages of each approach, and how do they impact the commit history?

    Glossary of Key Terms

    • Git: A distributed version control system for tracking changes in computer files and coordinating work on those files among multiple people.
    • Repository (Repo): A storage location for all the files associated with a project, along with their history.
    • Commit: A snapshot of the repository at a specific point in time, representing a set of changes.
    • Branch: A pointer to a commit, representing an independent line of development.
    • Merge: The process of combining changes from one branch into another.
    • Rebase: The process of moving a branch to a new base commit, rewriting the commit history.
    • Porcelain: High-level Git commands used for everyday tasks (e.g., commit, add, branch).
    • Plumbing: Low-level Git commands used for internal operations and more complex tasks.
    • Staging Area (Index): A preparatory area where changes are organized before being committed.
    • Remote: A repository hosted on another server or location, allowing for collaboration and sharing of code.
    • .gitignore: A file specifying intentionally untracked files that Git should ignore.
    • HEAD: A pointer to the current branch or commit being worked on.
    • Tag: A named pointer to a specific commit, often used to mark releases.
    • SHA (Secure Hash Algorithm): A unique identifier for a Git object, such as a commit or file.
    • Working Tree: The directory on your file system where the code you are tracking with Git lives.
    • Reflog: A mechanism to record when the tips of branches and other references were updated in the local repository.
    • Squash: Combining a series of commits into a single commit.
    • Stash: Temporarily saving changes to the working directory and index to allow for switching branches or other tasks.
    • Cherry-pick: The act of picking a commit from a branch and including it in another.
    • Bisect: A powerful command that allows one to use binary search to find which commit introduced a bug.
    • Work Tree: The directory on your file system where the code you are tracking with Git lives.

    Boot.dev Git Course: A Comprehensive Review

    Okay, here’s a detailed briefing document summarizing the key themes and ideas from the provided source text, which primarily covers a Git and GitHub course offered by Boot.dev.

    Briefing Document: Boot.dev Git Course Review

    1. Overview

    The source is a transcript of a video course focused on teaching Git version control. The course covers fundamental Git concepts, command-line usage, and team collaboration workflows, and focuses on both theoretical understanding of how Git works internally (“plumbing”) and practical application of Git commands (“porcelain”). The instructor heavily emphasizes hands-on exercises and examples.

    2. Key Themes and Concepts

    • Git Fundamentals:
    • Version Control: The course introduces Git as a system for tracking code changes over time, attributing changes to authors, and enabling history manipulation and reversion.
    • Commits: A core concept is the “commit,” which represents a snapshot of changes tied to an author, timestamp, and message. Git builds a graph of these commits, allowing branching and merging. “git creates a commit a commit is just a set of changes tied to an author time of day and other information.”
    • Branches: The ability to branch off a commit and create new lines of development is emphasized. Branches can be merged, and commits can be squashed or reverted.
    • Staging (Index): The staging area, or index, is explained as an intermediate area where changes are prepared for a commit. The instructor highlights the importance of understanding the difference between untracked, staged, and committed files. “An untracked file means that it’s never been added to the index which is like your staging area or it’s never been tracked”
    • Git is NOT a Delta Store: A key takeaway is that Git doesn’t just store diffs (changes), but rather entire snapshots of the repository at each commit. This was surprising to many, as the instructor notes “This was a surprise to me I always assumed each commit Only Stores the changes made in that commit” Git uses compression and de-duplication techniques to optimize storage.
    • Porcelain vs. Plumbing: Git commands are categorized as high-level (“porcelain”) and low-level (“plumbing”). The course focuses mainly on porcelain commands, as they are used most often in development. “the porcelain commands are the ones that you will use most often as a developer to interact with your code” The source claims the plumbing is the “hard things, the underlying tools you can use with Git” and that if you “understand how the the plumbing works the porcelain makes a lot of sense.”
    • Git Command-Line Usage:
    • Essential Commands: The course repeatedly emphasizes the core commands: status, add, commit, log, branch, checkout, merge, rebase, push, pull.
    • Configuration: Configuring Git with user information (name, email) is covered, along with setting default branch names. The use of local vs. global configuration is explained.
    • Log Flags: The instructor goes over using log in different ways, explaining, for instance, the use of “oneline” and “decorate”.
    • Reset: The git reset command is explained as a means to undo changes, with options like –soft (keeps changes), and –hard (discards changes). The instructor emphasizes the usefulness of git reset –soft in scenarios like rebasing after a mistake.
    • Remote Repositories: The course covers the concept of remote repositories and the standard convention of naming the authoritative source “origin.”
    • Fetch and Merge: The use of git fetch to retrieve changes from a remote and git merge to integrate them into the local branch is demonstrated.
    • Pull: Shows how to pull changes from remote by using git pull origin main, and what to do if you end up with diverging branches
    • Team Collaboration and Workflows:
    • Branching Strategies: The instructor presents branch renaming and branch visualization.
    • Merging and Conflict Resolution: The course addresses merge conflicts, manual resolution, and built-in Git tools like checkout –theirs and checkout –ours.
    • Rebasing: Rebasing is introduced as a method to integrate changes from one branch into another while rewriting the commit history. Squashing changes into a single commit is a common practice before pushing to a public branch, according to the instructor.
    • Pull Requests and Code Review: The course briefly touches upon pull requests and code review workflows, common in team environments.
    • Get Ignore: Explains the usefulness of get ignore files, how to create them, and the usefulness of the exclude parameter.
    • Stashing: A “stack” method, useful for applying some index to a data structure. Also useful if you need to pull new updates.
    • Advanced Git Concepts:
    • Reflog: The git reflog command is highlighted as a tool for recovering lost commits or branches, as it keeps track of HEAD movements. “remember get reflog keeps track of where everything has been”
    • Squashing Commits: The process of combining multiple commits into a single commit is covered, emphasizing its use for clean history and easy reversion.
    • Cherry-Picking: The instructor presents a “cherry-pick” as a method for adding small, specific commits.
    • Bisect: The git bisect command is introduced as a tool for finding the commit that introduced a bug through automated searching. It requires a programmatically informed test.
    • Worktrees: Briefly mentions the importance of work trees.
    • Tags: Emphasizes that tags are immutable pointers, so you cannot make edits to a tag.

    3. Notable Points and Opinions

    • Instructor Personality: The instructor has a casual, humorous style, often interjecting personal anecdotes and opinions.
    • “The Right Way” to Use Git: The instructor often presents a particular way of using Git as the “best” or “correct” way, though acknowledging that other approaches exist.
    • Emphasis on Understanding Git Internals: The course attempts to go beyond just teaching commands and aims to provide a deeper understanding of how Git works “under the hood.”
    • Criticism of Lane: The author is critical of “Lane” for his comments, which can be seen as copy-editing.
    • Reference of Popular Culture: References popular culture, such as “Star Wars”, “Slanderous” and “Ren and Stimpy”.

    4. Potential Improvements

    • More structured presentation of advanced topics.
    • More emphasis on different branching models (Gitflow, GitHub Flow).
    • More detailed explanation of the interplay between the working directory, staging area, and commit history.

    5. Conclusion

    The Boot.dev Git course appears to be a comprehensive introduction to Git, covering a wide range of topics from basic usage to more advanced concepts. The instructor’s emphasis on hands-on exercises and theoretical understanding makes it a valuable resource for aspiring developers, although the opinions and informal style might not be for everyone.

    Git: Frequently Asked Questions

    Frequently Asked Questions About Git

    Here are some frequently asked questions about Git, based on the provided source:

    1. What is Git and what does it allow you to do?

    Git is a distributed version control system that allows you to track changes to code over time, by author. It provides commands to search, manipulate, and revert history. Essentially, it creates snapshots (commits) of your code, tied to an author, timestamp, and other relevant information. You can branch off from any commit, create new commits on these branches, and merge them back together.

    2. Who created Git and why?

    Linus Torvalds, the creator of Linux, created Git in five days in 2005. This was triggered by a license dispute between Linux and BitKeeper, a commercial version control system that Linux had been using. Someone reverse engineered the BitKeeper protocol, and as a result Linus created Git for the Linux kernel development. Git was initially not user-friendly, requiring the use of low-level (plumbing) commands.

    3. What is the difference between “porcelain” and “plumbing” commands in Git?

    Git commands are divided into high-level (“porcelain”) and low-level (“plumbing”) commands. Porcelain commands are the ones developers use most often for interacting with code. Examples include git add, git commit, git branch, git merge, and git rebase. Plumbing commands are the underlying tools that Git uses, such as git apply, git commit-tree, and git hash-object. While understanding plumbing can be helpful, developers typically use porcelain commands 99% of the time.

    4. What are the key states a file can be in within a Git repository?

    A file in a Git repository can be in several states:

    • Untracked: Git doesn’t know about the file, meaning it has never been added to the index (staging area) or committed.
    • Staged (Indexed): The file has been added to the staging area, meaning it is ready to be included in the next commit. Only the changes added are tracked.
    • Committed: The file is part of a snapshot stored in Git’s history.

    5. How does Git store data, and what are “trees” and “blobs”?

    Git stores data as objects in the .git/objects directory, compressing them to save space. A commit is a type of object that includes a hash, author, timestamp, and message. Git doesn’t store diffs; it stores entire snapshots of files per commit.

    • Tree: Represents a directory in Git.
    • Blob: Represents a file in Git.

    A commit contains a tree object representing the root directory. This tree can contain other trees (subdirectories) and blobs (files). This structure allows Git to recreate the state of the repository at any point in history.

    6. How do you configure Git with your personal information?

    You can configure Git with your name and email address using the git config command. This information is stored in a configuration file, which can be either global (located in your home directory) or local (located in the .git folder of your repository). For example:

    git config –global user.name “Your Name”

    git config –global user.email “your.email@example.com”

    You can also configure the default branch name, setting it to main instead of master.

    7. What is git reflog and why is it useful?

    git reflog is a mechanism to record when the tips of branches and other references were updated in the local repository. The reflog allows you to recover commits even after branches have been deleted or lost. It keeps track of where “HEAD” (the pointer to the current commit) has been, making it possible to revert to previous states.

    8. What is git bisect and how can it help with debugging?

    git bisect is a powerful command for finding the commit that introduced a bug. It works by performing a binary search through the commit history. You mark a known “good” commit (before the bug existed) and a “bad” commit (where the bug is present). Git will then check out commits in between, and you mark each commit as “good” or “bad” based on whether the bug is present. Git bisect continues this process, narrowing down the range until it identifies the specific commit that introduced the bug. You can use it to check if a current commit is good or bad.

    Git bisect can even be automated with a script that programmatically determines if a commit is “good” or “bad.” This is done with get bisect run <script>, and by returning a non-zero exit code will designate it as bad, and zero will designate it as good.

    Git Version Control: Concepts and Commands

    Git is a Version Control System that allows you to track code changes over time by author. It was written by Linus Torvalds in 5 days and has become the standard for developers.

    Key aspects of Git include:

    • Repositories Each project has one repository, which is essentially a directory containing the project and a hidden .git directory. The .git directory stores the entire state of the Git project. To create a new empty repository, you can use git init.
    • Commits Git creates commits, which are sets of changes tied to an author, time, and other information. Git stores the entire history per commit.
    • Porcelain and Plumbing Git commands are divided into high-level (porcelain) and low-level (plumbing) commands. Porcelain commands are used most often by developers.
    • Configuration Git can be configured with your information using the git config command. The configuration file is a file that can be in global space (your home directory) or within your .git folder.
    • States Files in a Git repository can be in several states including untracked, staged, and committed. The git status command shows the current state of the repo. An untracked file has never been added to the index or tracked.
    • Staging Area The staging area is also known as the index.
    • Tracking Changes You can add a file to the staging area using the add command. After staging a file, you can commit it. A commit is a snapshot of the repository at a given time. The git log command shows a history in a repository.
    • Branches A branch is a pointer to a commit. Branches are lightweight and cheap. You can determine which branch you’re currently on with git branch. It is recommended to use main as your default branch if you work primarily with GitHub.
    • Merging Merging is bringing work from a branch back into the main line. A merge commit is a new commit that represents two diverging histories as one. It is the only commit with two parents.
    • Remotes A remote is another repo. Git is a distributed Version Control, so each repo is its own repo, and you sync between them.

    Git Branching: Management and Merging Strategies

    Branching in Git allows you to keep track of different changes separately. A branch is essentially a pointer to a commit. Because branches are simply pointers to commits, they are lightweight and cheap.

    To see which branch you are currently on, use git branch. It is recommended to use main as your default branch if you work primarily with GitHub.

    Key aspects of branch management:

    • Creating a Branch You can create a new branch using get branch New Branch name. However, it is more common to create and switch to a branch at the same time using git checkout -b <new_branch_name> or the newer command git switch -c <new_branch_name>. When you create a branch, it takes your current location and that’s where it points to.
    • Switching Branches To switch to an existing branch, you can use git switch <branch_name>. Older versions of Git used the command git checkout <branch_name>.
    • Deleting a Branch After a branch has been merged into main, it can be deleted. To delete a branch, use the command git branch -d <branch_name>.
    • Visualizing Branches Branches can be visualized as a series of commits. For example, a branch called main with three commits (A, B, and C) would be represented as A -> B -> C, where C is the most recent commit. If a new branch called other_branch splits off from A, it might have commits D and E, resulting in diverging branches.
    • Merging Branches Merging is integrating changes from one branch into another. A typical workflow involves branching off the main branch, making changes on the new branch, and then merging those changes back into the main line. This often involves a pull request on platforms like GitHub, GitLab, or Stash.
    • Merge Commits When merging branches with diverging histories, Git creates a merge commit. This commit represents the combination of the two histories and has two parent commits. The process involves finding the merge base (the nearest common ancestor of both branches), playing the main branch’s commits into a new commit, and then playing the other branch’s commits into that same commit.
    • Fast-forward Merge A fast-forward merge occurs when the branch you are merging onto has all the commits that the other branch has. Git simply moves the pointer of the base branch to the tip of the feature branch.
    • Rebasing Rebasing and merging can both be used to integrate changes from one branch into another. Rebasing rewrites Git history, which can be dangerous if not done carefully.
    • Git Reflog Git reflog keeps track of where everything has been. It can be used to recover commits on deleted branches.

    Git Merge Conflicts: Resolution and Management

    Here’s a discussion of merge conflicts, based on the sources:

    A merge conflict arises when two commits modify the same line in a file, and Git cannot automatically decide which changes to keep. This typically happens during a merge or rebase operation. Git identifies conflicted files and prompts you to resolve the conflict manually by editing the files.

    Key aspects of merge conflicts:

    • Causes A merge conflict typically occurs when changes are made to the same lines of code on different branches, and these changes are not direct descendants of each other. If the same line is modified in one commit and then again in a later commit, Git can usually resolve this automatically because it knows the order of changes. However, when two developers on separate branches modify the same line, a conflict arises when merging those branches.
    • Resolving Conflicts Resolving merge conflicts is a manual process. Git marks the conflicted files and asks you to resolve the conflict by editing the files in your editor.
    • Conflict Markers When a conflict occurs, Git adds conflict markers to the file to show the conflicting changes. These markers include <<<<<<< HEAD, =========, and >>>>>>> branch_name. The section between <<<<<<< HEAD and ========= represents the changes in your current branch (HEAD), while the section between ========= and >>>>>>> branch_name represents the changes in the branch being merged.
    • “Ours” and “Theirs” In a merge conflict, “ours” refers to the branch you are currently on and merging into, while “theirs” refers to the branch being merged. When rebasing, it can be the opposite.
    • During a rebase, the target branch becomes the branch you’re on, and then Git replays the source branch’s commits starting from the merge base forward to the tip of your target branch.
    • Therefore, during a rebase conflict, “ours” is “theirs” and “theirs” is “ours”.
    • Accepting Changes To resolve a conflict, you must edit the file, remove the conflict markers, and decide which changes to keep. You can choose to accept both changes, keep only your changes, keep only the incoming changes, or modify the code to incorporate both.
    • Built-in Merge Resolution Tools Git provides built-in tools to help resolve conflicts. The git checkout command can check out individual changes during a merge conflict using the –theirs and –ours flags.
    • Post-Resolution Steps After resolving the conflicts, you must stage the changes using git add and commit them to continue the merge process.
    • Re-recording Resolution Git has a “re-recording resolution” feature (re-re) that allows it to remember how you resolved a conflict. If enabled, Git can automatically resolve the same conflict the next time it occurs. To enable this feature, you can run git config –global rerere.enabled true.
    • Accidental Commits During Rebase If you accidentally commit during a rebase, you can use git reset –soft HEAD~1 to undo the commit and continue the rebase. This command moves the branch back one commit while keeping the changes in your working tree.

    Git Rebasing: Strategies, Use Cases, and Best Practices

    Here is a discussion of rebase strategy, drawing on the sources:

    Rebasing is a Git operation that helps integrate changes from one branch into another by moving or reapplying commits. It is an alternative to merging, and is often used to maintain a cleaner, more linear project history. However, it can rewrite Git history, which can be dangerous if not done carefully.

    Here are key considerations for a rebase strategy:

    • Primary Use Case The primary use case for rebase is to take the diverging commits from one branch and move them to the tip of the base branch that the feature branch is based on. This allows for a fast-forward merge back into the main branch.
    • How Rebasing Works When you perform a rebase (e.g., git rebase main on a feature branch), Git checks out the target branch (e.g., main). It then takes the changes from the source branch (feature branch) and applies its commits to the tip of the target branch. Finally, it updates the source branch to point to the new tip.
    • Linear History Rebasing allows you to maintain a merge commit-free history. A linear history is generally easier to read, understand, and work with.
    • Commit Shas During a rebase, even if the commit message is the same, you will get new commit Shas. This is because the parent of the commit is no longer the same.
    • Conflicts If there was a conflict while rebasing, there would be a conflict while merging.
    • Rebase vs Merge Both rebase and merge can be used to integrate changes from one branch into another. Merge can add an additional commit, while rebase does not.
    • When to Rebase It is generally okay to rebase your private branch on top of a public branch. If you’re working on your own branch and want to undo something you’ve already committed, git reset is preferable.
    • When NOT to Rebase You should never rebase a public branch like main. Doing so can cause significant issues for other collaborators. It’s generally good practice to rebase a public branch onto your own personal branch.
    • Rebase and Fast-Forward Merges Rebasing allows you to move a feature branch forward from diverging at a point up to diverging off of the current tip of the main branch, allowing for a fast-forward merge if you wish to get it back into main.
    • Interactive Rebasing Git rebase interactive is very nice and is used for squashing.
    • Rebase –continue If you make a mistake and commit changes (rather than calling git rebase –continue), you can use git reset –soft head~1 to undo that commit and then rebase –continue.
    • The “Ours” and “Theirs” During Rebase During a rebase, it is important to remember that “ours” is “theirs” and “theirs” is “ours” during a rebase conflict. The target Branch becomes your branch that you’re on, and then you replay the source branches commits starting from the merge base and forward at the tip of your target Branch.
    • If you had merged main instead of rebase, HEAD would still point to your branch.
    • Git Rerere Git has a “re-recording resolution” feature (re-re) that allows it to remember how you resolved a conflict. If enabled, Git can automatically resolve the same conflict the next time it occurs. To enable this feature, you can run git config –global rerere.enabled true.
    • Squashing
    • Squashing is used to combine a series of commits into a single commit. This is often done to clean up the Git history.
    • To squash the last n commits, start an interactive rebase with get rebase -i HEAD~n. In the editor that opens, change the word pick to squash (or s) for the commits you want to squash into the previous commit.
    • After squashing, you can edit the commit message.

    Undoing Changes with Git: Reset, Revert, and Amend

    Here’s a discussion of undoing changes in Git, drawing on the sources:

    Git provides several ways to undo changes, ranging from simple operations on your local branch to more complex maneuvers for shared branches. The right approach depends on the situation, such as whether the changes are only in your local repository or have been shared with others.

    Methods for Undoing Changes

    • git reset: This command is a powerful tool for undoing commits or changes in the index. It has three main options:
    • –soft: This option is useful if you want to go back to a previous commit but keep all your changes. The committed changes will be uncommitted and staged, while uncommitted changes will remain as they were. It takes the commits changes and applies them to your work tree, and moves your branch back once.
    • –hard: This option not only undoes the changes and moves your branch back, but it also clears out your index and working tree. Any uncommitted changes will be lost. This option should be used with caution, as it can lead to data loss.
    • git reset commit_hash: To reset back to a specific commit, you can use git reset –hard commit_hash. This will reset your working directory and index to the state of that commit, and all changes made after that commit will be lost.
    • git revert: This command is used to undo changes on a shared branch. Instead of removing the commit, it creates a new commit that does the exact opposite of the commit being reverted. This keeps the full history of the changes and undoing.
    • To revert a commit, you need to know the commit hash. You can find this using git log. Then, use the command git revert <commit_hash>.
    • git checkout: The git checkout command can check out individual changes during a merge conflict with the –theirs and –ours flags.
    • git commit –amend: Can be used to change the last commit’s message, but it does change your SHA.

    Scenarios and Best Practices

    • Local vs. Shared Branches:
    • If you’re working on your own branch and just want to undo something you’ve already committed, git reset is generally the way to go. This is useful for cleaning up commits before opening a pull request.
    • If you need to undo a change that’s already on a shared branch, especially if it’s an older change, git revert is the safer option. It avoids rewriting history and stepping on your coworkers’ toes.
    • Rebasing: If you make a mistake and commit changes (rather than calling git rebase –continue), you can use git reset –soft HEAD~1 to undo that commit and then rebase –continue.
    • Untracked Files: git reset –hard will not affect untracked files because they have not been added to the working tree yet.
    • Accidental Commits During Rebase: If you accidentally commit during a rebase, you can use git reset –soft HEAD~1 to undo the commit and continue the rebase.
    • Reset after a mistake: A soft reset is an amazing thing to use and it becomes exceptionally good when you screw up a revert, cherry pick, or a rebase.

    Dangers and Precautions

    • Rewriting Public History: Never rebase a public branch like main because it destroys your life.
    • Losing Changes: Be very careful when using git reset –hard, as it can lead to irreversible data loss.
    • Force Pushing: Never force push to master.
    • Accidental Deletion: If you were to simply delete a committed file, it would be trivially easy to recover because it is tracked in git. However, if you use git reset –hard to undo committing that file, it would be deleted for good.
    Learn Git – The Full Course

    The Original Text

    93% of developers use git which actually feels to me a little bit low because 100% of the developers that I’ve worked with use git it’s got a tighter grip on the Version Control industry than Google does on your personal data in this video the prime engine is going to walk you through not one but both of his git courses I’ll try to keep this intro short because Prime does a better job of talking in front of the camera than I do but I just wanted to let you know what you’re getting into now in each course there are 11 chapters which means 22 chapters in total you’ll learn how to set up git what repositories are get internals get configs branches how to merge how to rebase get reset what remotes are how to use GitHub with Git and ignoring files with G ignore in the second half of the course you’ll learn how to Fork AO how to use ref log merge conflicts rebase conflicts squashing stashing reverting cherry-picking get bisect get work trees and tags it’s a lot the first half of this course primes course number one is really all about learning how to use git as a solo developer and course number two covers all the stuff you need to know to use git effectively in a team Prime has spent over eight months writing these courses and the rest of the boot de team and I have spent that same amount of time really helping to edit test and refine them so I hope you enjoy them but this is a very Interactive Ive course I do not recommend sitting down and binging it in one sitting there are interactive lessons and projects the entire way so get your hands on the keyboard and actually follow along in fact I actually recommend that you take the course on boot Dev and go ahead of prime and then watch him go through that same lesson so you can see his approach his commentary and his Solutions after you’ve had a chance to experiment and and challenge yourself and do it yourself now all of the content in this YouTube video and all of the content on bootd are completely free there’s no need to sign up for a boot Dev membership to get value out of this course that said all of the interactive features on buev are paid features so if you want to be able to submit your own assignments if you want to view Solutions chat with the AI chatbot or get a certificate of completion at the end uh you will need a paid membership for that and you can actually use primagen code Prime YT that will not only help us at boot dev be able to produce more courses like this but that also supports the prime engine directly that code Prime YT will get you 25% off your first month or year if you choose an annual plan of a boot dodev membership one last note if you get stuck and need help our Discord Community is literally just a few clicks away so join the Discord Community ask for help and let’s talk about get all right we are now going to officially start the entire boot dodev learn get I’m going to go through my I’m going to go through the course that I created I want to do it and it’s going to be awesome here we go we’re going to go through the course we’re not going to watch the videos because guess what this is my course in 2005 after license disputes with bitkeeper lonus Tal’s creator of Linux you may have heard of it sort of runs the web not a big deal decides to write his own Version Control he wrote git in 5 days and within a couple years it became a widely used Version Control and now today it is the de facto standard for all developers to be clear when I say get I don’t mean an insult from across the pond and I don’t mean GitHub gitlab stash or any of the others all of those companies use git they are not git git allows you to track code changes over time by author with a set of commands to search manipulate and revert history in simple term git creates a commit a commit is just a set of changes tied to an author time of day and other information as many commits as you want can be added to the graph at any commit you can Branch off and create new commits on the new line any of these branches can be merged into any other Branch including the main line commits can be squashed into one commit and commit messages can be edited also git commits can be reverted just in case they don’t want terrible code git is very complicated piece of software but the interface and operations are very simple and in this course we’re going to be going over installing and configuring get porcelain in plumbing commands inspecting G history branching merging and rebasing undoing changes and remote repos and GitHub I hope you enjoy this course and in about another month or two I will be releasing part two which will go over all the advanced features Advanced Techniques with merges and rebases and conflicts and of course just really diving into some of the more complex parts of git but in this course you should be able to get everything you need to become quite proficient in the real world incl including understanding how git works the name is the gagen I already have everything done I might need to update boot dodev hold on one second all right there we go I’m going to get the latest version here we go go install I thought they I thought that was a thing H anyways okay there we go we got the new boot dodev everything’s looking good let’s do a little boot Dev version oh yeah looking hot looking good perfect I believe I should all be logged in so I’m just going to go like this just to make sure that I’m logged in there we go echoing rebasing his base there we go everything good I believe I’m I believe I’m all good perfect okay submit so this is the cool part by the way so this tool was developed I think the motivation started with my course and other courses I think Lane was developing one that also needed it as well but this tool is super cool so you copy this thing you paste it in and when you go right here look at that it says hey you did everything correct okay fantastic all right we’ve already installed git I already have everything installed I don’t need to worry about any of that all right we’ll do that thing as well okay perfect the CLI is so cool it is all right read the friendly manual one of the best parts of G is that all the documentation is fantastic but that wasn’t always the case by the way it was actually the the git documentation to this day I actually can’t read the uh man G tag page still okay so everybody knows what a tag is right we all know what a tag is a let’s see add a tag reference in ref tags unless DV dlv is given to delete list or verify tags um okay okay I think we understand this right unless f is given the named tag must not yet exist and then this is happened to create a take object or requires take message unless M or f file is given and editor is started for the user okay what the hell is a tag though can you just tell me what it is otherwise a tag reference points directly to a given object I know it’s just like is this just a wild I’m surprised the very first description isn’t being like a tag is a mut a immutable named pointer I’m just like what the fu is this all right who created get obviously I did a by the way lonus tvols did create git in 5 days and The Story Goes Like This he created git in five days because one of the one of the maintainers of Linux broke the bitkeeper license to Linux bitkeeper said you can use bitkeeper you’re just not allowed to reverse engineer the protocol and somebody reverse engineered the protocol and get and bitkeeper said get the hell out of here get out and so they actually had no more uh subversion at that point or whatever bitkeeper was so he wrote to in 5 days now remember git was not friendly at all you had to use all the plumbing right you had to use like you had to like cat out the file you had to create the tree like you had to do all the tracking yourself and it was not fun right it was not good it was not good but anyways lonus did it all in just a moment and he did it in five days then on the sixth day he rested porcelain and plumbing for whatever reason get is compared to the crapper uh rip John crap and so porcelains the outside the good stuff uh the plumbing is like the hard things the like the underlying tools you can use with Git all right so in get commands are divided into highle commands and lowl commands the porcelain commands are the ones that you will use most often as a developer to interact with your code some porcelain commands are these on don’t worry about what they do yet we’ll cover them in detail soon absolutely by the way some examples of Plumbing are this one get apply give get commit Tre get hash object in which I barely know any of what those things do we’ll focus on the highle commands because that’s what you use 99% of the time in fact I’ve never professionally use the lower level commands right BCT is I I I believe is a porcelain command um reflog porcelain command cherry pick porcelain command it’s a bit confusing right all right 99% of the time porland commands are used to interact with Git yeah but you can and I have done it but it’s really good to understand how they work if you understand how the the plumbing works the porcelain makes a lot of sense all right quick and fig we need the configure get uh with your information uh whenever you code yeah blah BL blah blah blah so we got to do this thing we got to add our name in our config so if you’ve never done config and get get just has this whole Global it’s literally just a file that’s all it is is just a file and it’s either in global space which means it’s in your uh home directory or it’s within yourg fer so kind of either or there anyways this is pretty good so we can uh we can do this config set username email so I’m going to make sure let’s see uh get config uh local what do I got here oh whoopsies uh is it List local I always forget how to use this one air keys does not contain get config what what what is it it’s it’s list oh yeah I forget list is the only one config is the only one that has this older way of doing a bunch of Dash dashes whereas like when you use something like get stash you go like get stash list whereas with config you go this kind of list and always it always I always have to remember what the hell I’m doing right there okay local so as you can see I have all these things these are all the good stuff this is uh from graphite so don’t don’t mind that here we’re going to probably want to do stuff little get config uh list GP name do I have a name in there I do I have the name uh there we go I have email perfect bada bing bada boom we got those things already set so I have all that and you add it to your Global so your you’re Global by the way if you just go like this you can go uh whoopsies get config right it’s right there it just takes the latest value all right and so we also have this one finally let’s set the default Branch we’ll talk more about this so we’re all on the same page we’re going to set the default Branch to master to begin with so the funny part is is that um hey hey now let’s see hey now Global and then you have to go uh what is it is it add look at that there we go add there we go so it takes the latest one probably need to do an ad might want to make a little note there never caught that problem only level two week I had to reset my entire account all right make sure it works so there’s a reason why we do this so we can show you to do it differently later right but it’s Master by default true but a lot of people already have it say updated to main or to trunk or something else so I just wanted to make sure that we had this such that everybody can change it um and see what it is so there you go all right so we can C the config awesome you saw that we CED the config everything looks good all right we’re going to kind of rush through these early ones because I don’t think they’re very they’re not that important and when you’re learning how to use git these ones don’t make a lot of sense like what the heck is this config thing why are we setting all these things we just got to do it to set up your repo so you understand how git works right so this is all confusing stuff you’re probably very confused if you’re new to get that’s fine it’s [Music] okay all right so all right the very first step uh of any project is to create a repository a get repository or repo represents a single project you typically have one repository for each project you work on it would be wild to see many repositories for a single project unless if you’re considering uh Forks SL yeah webflix you like that a repo is essentially just a directory that contains a project other directory or files the only difference is that it also contains a hidden git directory this was a big eye opener for me is realizing that the that the dogit is literally the entire state of your G project it’s like the entire thing and so if you’re ever having questions about what’s going on everything is actually stored in here so when you think oh how does it know every like how does it know all my branches it’s literally in the git directory everything about it is in the git directory uh webflix this uh this course we’ll be managing content for webflix an imaginary self-hosted video streaming application can you imagine why would why would we name it webflix that makes no sense let’s see navigate to somewhere in your file system where you’d like to store the project and once you’re there create a new directory called webflix all right uh rmrf I bet you webflix already exists in my oh my gosh get the hell out of there oh get the hell out of there okay makeer webflix there we go and webflix there we go now I’m in here it’s brand new right it’s empty nothing in here and so I’m I’m assuming we’re going to have to get init get init just creates the new empty directory right it doesn’t do anything other than it creates a brand new directory it uses our config let’s go so I should be able to go ls- la you can see a git folder right here if I find inside the git folder it’s pretty empty it just has all this stuff it has a bunch of sample preh hooks it has no objects which is where it stores everything it has uh nothing I believe even the head is a little bit goofy if I’m not mistaken there you go that was weird cat get head there you go weird huh getting it yeah all right so anyways we do all this one awesome so now that we have our uh repo initialized let’s actually get into the stuff is this VOD G stay online it’s actually going to be moved to the uh boot dodev YouTube there we go we got all this this looks good let’s go return to our browser done got him man I’m so good at this I’m getting so much stats look at this I’m already level two a file can be one of the several States let’s see a file can be in one of several States in a get repository here’s a few important ones untracked staged committed okay this is very important this is also very important to understand because I’ve lost so much work not understanding the difference between all of these all right the get status command shows you the current state of your repo all right so assignment every good content management system needs a table of contents create a file in your rout called contents. MD and add the following lines let’s do this all right Vim contents. MD d uh paste this thing in Bam Bam get status you’ll see right here untracked files that means git doesn’t know anything about this this file an untracked file means that it’s never been added to the index which is like your staging area or it’s never been tracked so it just says we don’t know what’s in it so if you delete this file you lose every last bit of content because I’m pretty sure there’s been a lot of people that have goofed that up yeah I’ve done it it hurts it’s emotionally a bruising experience to accidentally have a file that was untracked you think it’s tracked you do something and you delete it and Fs you removed untracked files yeah removing untracked files is is emotionally painful because you can’t really recover it it’s a right of passage it’s a right of passage to emotionally bruise yourself all right there we go so now I should be able to jump in here I should be able to run the little tool there we go everything’s good all right so staging staging you’ll notice the term index a lot so if we go into here and we go mangit uh what’s it called add you’ll probably notice the word index quite a bit in here and the index is literally just the changes that you have staged onto your system that means any untracked files become tracked files and only the entire changes are tracked at that point there we go uh add this one let’s see for example I use Arch by the way right without staging every file in the repository would be included in every commit but that’s often not what we want all right so you want to get add the file so I’m going to add the contents and then do this now me personally whenever I do stuff I usually hit a get status if the tree represents what I want it to be meaning that the changes are what I want and we have just this one untracked file I often will just use get add this now here’s the deal about get ad okay that’s a little goofy all right uh get status uh when you do this here I’m going to go like this I’m going to go touch Fu if I go like this get status you’ll notice that Foo is untracked as well if I make her uh Fufu and CD into Fufu and then get add this you’ll notice that Fu remains untracked that’s because get add dot adds everything at that directory and Beyond it doesn’t add it doesn’t add things in the directory P you have to use different ones like get add capital A that kind of stuff but we’re not talking about that okay we’re not talking about that uh there you go get get the hell out of here there we go status we got that fantastic um so I should be able to just run this we’ve now added it our contents have been added we’re looking good we’re looking good oh man I’m getting so much experience points I I’m I’m almost level three after staging a file we can commit it a commit is a snapshot of the repository at any given time so this is very very important and this is a thing that a lot of people don’t understand about git git is not storing diffs git stores the entire history per commit so your entire git everything is in a single commit and that’s very very important distinction to make because a lot of people don’t realize that okay so our assignment is commit the contents to file this with the message add contents this you would normally start a commit message with a obviously this is because we’re doing stuff with boot dodev so it wants to be able to keep track of all your commits and all that so there we go then run get status skin you should see that the file is no longer staged right all right so let’s go back here uh let’s zoom in uh get commit let’s see uh get commit there we go we did that and so if we go get status you can see we have a clean working tree get log one line You’ll see that we have one thing right there let’s see wait it so it doesn’t store per change commit no and density I’ll show you why in just a moment so this course is meant to really show you what is going on here all right so now that we have that I should be able to just take this boot. Dev paste that in there go right here awesome I did it I’m I’m smat I’m smat I’m real smat uh half of git you’ve learned half of G you’ve literally learned half of git we just get commit status add commit right that’s all you need to know status add commit that’s like most of I know that’s crazy to think of but that’s it half of G easy you’re like you’re like a senior engineer at this point it’s not near half though I know of course it’s not actually near half because when you go like this get uh uh when you go like this man get Dash you’ll notice that there’s 151 possibilities but of those possibilities three of them is what you pretty much use constantly which commands adds a file to the staging area Prime is it Prime no add right it’s in the name dummies it’s in the name name dummies all right get log get uh okay log is fantastic by the way log is one of those sleepers that people don’t know how to use but there’s so many good stuff to a log get repo is a potentially very long list of commits where each commit represents a full state of the history a git log command shows a history uh in a repository this is what makes get a Version Control System you can see who made the commit when the commit was made and what was what was changed so there’s a lot of cool things so here so this right here so they we’ll see what uh he made us do this goes get no pager I believe this just simply will output the git log so normally when you do git log it actually outputs this like second screen that’s kind of like less if you’ve ever use the Tool uh less that’s all it’s doing instead no pager just prints it directly out it just prints it to standard out and log is the command N1 means the last 10 commits but what you really want to do is you want uh you can do things like one line that will make it nice and smooth so you can just see this nice beautiful thing you can do uh parents which will do annotation we don’t have any parents yet we don’t got no parents we are the Batman of commits uh and you there’s a bunch of stuff graph is really cool if you’re working on something cuz graph is you’ll notice that there’s like a little Aster right here it will actually graph how your commits are being merged back in and how the uh different branches are going so we’re orphans right now we’re effectively orphans right now or you can think of us like Adam maybe we’re the first huh it’s not that bad right right all right do the one of those there we go bada bing bada boom all right so let’s get into some real stuff different hashes my latest commit uh or so in this example the commit hash was this our commit hash was what 78 blah blah and that’s because whenever you do anything with Git the hashes can’t you can technically do a hash collision by being able to generate the same git changes from the same author at the same time and whatever other information that it uses with the same parent and all that you could actually create the the hash is consistent it’s recreated every single time so it’s an important Point all right there we go if you’re not careful you’ll have two commits with the same hash false you’d have to be very careful to create that and I don’t believe that’s even a uh it’s not even like a yeah g is the original blockchain for those that are wondering all right you may have noticed that even though we you and I both have the same content in our repositories we have different hashes yes we already went through all this yes they do a sha one it’s beautiful which does let’s see which does not affect the uh the hash of a commit the commit time stamp message author’s preferred text editor even though it should I do think all Vim hashes should start with 777 a little bit of luckiness to it to me that’s the only appropriate thing to do all right the plumbing so far we’ve used git in a porcelain manner but the let’s see but to Sate our insatiable curiosity Sate is a weird word okay Lane may have done a little bit of writing for me in this one just so you know uh let’s take a look at the plumbing all right it’s just files all the way down all the data in the git repository is stored directly in the hidden file you can actually see that look at this if I go like this if I go find inside the git folder you’ll notice something right away look at this look at that thing that thing looks just like this thing right here right 7805 172 7805 172 look at that huh kind of crazy right that’s my commit okay sneaky git very Shakespearean I know he’s very Shakespearean he uses phrases like upstairs and downstairs and it’s crazy all right git is made up of objects that are stored in the git objects directory uh a commit is just a type of an object correct use log 10 to view your commit hash do this inside the object directory and we already did that we already saw it which uh let’s see which matches the format of the file you’ll notice here too so this is something that you probably don’t know about Linux uh this right here this is called an inode busting effectively what IOD busting is is that a directory can actually end up having too many files in it if you ever done it weird stuff starts happening happen happening so instead get to prevent iode busting or to prevent iode whatever it is you’ll do this so this takes the first two letters and then does this right i’ I’ve ran out of iodes before yes I i’ I’ve goofed up myself so a directory can only be such a large size so therefore this just helps separate out things this is very common you’ll see this in CDN cdns do the exact same thing the actual naming underneath will start doing weird stuff like this screw you unlinks your list yeah it is it I’ve done it once I dude I note issues are insane by the way they’re crazy yep I ran into this with a massive log directories exactly you have to do I note busting or else you just life is painful and I did it once and then once you do it once you never do it you just never do it again all right that’s it that’s all there is to it all right so that’s why they do this they take the first two and they turn it into a directory so that way it just kind of spread things out all right so let’s take a uh let’s take a look at what’s inside this suspicious get commit object file have you ever tried catting one of those things the first thing I ever did when I found out get was just a folder is went right to objects went right to my commit and tried to cat it out and it’s just this right that’s a bunch of right there okay what the hell does this even mean all right so you can’t really do anything no it’s a mess uh let’s see the contents have been compressed to Raw bites so that’s why git remains small is because git compresses things and that’s very very important all right now the lesson let’s see okay hold on this lessons run and submit are a bit different because you need to tell boot. Dev CLI where your commit object is located all right so we’re going to do the exact same thing so I have to do this but I have to give it this name right path to file right so I’m going to grab this thing and I’m going to go like this uh let’s go get objects 7805 05 this thing and then submit I believe I did that correctly this one I screwed up last time I tried to do this let’s see failed to get this thing page not found wait who’s he what’s he all right let me reread this one sorry sometimes sometimes I’m not good at reading lessons Okay I just want you to know that rtfm read the friendly manual sometimes I don’t read the friendly lesson okay let’s look at this again try to C the contents of the file we already did that nope it’s a mess the contents has been compressed um we can we can print in a decimal I don’t really care this lessons run and submit are a bit different because you need to tell boot. CLI where your commit object is located uh run and submit the test but provide the path to your commit object file as a second argument run lesson lesson ID okay so let’s try this again because I’m apparently I’m too stupid so I need to go boot. run lesson ID path to file okay get objects 78 052 there we go look at that I’m getting so much exp I’m level four you guys wouldn’t understand practically a grand wizard Arc Mage I don’t think you’re supposed to be a grand wizard right that’s not uh you don’t want to be that you don’t want to be that guy okay I forget sometimes I forget things okay uh luckily git has a built-in Plumbing command cat file that allows us to see the contents of a commit without needing to fuss around with the object files directly so you just use get cat file- P cuz technically like if you’re viewing a tree you have to use a tree command you know there’s all these different things but cat file just allows us to look at everything at once without having to worry about its type and all that uh so you can just go get CAT file this so if I do this get cat file this guy and do 78517 I believe you only need up I think you only need technically you only need four to specify it you’ll notice something when I cat out my commit you’ll see the author and all this and then you’ll see the message that’s so it’s nice then you see this tree command look at this tree this hash we don’t know what this hash is right so I can actually go get uh get cat file- P 5B 21d and then you’ll notice that it has a blob object and that blob object is a Content so to kind of put this in perspective you can think of a tree as a directory and you can think of a blob as a file so that’s kind of important to know so when I cat file this thing you’ll notice that it’s contents which is the exact contents of our contents file they’re identical so do you see what happened there why did I capitalize B for those that don’t know why I capitalize B uh when I type I have dvorac but even more so when I type numbers 1 2 3 4 5 6 7 8 9 10 you’ll notice that I typed out symbols symmetric symbols it’s because I’ve optimized my keyboard to prevent wrist pain from happening because I program a lot so I have to hit shift to type my numbers right so sometimes I’ll do a capital B when trying to type stuff because I’m still holding shift does that make sense okay there’s no there’s no reason or Rhyme or anything to do with it it automatically lowercased it for me it didn’t mean anything all right so there you go you can see that so this is actually really cool what just happened here look at this I was able to cat my commit out take the root directory tree cat that out see the file that was there then cat that file out and see the contents of that file this is very important because we’ll use it later to grab stuff out it’s kind of fun it’s kind of it’s kind of neat so there we go so we can do that all right so use cat to do all this one pass an argument to the CLI notice that boot. Dev CLI test for this lesson take an additional argument to noted by this one right there we go you need to provide the hash okay so I need to provide the hash there we go all right we’ll do that we’re going to grab that bad boy and I’m going to go like um I’m going to go like that and then I need to grab the is it which hash are we doing that you need to provide the hash of your last commit okay we need to provide the hash of the last commit there we go so I’m going to go back up here I think that’s all I need to technically do d s and then take out this little slash I think that should do everything I need to do there we go got it first try got it so good at this why would you ever need to do that in get you’ll see you don’t technically need to do this in get but it’s really good to understand why this is where the big eye opening moments about to happen for everybody about how git actually works because what we’ve seen so far is that we’ve made one commit right we’ve made one commit and we’re going to call it a and in that commit we have a tree that’s like our root directory and inside that tree we have a blob which happens to be some big long hash and it is contents. MD all right this is very important so this is our Commit This is commit a so now we’re going to add this and we’re going to see how this changes all right all right I believe I did all this all right trees and blobs now that we understand some of our plumbing equipment let’s get into the pipes here’s the terms you need to know tree is a way of storing a directory blob is a way of sorting storing a file so you can see right here I already showed you this there’s the tree we are able to go through through the tree and get all the way to the blob right assignment use get cat file again but this time use it on tree you should see a blob with its own hash use cat file again on this one submit the sees with The Blob hash okay we should already be able to do all this uh because we actually already did this all right let’s find this little bad boy right here where are you where are you where the hell are you there it is hey there we go by bing bada boom able to grab all that stuff out I just grabbed out the file hash cuz I knew what it was or the blob hash all right second uh second command uh reminder of commands get log um and Cat file that’s what we’ve been doing log is a porcelain command where cat file is a plumbing command you’ll use log more often when working with the code uh on coding projects but cat file is useful for understanding gets internals we already kind of talked about that so we’re going to create a second file called titles this is where things get really interesting are you ready for this uh all right so we’re going to go like this titles. MD paste this all in here delete that one uh run through and then we need to save stage and commit the file with the files long as it starts with a B right that’s the thing get uh add this get commit with a B There we go awesome and then run the CLI there we go I’m going to grab the CLI and we’re going to do this bada bing bada boom all right so we’ve created a second commit right this is how you will understand get get stores an entire snapshot of files on a per commit level this was a surprise to me I always assumed each commit Only Stores the changes made in that commit now type one in the chat if that’s what you thought too I assume a lot of you thought the exact same thing that get stored Deltas right yeah I mean look at this a lot a lot of changes in here and I think that’s completely normal anyone that doesn’t think that get stored Deltas right away you’re lying to yourself you’re like yeah I didn’t think that I always knew that it didn’t do that no you didn’t okay your your small brain did not think that we all thought that because that’s totally normal thing to think okay well it’s true that g stores entire snapshots it does have some performance optimization so that your git directory doesn’t be get too unbearably large get compresses and packs files to store them more efficiently get D duplicates files that are the same across commits now you’re probably thinking isn’t that just Delta stores hold on let’s find out let’s just find out okay watch this we’re going to use git cat file and we’re going to find the hash blob of our titles MD okay watch this all right so I’m going to go like this uh I’m going to go uh let’s see I’m going to go get log log one line I’m going to grab this last that’s my last hash right there we go I’m going to go get uh get cat F I know there’s better ways to find your your current hash just shut up this is good enough this is good for people to understand now notice that we have our tree also notice we have our parent now so our parent is our previous commit so we can actually walk back up the tree if we needed to this is if you’re wondering how git log works is that it stores parent pointers as part of the commit all right anyways so we’re going to take our tree and go get CAT file – P this now notice that there’s two blobs okay there’s two blobs here the first blob is the previous contents and this one is now titles okay so I can actually take this and go get CAT uh file- p and I can actually cat out the titles file uh I can actually go to this one and get cat uh G cat uh cat file- p and I can cut out this one and this will give you the contents of that file but notice this right here I want you to look at this would you look at it for a second I’m going to jump into my parent get cat I’m sure I explain this in a moment in the course but I like to explain it this way uh there’s our parent commit I’m going to grab that tree notice that that tree is different than uh is a little bit different like everything’s a little bit different this is the older version of the tree get cat file- P this look at contents look at contents it stores a unique tree per commit but that that doesn’t mean it stores the entire file it just stores a pointer to the file so when I say A commit stores the entire history it stores every reference I know kind of mind blown right that’s why it’s efficient because what happens is you can think of it this way is that let’s say we have Commit a and commit a has the parent tree and then it has the blob that’s pointed to our contents file okay and this is like let’s just say it’s like e f and then a bunch of letters right blah blah blah blah commit B adds that new file and so it’s going to have that same tree but this is going to be a different notice that the hash is different on this tree because this tree has a new set of kids so something has happened to this tree which means that it can even point to trees that have not changed that’s very important so we have a new tree we’re just going to call this one one we’ll call this one two and this one is still pointing to that exact same EF blah blah blah blah but then we have a new one which is going to be our titles which is going to have its uh we’re going to probably need to call this like titles and then it’s going to have its own commit right here and so it doesn’t update this this Remains the Same so it’s very important to understand that all right so let’s see what we have to do here all right we’re going to use cat file we’re going to view the uh the hash of The Blob for our titles and you can do that save that hash somewhere in your notes all right let’s save this hash somewhere in the notes because we have to find it there we go it’s right there I can just come back to that later add a new new directory to your project called quotes inside add two files all right so let’s uh Vim uh what is it you say quotes they say quotes I can’t remember quotes yeah I think so uh what was the first one called uh star wars. MD and then what was the other one uh Dune MD Dune by the way is a great movie Dune Dune can also be fall under the good Sci-Fi um all right so there we go we have those two things stage and commit both files in a single commit with the message C add quotes perfect okay we can do that uh get status you can see it’s right there get add this thing get commit DM put all that in there get log one line should have three commits you can even go like this get log – P which will show the differences so this first one adds this new file uh from nothing to quotes Dune from nothing to quotes Star Wars and then it doesn’t make any other uh edits right and there’s the previous commit which adds titles and the previous commit before that which add contents okay cool awesome we got all those things all right so we did all that one use the command CAD file to view the hash of The Blob for uh titles again you’ll notice that it’s still the same hash correct there you go because the file hasn’t changed run submit this thing Perfect Isn’t that cool Isn’t that cool I think that’s pretty cool I mean I think that’s very very cool for me that was a very mind-blowing moment is to understand how git works because then it no longer felt as confusing and that was my big kind of like I I I I got really really confused for quite some time when I first played around with Git because of that thing all right what does it mean that files uh which were once committed then deleted will be forever kept by git so technically it’s not forever kept by git it’s forever kept by your history unless if you prune your history so you can actually prune your history out of git and so that way it would actually clean up any broken references so it doesn’t actually keep say deleted commits that don’t exist so get prune DF yeah so that will go through so we will actually do that I’ll I believe in this uh in this section we will actually revive a file that was long lost or a commit that was long lost it’s kind of obvious that it’s store snapshot otherwise you need to walk back the tree a lot for files that don’t change often yeah I mean it’s it’s obvious in hindsight but I think the first time you think and you download the first time you ever use a a Version Control you think wow how could it possibly ever store everything it must have to like create the repo by walking all these links that’s why it gets so fast is it doesn’t it keeps your tree and then when you need to change your directory it literally just walks that tree and recreates every single file at each one of those points right that’s but the first time you you wouldn’t understand that right let’s see 100% of the working let’s see 100% of working with Git is checkout Branch ad commit push Force push rebase or merge yes exactly that’s why I say that’s well I mean it’s not 100% it’s like 99 95 there’s log there’s ref log ref log is incredibly important we’re going to go over that there’s also like get checkout so get checkout theirs versus ours it’s very important when you want to be able to just grab an entire change from one side of a merge [Music] conflict let’s take a command apart get config okay so here we go we’re going to actually start talking about config now cu the config is actually useful to use and understand because sometimes you actually want want to be able to change ways in which your G experience changes or in which in which it operates so let’s look at this all right so let’s take a look at the command so get config is obviously the top level it’s still the older style command so instead of get config ad it’s get config D- ad which is kind of a pain in the ass Global is where to store it so it’s either Global or local there’s some other places you can store and get but nobody actually stores things in git right uh or in those ones at least as far as I can tell I don’t know of any use case where you store in system uh I’m sure there is a use case I’ve just never personally ran into it I’ve always just used you know local or Global all right uh so Global stored in uh this right here in your uh home directory get config whereas local is stored inside your git configure right so if I go like this if I go in here and I go uh let’s see uh let’s see what is it LS or find in my git folder what is it name is it config I think it’s config there you go yeah there we go uh cat config it’ll say here’s the things that are inside of your local repository so when it creates a config object it actually takes your globals then it takes your logos and kind of combines them one at a time all right assignment you can actually store uh any old data in your git configuration granted only certain keys are used by git but you can store whatever you want yeah it’s just a key value mapping that’s all it is so you can like uh I know when I was at Netflix we actually had a lot of information stored for how we operated over certain stuff so it just I used to have a bunch of Netflix stuff on my system at one point uh set the following useless key/value pairs in your local git configuration so right here so we’re going to do this for our locals all right so it’s not too hard so you can go like this get config add local so I want to add a key value and I want to do it locally and then what do we want webflix uh CEO okay the prime gen okay uh actually yeah we’ll call the prime gen and then we’ll do uh the CTO as the lanen right that’s the actual CEO of um what’s it called of boot. Dev and then valuation valuation mid it’s a mid it’s a good mid valuation hey who here wouldn’t want a good mid valuation git has a command to view the contents right so if you just go List local it’s going to list everything you can also just cat it out right so as we did earlier you’ll see here’s our top level uh section here’s our keys and values uh so a good thing to notice here is that this is a SE section and this is a key so when you look at this you’ll notice that this is the section this is the key that’s important to know because you can actually delete all configuration by section or by section Keys all right so there you go you can List local so if I just go get config List local it’ll just uh list all my just local only files right here all right so let’s grab this thing jump in here paste it in your company position mid isn’t that everybody’s company position by the way configs were one of the more confusing parts for me not confusing by how they operate because they’re actually exceptionally simple but when I first started using git config was something that I executed once and then I never looked at again and then then whenever I had to touch it I was just like I don’t want to do this right and then I just got all confused by stuff and then I just it felt confusing because I refused to just spend the three minutes it took to understand said it and forget it exactly and then you just don’t know how certain things operate and simply because you didn’t learn this really simple thing this is why I did config because config is one of those extremely useless things you should pretty much never need to know but that one little moment you need to know it it’s very useful it’s very very useful we’ve used list to see all the configuration values but get flag is uh useful for when you’re trying to get a single value right so we can do get uh key remember a key is a section. key name so username webflix CEO there we go so I can we can get the web value so I can go uh get get uh let’s see what is it web webflix webflix valuation and it’ll go and get mid nice right doesn’t get config username just get it uh get config user.name yeah it also gets it you could get must get is the default operation but it’s good to know that because you can also do do set right all right there you go beautiful we did that one uh bada bing bada boom all right this is looking good all right the unset flag is used to remove a configuration value for example get onset key let’s remove the CTO all right so we go like this uh get config unset right everybody you know everybody loves a good unset right I really hate the term unset uh which one are we doing CTO CTO yeah all right I just fired Lane because you know what screw Lane what happened when you tried to unset uh oh try using unset to remove the section I forgot to do that one if you do this what ends up happening key does not contain a section right so you need both a section and a you need both a section and a value or a key name for this thing to be able to be removable when you use unset you have to do unset section if I’m not mistaken I always forget the entire section it failed because you have to use key and value right you have to use both you got to use both duplicates typically a key Value Store like python dictionary you aren’t allowed to have duplicate Keys strangely enough git does not care yes if you look at my git config uh Global uh list Global and then we GP what is it um uh a nit you’ll notice that I have in here three of them okay I had in it default Branch master in it default Branch Main in it default Branch Master yeah it just takes the last one my bad my bad on that one yes you can yes but but if you do that you have to force push right Force pushing is the only way for you to be able to change history for everybody else and if you do that you will ruin the whole repo and everybody will know all right duplicates unset all so unset all is if you want to unset uh entire thing you only need a section then right or sorry unset alls if you want to delete a multi- existing uh key value combo which is kind of odd having an key set combo it’s just kind of weird so if I do this and I go like this and I add a bunch of CEOs I should be able to go in there and go get uh config List local and now you’ll notice we have a whole bunch of CEOs right we have four of them me plus uh Carson Warren and Sarah all right so if I want to undo that I can remove all CEOs by doing unset all right get config unset uh web flick flick flick do CEO there we go CEO has multiple values unset all bada bing bada boom get List local all the CEOs are gone anyways okay so now that we did all this pretty straightforward right pretty straightforward stuff there we go there we go awesome we’re kind of getting through these things uh you know the config SE section it’s it’s it could be boring but whatever it’s fun uh you know it’s you got you just got to learn these things right all right so there you go so we’re going to do the the next thing um which is we to remove an entire section now webflix is a section we have so if we just go remove section we can actually remove all of it so if I go back here and I go um I can add all of this and go get config uh if I go get config List local you’ll see that I have a bunch of webflix stuff so if I go get uh config what is it it’s remove section right it’s not unset section you know how many times I struggle with remove section versus unset and all of that man whenever I’ve had to do anything like that I’ve screwed it all up it’s so easy there you go make sure I really get it out there you know what I’m talking about we want to get it out there and then also you’ll notice that if I go like this cat config uh uh cat get config you’ll notice that it actually removes the section right just fun little fact fun little fact if you’re wondering you know what I mean bless you my goodness yeah thank you yeah you just edit the file directory I personally find that uh I would just rather jump in here and edit this often than doing all that other crap to be real it’s just it’s just much easier CU this other thing is just it’s just really hard you know it’s just really really annoying all right locations uh there’s really only two locations that you should really be concerned about I actually never used a work tree specific location or a system location I’ve really only done Global and local I find location location Lo anyways in my experience 99% of the time you’ll be using Global to set things like your username and email the other 9% of the time you’ll be using local to set Project Specific configuration the last 1% of the time you might need to fuss around with system in work tree configuration but it’s extremely rare yeah I’ve never I’ve never personally had to do it I just know that it’s been done on my system so there you go here’s the set of uh here’s the set of what’s it called ordering so if you have a work tree specific it’s be the most specific therefore that’s going to be the one that gets presented then local then Global then system system is like the it’s kind of like just think about it like uh JavaScript and merging arrays right system is for all users correct global global is not Global it’s not a global list if that makes sense it’s a local Global you know what I mean it’s not a global global it’s a local Global all right suppose you set username to Prime at the system level username Lane at the global level and username TJ at the local level which value will actually get TJ even though TJ does stream but he sucks okay just so you know yeah Global’s the user it really should be it it really should be repo user system for me that seems much easier to understand and TJ catching Strays TJ’s always catching Strays okay shots fed all right let’s see which is stored at the home directory that’d be [Music] Global all right so what is a branch so now we’re going to get on to branching so a get Branch allows you to keep track of different changes separately for example let’s say you have a big web project and you want to experiment with changing the color scheme instead of changing the entire project directly as right now on our Master Branch you can create a new branch called color scheme and work on that branch and when you’re done if you like the changes you can merge color scheme back into the master branch and keep the changes if you don’t like the changes you can simply delete color scheme branch and go back to master so underneath the hood this is what’s actually happening look at this beautiful little little graphic do you like that graphic it’s beautiful huh it’s beautiful does this make sense so here’s a big thing that you need to understand tips just the tips the tips is the commit that is the latest one on whatever Branch you’re looking at okay so you need to know your tips and then eventually they should merge back at some point because that’s how branches work they should be branched off of some uh some they call it the merge base this would be called the merge base we don’t have that as part of this graphic so this is called the merge base or the Le or the uh most common ancestor is one right here and so this is for when you merge it finds this thing right here and then merges things together merge tips use rebates yeah exactly so just so you know these are all commits branches lit like a branch a branch is literally a pointer to a commit that’s it orphaned branches are wild yeah I don’t even know how to create like honestly I don’t even really know how to create an orphan Branch it’s exceptionally difficult to create an orphaned Branch uh it’s just not something you do you know on purpose all right so let’s see because a branch is just a pointer to a commit they are lightweight and cheap this is why when people say branches are really cheap it’s because it’s just a pointer that’s it uh which branch you’re currently running get Branch there we go so I can go like this get branch and you can see I’m currently on Master fantastic remember you should be on Master because we set initial default Branch to master at the start of this course yeah yeah yeah so there we go um fantastic and we’re going to do that and we’re going to execute this thing Bada Bing Bada Boom Confetti feeling good confetti out of my mind all right default Branch we’ve been using GS default Master Branch interesting interestingly GitHub a website where you can remotely store G projects recently changed default Branch to master to main as a general rule I recommend using Maine as your default Branch to work uh if you work primarily with GitHub yeah because if you don’t you have to like go in to every single it’s just a pain in the ass right that’s all it is if you don’t do that you have to actually go into your projects and you have to set it as your whatever other Branch you’re using as the default or else it will use main as the default and then you will get cloned down a repo and then main will be like this empty branch and then you have to undo all of it there you go gitlab has main too and I think newer versions of git has main as default too I’m not sure if G newer versions of git has that as default um like if I go like this uh get let’s see get config remove section um oh don’t do that unset all um let’s see what is it it is a nit uh default a branch there we go and so if I go get config list there we go you’ll notice that I still have this one did I not do this correct am I oh is it lower B oh is it really lower B is it really lower B Branch nah that can’t be right right why why are you still here why por and Maria why are you still here oh it’s cuz I’m not doing gosh I’m so stupid Global globalist there we go I’ve have undid my Global list this is very important to undo your Global list there we go list there you go it’s gone you can see that it’s gone so if I go back here and go like this make dir testy uh testies and CD into testies uh we’ll go in here and we’ll go like this get an it get an IT using Master the name of this initial Branch this is theault Branch name subject to change to configure the initial Branch name do this right here initial Branch name uh names commonly chosen uh instead of master or main trunk Development I’ve seen Dev I like using trunk just to mess with people okay I think it’s funny here get might be old uh get oh it could be old I’m on uh 245 it’s pretty new get uh latest uh version 246 yeah I’m only back I’m only I’m only off by a little bit I used using trunk just to feel something exactly exactly there you go okay so now that we’re here there we go all right so here we go all right how to rename a branch so you go go get Branch uh M for rename right classic M for rename am I right am I right old name new name all right we’re going to set our initial Branch to Main and then we’re going to rename our Branch all right here we go uh let’s just weo back in here and get Branch M Master main get uh config add Global s uh we can actually even do it that by the way you can also do it at a local level so I can go uh nit default default Branch uh what the hell the thing called it’s called main so there we go so I can actually do this at a local level so now only this repo has the default Branch as main whereas all my other ones will still have whatever my Global version is it’s very good to know how to use locals and globals it can be very useful I’ve had to do a lot of things where I have to goof around with different versions all right there we go wasn’t a lowercase B I think the lowercase b was an accident I want to say it was an accident anyways there we go I’m going to copy this one oh my gosh uh okay dang it so it’s gonna my thing requires me to be a globalist I’m now a globalist I am now officially a globalist globalism all right really just Alex jonesing on this thing all right there we go visualizing branches uh throughout the rest of this course we’ll be visualizing branches by the way this is how git does it as well so if you do not know if you go uh man get commit I believe they have it in commit no uh rebase yeah you’ll notice that they effectively do this so I TR I tried to copy a effective version so that way it’s easy to understand easy to see okay sounds good yeah yeah yeah yeah all right let’s see this means a branch called main with three commits a c is the most recent commit as you can see A to B to C Branch there you go so this one right here means a it splits off from a and there’s d and e on something called other branch and B and C on Main so they are diverging branches with the merge base of a all right everyone get that I’m going to be using that term a lot merge base uh answer the questions based on the following diagram which commits are part of Lane’s Branch uh none because he’s a CEO and doesn’t work these days but it’s going to be GH this one bam got it man I’m so good I’m globalist all right there we go all right throughout the rest of this course oh I already answered this one which are part of commits of main uh it’s going to be a b c d got it first try all right VIs izing branches oh we’re doing it again dang we’re going to do primes Branch huh primes branch is EFA or a EF EFA man I didn’t even get close you should already be on the main branch uh your default branch and you can always check with get Branch I wonder if there’s a way to name your default Branch something that would break your system can you do rmrf uh see two ways to create a branch right get Branch New Branch name this creates a branch called New Branch uh the thing is I rarely use this uh command yeah I rarely use this command reason being is that whenever I create a branch I also want to switch to that Branch right right so I typically use get checkout B just because that I mean I’m I I guess I am a boomer it’s hard for me to break that habit but the newer ones is get switch C so I’m trying to show you kids you youngans to use get switch C all right that’s the one you want to do all right I’m just so used to get checkout B I can’t help it so if I use get checkout B sorry I’m old my fossils are creaking you get the idea okay so what this does by the way whenever you create a branch it takes your current location and that’s where it points to all right so when I do this my new branch that will actually create a new loc it’ll create it’ll have the exact same sha or the exact same uh commit yeah it’s your head location so it’s it’s good to know that because a lot of that’s kind of like one of those confusing jumps people have to make oh yeah on itchy there you go all right anyway here we go uh create and switch one called ad classic so let’s just do that right now there we go I’ve created ad Classics uh let’s see and then let’s see run get Branch to verify so I can go get branch and you can see that I’m on ad Classics get that and if I go get log you’ll see that I have ab and c and if I go get log uh main you’ll see a b and c the same thing they’re the same thing I believe if I even go like this uh find uh get what is it uh grep refs something like that right you can actually see this right here so you can see it right here so if I go right here and I go uh cat that you’ll see it’s pointed to this thing and if I cat uh main it’s poed to the same thing there you go makes life easy for you to know these things learning gets sucked yeah learning get well it doesn’t it’s just it’s just time cons it’s a bunch of little things that you just have to learn all right switching branches uh we talked about using get switch to change branches there’s another command you’ll certainly run into and it’s been around for a long time and older developers use it get checkout okay calling us older developers hurts a little bit me in the past me in the past get switch is a newer command that is meant to be more intuitive and user friendly uh it probably is more user friendly because get checkout is kind of like this grab bag because you can also like check out sides of a merge conflict there’s a lot of weird stuff shows the history get okay get developers of a certain generation and that’s me also uh it’s recommended to use get switch over get checkout for simply switching branches that’s what they say let’s okay let’s switch to a branch called Prime all right there we go uh the new way the old way right there you go for this course we’ll stick with get switch right there we go all right switch to Branch main run get branch make sure we’re on there switch back to Classics run this one run this okay I’m not going to do that yo dog uh I’m happy for you or congratulations or I’m sorry there we go we passed I’m not going to switch around but you get the idea it’s just get switched without the- C for create that’s all all right upleveling our abilities will uh use the ad Classics Branch to add a commit to the project without affecting the main branch so we’re going to actually create the D here in other words ad Classics Branch will have all the commits from Main plus a new one all right so we’re going to switch to add Classics we’re going to create a new file called Classics CSV and there we go so I’m going to go uh Vim classics. CSV uh go here I’m going to yank that bad boy paste it in here of course the classics uh you know The Princess Bride I actually watch this every Christmas it’s literally the greatest movie of all time here we go all right so we have this we’re going to stage and commit the file the commit message to start with D all right run commit okay here we go so we’re going to do that one get add this get commit Dash D is great there we go and you should be able to see the commits with the branch with get log we don’t need to do that let’s copy that bad boy paste it in make it happen B bam bam bam got it we’re all in the good stuff so let’s go over here so we’re about ready to start get into some good stuff log flags as you know get log uh shows the history of your uh commits in your repo there are a few Flags you’d like to know short full no I like to I don’t really use decorate decorate typically works well uh if you want to see where things are coming from so you can do get log uh decorate full if you want to see a bunch stuff on Line’s the one I use a lot okay this is the one I always use because if I go get log you get like all this crap but if I go get log on line you get that that just feels nicer right that’s the one I want what the hell is decorate well this is decorated right now and the reason why it’s decorated if I’m not mistaken if I go uh no pager no pager uh no okay there we go all right it’s not doing it effectively decorate it decorates default default version I thought I thought there’s a way what’s the way hold on let me go like this on line uh T out there you go so there you go that that took it off so if you pipe it to another program this is kind like a non-decorated one a decorated one right here shows where you’re pointing at so head which is also pointing to add Classics main is on C that’s what decorate does so get log decorate equals no will not tell you anything about where stuff is at does that make sense and then you can also use git log remember how I talked about graph graph is pretty cool graph uh one line so you can kind of see that I’m just going it’s just all one line right now there’s no there’s no change right now but we’ll get to the point where we start seeing some changes don’t worry we’ll see it we’ll see it uh there we go fantastic I think that’s all I need to do run get log with full decoration we already did all that explain the decorations let’s go we got it we got the confetti we’re confetti out of our mind I’m level seven by the way you guys won’t even understand what it’s like get propaganda hour absolutely uh Kung Fu no get Fu remember git stores all the information in files in the git subdirectory at the roof Ro of your project even information about branches the heads or tips of the branches are stored in get rep’s heads if you c one of the files in that directory it should be able to see the commit that the hashes points to which we already did use find and Cat to find the commit hash of your main branch we already did that one uh what is stored in get ref’s head uh one file each for a commit oh what is in there I forget let’s see it is going to be get ref’s heads is going to be each one of the branch names one file for each branch containing the commit hash of that Branch points that one let’s go let’s go I’m a genius nope we’re not going to watch this branching and get is practically free and it really is kind of the core operation when using git but at some point you have to get that work from a branch back into the main line and this is where merging comes into play now a typical workflow for pretty much every Dev looks like this first we need to update our repository to the latest code this is typically done through get fetch or get we’ll cover those more later you Branch off the main branch and give it a name that kind of represents what you’re working on new feature a you fix the bug create the feature update the docks and create your one or more commits on that Branch then finally you merge those changes back from your branch into the main line typically when you’re at a company this will involve some sort of poll request on GitHub on stash on gitlab but conceptually it’s no different than executing git merge on the command line oh what’s the point of having multiple branches you might ask they’re most often used to safely make changes without affecting your or your team’s primary Branch however once you’re happy with your changes you’ll want to merge them back into your main branch so that they make their way into the final product all right so here’s the visual look at this beautiful thing and then notice this this right here is called a merge commit it’s very important to understand merge commits because if you don’t you don’t understand why rebase is good so merge commit and especially when you look at a log we’ll look at the log here shortly but it will actually show you why uh or how these things kind of exist and why they’re unique and why it allows for log graph to be very nice uh so hold on let’s see what the assignment is just to make sure I don’t get ahead of myself uh first switch back to main next our contents file is eerily empty yep update uh update it to contain this all right there we go now the yep and then we’ll this okay perfect perfect let’s go all right so what we’re going to do is I’m going to go like this we’re going to get check out main oh wait no wait get get switch add Classics get switch main don’t use checkout we don’t use checkout we’re not using check it out we’re not doing it all right and then update this file right here don’t you do it uh get status it’s nice it’s not it’s not mgit all right there we go so commit uh let’s see commit the changes with a message starting with e all right so let’s commit these changes get add this get commit uh e uh let’s see uh contents such contents with a new line at the end why I don’t know why there we go so now we have this one we have ABC uh abc e abc e and ABCD awesome so we should be able to do the whole get log graph all look at this nice bad boy look at that look at how graph does that it’s nicer in one it’s it’s nicer in one line honestly one line you can see right here so there’s ad Classics it’s been branched off at that point and here’s this guy so it’s a nice way to look at all your stuff there you go why not use checkout it’s just older switch is the one right all right there we go fantastic right so I should be able to just do that everything should be good there we go confetti it out of my mind all right merge commence we are merging two branches together with diverging history look at this thing right here the diverging history simply means that main branch the one we branched off of at Point a has commits and we some branch have added more commits main has B andc our Branch some branch has DNA that means when we merge we need to be able to create a new commit that represents these two diverging histories as one this is called a merge commit and it’s the only commit with two parents the process for a merge commit looks like this first we need to find the merge base the merge base also called the best common ancestor is the nearest ancestor that is in common to both branches and in this case that would be a we then play main Branch’s commits into a new commit and then we play some Branch into that same commit when all the changes are in that new commit we commit it to Main and in this case we call it f and we give it two parents one parent pointing to C from the main branch and the other parent pointing to E from some Branch if you use G log you will actually be able to see the diverging from a the two diverging commits and then the coming back together in F merge commands are the result of just merging two things together yeah so what a merge commit does or how a merge works is that when you merge in something it takes it finds the most common ancestor or the merge base then it merges Main and this one together to make one Super One make one super commit adds that to the front of the branch that you’re on and then has two parents which is where you came from does that make sense so if we were to merge Vim Chads only in main while using this we would find the merge base or the best common ancestor uh in this case a replays those two commits bam creates a special commit called a merge commit and then this thing has two parents there you go fantastic right uh so in our current webflix history we have this we have main abc e and we have ad Classics which is D so when we merge we should have this like we should have an F commit that’s going to be this little merge Branch right here so let’s just do that now get merge ad Classics I assume that’s what we’re supposed to do and we wanted to go f so that way we can denote it there we go we’re going to write that and we just did it perfect right so now if I do this whole on line decorate graph parents business hell yeah that’s a lot of stuff you can see right here classics branched and then came back together and you can see right here that this is a merged base because it has two parents or not a merged base sorry uh why would I say merch base it’s not a it’s a merge commit because it has two parents never worked with two parents children yeah most children in get do not have two parents this one does so there you go this you can actually watch it because this one points to this Commit This one points to that commit they both point to the same merge base there you go now that everybody knows feels good right a lot of arch users out there confused about merge commits all right so logging has to be one of the best tools in the git belt because git has extensive logging and observability if you need to recover work visually understand how you got to this point commits along the way messages that you have created where the branches and tags are including in your repository your remote repository and of course all the tags that you currently have and much more than logging has it let’s break down a Quick Command right here get log on line graph decorate parents now this looks like a lot of options but actually it’ll make a lot of sense once you understand what those options mean one line will give you a condensed view of your history first off the hashes are shortened to seven characters which is the minimum amount get requires for you to specify hash also you get the commit message this gives you a nice quick view so you can can see what happened in the past graph will draw all the little lines so you can see exactly how your commits have diverged and come back together through merges decorate will give you the branch and tag information this can be nice to see how far you’ve straighted away from a branch or where a previous Branch might be parents will give you the parent commit upon every other commit this can be very nice for merge commits because you can see where the two parents came from to create the merge commit go ahead give it a try yourself oh we already did this I already kind of explained this beautiful niceness right here uh each Aster represents uh a commit in the repository we actually already talked about all this this is fantastic why does the first uh line show three commit hashes uh because it’s the first commit in the history no because it’s a merge commit with three parent commits no because it’s a merge commit it shows its own hash and the hash of both of its parents we already talked about that I think that makes sense right wait where did where did my log go oh I didn’t print out the log there you go you can see these are the commits right here these are the lines this is its sha and then its parent Sha see that’s parent parent parent parent it’s commit Shaw parent that’s its commit Shaw this is its parent it’s the parent or the shaw it’s parent the shaw this is Batman right here no parents beautiful asky beautiful asky there we go all right merge logs let’s see you can output your get log decorate graph parents aside from the hashes look something like this we already taled well we already did this we just got to answer new questions why is the weird diagram EG all these things uh whoopsies I I didn’t mean to click that it’s what happens to your brain on Arch Linux after 10 years that’s not what I wanted to do um it demonstrates the branching structure three commits were merged into the main no it demonstrates adding Classics was merged into main boom that’s what it demonstrates it’s beautiful I want to make sure you guys get it all right a fast forward merge does everybody who knows what a fast forward merge is I’m curious type zero if you don’t know what it is I’m actually curious about this well lot of zeros dang dang that’s a lot of zeros a bit I’m shook I’m shooking right now okay the simplest type of uh merge is a fast forward merge let’s say we start with this one main branch and then delete vs code now we run this on Main get merge delete vs code because delete vs code has all the commits that Maine has get automatically fast forward merges in other words the best way the branch you are merging onto if the tip of that branch is the merge base then you can fast forward merge does that make sense yes in other words I tried to one more time I tried to that’s why I’ve been trying to say the word merge base remember a merge base so for these two commits right here a mer the merge base is this right here so in this example this one uh this one was main this one was add Classics so the merge base was this right here so if Classics was branched off instead of such contents the merge base is the tip of the branch you are merging on therefore you there’s no Branch right it can just literally update the pointer the end kind of sounds like rebasing main no it doesn’t sound like rebasing main that’s not what rebasing does we’ll explain what rebasing does in a moment rebasing has nothing to do with merge people sometimes goof that up a little bit it’s not what it does um all right because delete vs code has all the commits main has get automatically does a fast forward merge it just moves the pointer of the Basse Branch to the tip of the feature Branch that’s all it does bada bing bada boom all right uh we’ll get to mer we’ll get to rebase here shortly so you’re just adjusting head pointers that’s pretty much what you’re doing so when you’re doing a a fast forward merge you just main just now points up one right assignment uh because ad Classics branch has been merged into main we don’t need anymore delete that Branch okay we’ll delete it uh create a new Branch off of Main update titles uh let’s see add a commit to that branch that updates titles MD file and add Curious Case of Benjamin Button as the final entry in the list and then use G okay we got to do a couple things here hold on hold on let’s delete get a check not checkout switch de see I I always mess that one update uh titles titels uh there we go uh let’s just open this up and go add classic contents what we doing titles uh Curious case for Benjamin Button is that the one we’re doing titles MD we’re going to add The Curious Case of Benjamin Button there we go we’ve added it so now we have that and then we’re going to just create a commit with G all right get add this get commit dasg a curious case all right there we go uh run one line to see what we’ve done here get log one line you can see right here here is update titles here’s main Main’s one behind you’ll notice that this would be the merge base right so Main is currently if I were to merge this onto main main would also be the merge base and that’s very very important to know all right so let’s go in here let’s do one of these there we go does all this updating bada bing bada boom looking good looking good confetti let’s go all right so fast forward so now what we’re going to do is we have this diagram and now all we need to do is just merge it back on so we’re going to switch to Main and we’re going to merge update titles onto it and you’ll see what happens here so get check out main sorry I did check out not switch get log uh you’ll see that I don’t have G on here if I go on line it’s probably easier to see no G if I go all you’ll see that g does exist only in update titles there we go and then we can go like this graph and you’ll see right here that g is on the end so it’s just straight ahead so now if I just simply merge get merge uh update titles you’ll notice that it does a fastforward merge and now notice if I go like this get log one line notice that this one had a branching Factor this one does not there’s no Branch there’s no merge commit uh and you can see by me going like this get um uh parents so you’ll notice that this one is a merge commit because it’s merging e44 and 7 a0 this one is not because it’s just having its parent to be one behind very important to know okay that’s a very important thing to know people just you know they just don’t know these things all right there we go I hopefully I did everything correct and I didn’t accidentally go forward sometimes I go forward too fast and screw everything up all right so now we’re going to go to rebase everybody thinks rebase is the most awful thing ever and it’s on Twitter if I go to Twitter I guarantee you I search up the word get rebase and there’s going to be something awful up at the top get rebase or hopefully it’s going to be me saying people don’t understand it all right mer all right here we go there you go look at that see open Slack someone help with rebase branch in Flames sends thoughts and prayers close the slack go to gym rebase Force push I up I get rebase like look at this it’s just it’s an endless supply Hacker News is having a get rebase discourse again I like this Comon a lot see it uh blot the blah blah blah blah blah blah blah blah blah blah again they hate this one I think this is the way okay personal opinion rebase is tight rebase is the only way to do it something about get rebase thanks yall for coming I don’t even get this one okay I don’t even get this one this one must be get rebase this is get rebase so you got to be careful when you’re rebasing okay you could screw up the world I just want you to know that okay you could screw up the world rebase might just be one of the most misunderstood features of git where the fear typically kind of comes from is that somebody changes the history of a public branch and when I say public Branch I mean a lot of people rely on this Branch for their repos as well and of course when they pull and the changes have been somehow altered in the past all these conflicts and these weird git errors start happening and it just causes a disaster for everybody and then everyone says rebase is terrible I will never use that only use merge well skill issues you used it wrong to understand rebase you simply need to understand its primary use case rebase helps you to take the diverging commits from one branch and move them to the tip of the base branch that the feature branch is based on now that sounds like a mouthful but it’s actually pretty simple so take this graph right here we have two branches Main and Feature Feature branches from Main at commit a and Main gets B and C added to it while the feature branch has d and e now we want to be able to take the feature branch and get those changes from Main now with your current knowledge you would probably merge main into feature creating a merge commit and that does have consequences and we’ll discuss more about that in part two but for now let’s focus on rebase rebase is is going to allow you to move forward feature Branch from diverging at Point a up to diverging off of Point C allowing for a fast forward merge if you wish to get it back into Maine this also allows you to maintain a merge commit free history and again there are some consequences for that and they can be quite nice and that is it you’ll notice this gives you the opportunity to do a fastforward merge and kind of have a free of merge commit history this will allow for some Advanced G features to be more easily usable if you maintain this type of workflow okay so rebase is very very simple all rebase does is update where your branch points to this is well okay I mean technically there’s actually a couple different use cases for rebase but let’s just start here this is the first one so pretend we had Main and we had feature Branch if we were to get rebase main on our feature Branch it would take the pointer which is which it’s parent pointer it’s its merge uh base is pointing at a and it’s going to go all the way to C then replay your commits d and e and now you have a linear history which means you can do a fastforward merge okay so it’s actually really really simple and you’ll notice that DNE even though the commit message is the same you will now get new commit Shaws why would you get a new commit Shaw well that’s because D its parent is no longer a it’s C so therefore D has a new sha e has a new sha because D has a new sha now you have to fix all the conflicts if there was a conflict while rebasing there would be a conflict while merging if you’re if you’re experiencing continual conflicts it’s because you don’t know what you’re doing and I will explain why in a little bit okay okay buddy can you calm down again whenever I see some whenever I see somebody say something about all these conflicts and all this stuff with uh with rebase what it makes me realize is you don’t know what rebase does and how to and how to get around stuff so it just moves the merge base exactly it just moves the merge base and that’s really important do you talk about conflicts and G two yes so git one is all about using git for yourself get two is all about using it for a team so it takes the code from d and e and applies them to uh code version C yes so literally so the exact operations of get mer rebase does this so let’s say we’re on feature branch and we say get rebase uh main what happens is that we check out main I’ll call that the target Branch we check out Target Branch we then take Source branch and apply its commits to the tip of Target Branch then we update Source Branch to point to the new uh to the new tip why is it uh important to change basis uh reverting so people really hate get revert it does make things better when you need need to revert so reverts typically happen in larger companies if you’re just working with like two or three people you’re probably never going to revert anything and that’s fine but if you have say a 100 people working on the same repo and there is a test that needs to go out that day and you accidentally screw up Main and you need to unscrew up Main and they can’t wait for you to go okay this is going to take me a couple days to fix you have to revert your commit out of the history and then you have to re-release into production the reason that’s nice if you properly do what I consider the best way to use git which is to always rebase right so here’s ABC you always rebase such that you can do Fast Forward merges and whenever you do this you uh you take this and you merge it into a singular commit right you squash it is what’s that called is that if you run into a situation where you need to use revert or revert I always I never know how to I never know how to say the word revert in that kind of tense uh or in that kind of sense I always call it revert I never I don’t know what to do here anyways when you do this it then is really easy to remove this right always rebase in local branch I rebase in public okay that’s crazy don’t rebase in public you can also fast forward merge too yeah just do it with idea that’s not a good way to do things I’m just throwing it out there knowing how git works and setting it up so that it can be very easy to change things but uh but but sometimes I just commit a just a lot of commits you should you should commit early and often okay this is a good way to do things committing early and often is great do that but do you lose commit history when squashing it depends you loose your history of your local changes and that’s okay you can do that you can squash them down to a single one so that way when you merge back into the main branch the public Branch it’s just one commit now maybe you want those in two commits if you want them in two commits then squash the commits into the two ones that you want maybe you want them in all the commits then keep them all right you can kind of choose what you want to do cuz when you revert you can do the same thing as you do in cherry pick and provide a list of Shaws to like take out or put back in uh get rebase interactive is the best thing that is get rebase interactive is very very nice and we’ll do that for when we’re squashing right why would you go with interactive rebase and squash your commits into a single one instead of uh merging with a squash uh I do that that’s how I do it so locally whenever I’m about to do anything I get all my commits prepared I rebase I squash and I push things up try making yes we can do this too uh this is one good way to do things but we’re going to get to that that’s later on right I’m not trying to we’re trying to stay on task here okay lot of questions rebase is always a lot of questions because rebase gets the biggest bad RP from the internet and most people have absolutely no gosh dang idea what rebase does and so then they’re like oh but rebase is bad because it’ll screw up your history and you’re like you’re right you can you can f yourself up with rebase absolutely you can chop off your finger with a skill saw it doesn’t mean skill saws are bad it just means you should probably know how to use a skill saw before you just start slanging that blade all around right I know that’s crazy both rebase and merge can be used to integrate changes from one branch into another in some sense yes very very true anyways all right rebase versus merge BL blah blah blah we’re going to do this one uh blank can add additional uh commit and blank does not rebase merge can add an additional commit rebase does not correct so if I’m rebasing and there’s never conflicts can I still lose history for months go so I’m not sure what you mean by losing history people say that cuz they don’t know what it means what are you attempting to say if you have history that’s in a public Branch you will not change it unless if you interactively squash rebase and then Force push which if you do that you’re a bad person you should be fired that’s crazy don’t ever do that you will you will actually ruin everybody’s life you actually will yes conflicts happen whether if there’s a conflict while rebasing there’s a conflict while merging that’s a good good thing to understand nobody wants to see million see see your millions of commits just squash it yeah a lot of people prefer the squash all right we need a new Branch uh feature branch and to be able to practice our rebase we want to not include some of the commits in recent main uh we’re going to use get switch command and create and switch to a new local branch called update Dune but Branch off the decommit you can supply a commit hash directly and get switch so we’re going to do this right here we’re going to get switch Branch it off of Dune okay people so we’re going to go like this get log uh on line and there we go so D is that bad boy right here get uh switch dasc update Dune and from that one there we go I said update done you get the idea so if I do that another little oneliner right here we’re going to see this beautiful part right here if we do on line all you’ll see that head is pointed right here update Dune I’m close enough it’s not my fault I didn’t copy pasta what can you do okay so now that you see that this is good this is good good good good good stuff there we go we’re going to paste that in we should be wait what oh update okay it’s actually requiring me to do that get Branch M up uh update uh done to update Dune I don’t know why you got to be like that get boot Dev okay you can’t let a man have oopsy daisies here so you never push until your feature is done or you need the force push yeah I I don’t I don’t I don’t push my features up regularly I keep them and I commit them and I get everything I want and then I push it up and then there’s some there is some there is some a little bit of style points here of how you want to handle things after that some people don’t like to make changes uh some people don’t like to make changes in the sense of having to force push again so all PR changes will become their own um commits and then squash that one more time and then merge it when it’s ready that’s one way or you can merge your PR changes back into a single commit and and then you have to force push it so it’s kind of like you got to Riz get your own way and some people prefer the you know the the pr changes to be their own separate commits some people don’t that’s the rizing part you know also if you have really shitty cicd pipelines you may find yourself constantly you know doing that and get Force push every five minutes with amending draft commit yeah that’s me called using get we’ve all seen that we’ve all seen it where it’s just a wall of test test test test test test test test test test test test test test test it’s just the worst yeah I get a bad feeling when not pushing for several days okay I I mean that’s fine you can have of either no one’s telling you not to it happens it is kind of weird right I feel bad not pulling I like to pull pretty regularly all right so now we’re going to rebase main this will do the following check out main remember I called that Target Branch replay one commit at a time from J diesel onto Main update J diesel Branch support to the latest commit the rebase does not affect Maine while J diesel has all of its uh had all the changes from Main there you go so it’s going to pull in those changes so our assignment let’s add two commits to Dune Branch add the following quotes to Dune the spice must flow and then for that will be H and this mind killer all right let’s do this okay Dune is a really good movie okay I don’t care what you guys say all right wait spice must flow okay good uh get status so you can see that get add this get add this get commit Dash I think it’s h uh spice me daddy why not uh go into here that was H we’re going to do I grab that one go back in here do that save that add get commit fear me Daddy I think so I think that’s right I think we just got it okay so I should be able to get log and see this thing so there we go you can see that right here in fact I can go like this graph would make it nicer so you can see right now that I’ve branched off of D you can see my little Branch off of d right here that goes up and does uh does this right here H and I there it is right so you can see the branch right here this is the main line This is the uh the new line that we’re doing what is dash all it it lists every last Branch right so if you to list every last Branch you can I believe you can also forgive me if I get this wrong I believe I can also go Main and update Dune right you can also specify which branches you would like to see how they do what is happening with that here let’s take a look at that so you’ll notice right here if you remember this right here was when we did our merge B our our merging and all that fun stuff right so this has update titles and Main pointing right here do I need to I don’t think I deleted update titles did I did I forget to delete update titles get Branch delete update titles are you sure you want to delete it Force get the hell out of here all right all right there we go so you can kind of watch this thing move right so there there was remember we had a split at one point right here that had DNE so this is the merge commit from DNE so if I go here I forgot to do parents this will make it more clear so you can see right here this is the merge commit for from uh which one is that one from E and D that’s the one we created earlier this right here is our current One update Dune so you can kind of see each one of the lines forming and we split off uh we split off on D right here so the split went up this way to H and I so it goes i h d CBA a for update Dune and for main line is going to be GF e D or is that or actually it’s going to be gfd e CBA I believe that’s how that that’s the ordering there you go that’s that’s how you read it you read it from top to bottom left to right classic real real classic right there all right Perfect all right we’re going to do those two things we have those ones we’re going to run one line I like mine where I did run line main you can see here’s a more graphical depiction of it all right you can see that so now our goal here is to rebase it and so we’re going to have uh does it tell us to rebase it I can’t tell finally while still on that we want to rebase or change it so when we rebase them you’ll notice right now here let’s go back to this thing you’ll notice that we Branch off of D for I and H so when I go like this get rebase Main and reexecute this you’ll notice it got a lot more simple we are now right here it’s now branched off of G which makes it into a nice linear history all right we just moved our Branch forward you’ll also notice oh I I didn’t I didn’t save the output or else you’d see that the the stuff all changed there you go pretty straightforward right there you go no conflicts why would there be a conflict we edited different files so remember conflicts will happen universally since we do not have a conflict in a merge we’re not going to have it in the rebase pretty much either uh there might be some Edge case where that’s not true but I can’t think of why that would ever be true because a conflict in its core happens because git has three operations add delete modify and so if two operations modify the same line it can’t do it it doesn’t know how to merge those two things because git operates on a line by line basis it does not operate within code because once you operate within code it has to understand the intent of code and therefore it can’t so therefore it’s going to say hey since I can’t understand the intent of code you’ve modified the same line you need to do something about it I don’t know how to do something about this does that make sense all right the advantage of merge is that it preserves the true history of the project this is true you know where all the branches happened and where all the merge commits happened it it shows when branches were merged and where one disadvantage that it can create a lot of merge commits which can make history harder to read and understand which can also make it harder to manipulate history with uh reverts and reverts can be a strategy especially in bigger companies I had the revert at Netflix probably 10 times in my life right it’s real I’ve had to do it comments can cause conflicts I’ve don’t know about oh comments as in comments and code yes comments and code yes a linear history is generally easier to read understand and work with some teams enforce the usage of one uh of one or the other on their main branch but generally speaking you’ll be able to do whatever you want with your own branches it’s true how painful was it not painful at all uh when it came to that because I always did I always did the same stuff I never merge committed I always did all my stuff really nice and made sure I had a single commit so whenever I had to revert which did happen uh all I did was just revert commit revert commit walked away right easy easy peasy right warning you should never rebase a public Branch like Maine if you do this you will destroy your life and what I mean by that is when someone pulls it will say your histories are out of sync and then you’ll have this huge conflict problem and then you have to effectively undo everything uh it’s generally good maners to rebase a public Branch onto your own personal branch all right hold on rebase a public Branch onto your personal Branch that’s kind of a confusing question I think what it’s saying is rebase a public branch and change its history if that’s the case no that’s bad there you go rebase and get merge are different tools all right we already talked about this it’s generally okay to merge changes into your own uh private Branch or to rebase your branch on top of a public Branch yes this is [Music] correct all right undoing changes one of the major benefits of git is the ability to undo changes there are a lot of different ways to do this but first we’ll start by going back a commit history without uh without discarding changes all right we have a little story you guys ready for a little bit of a story I don’t even merge I just pull damn it’s crazy why would you do that let’s see okay the new internet webflix tried to add his favorite movie to the titles file but overwrite the entire file by mistake to simulate that on update Dune Branch go ahead and overwrite titles with just one line The Internship oh Vince Von oh Vince vaugh all right I don’t know why that happened I think that’s what they’re looking for oh he actually doesn’t even want that he want the entire file overed there we go that’s what that means if you’re wondering this just means redirect output but it redirects output and destroys the file double carot redirects output and appends to the files all right make sure the file is changed by running get status and then commit with-j all right uh get add this get commit J interns am I right there we go fantastic am I right am I right am I right all right get reset is a command that can be used to undo the last commits or any changes in the index by the way I use reset quite a bit okay not just soft either also hard but soft actually soft reset is an amazing thing to use and it becomes exceptionally good when you screw up a revert cherry pick or a rebase and so it becomes really good the get reset soft I know some of you some of you prefer hard but hard isn’t always good okay it’s not it’s you can’t go hard all the time you got to go soft sometimes trust me on this one I’ll show you all right get reset command can be used to undo the last commits or any changes into the uh to the index staged but not committed changes and the work tree unstaged and not committed changes so we can do re get reset commit hash or it it really shouldn’t be commit hash here this is kind of a oopsy daisies it should be committes commit is a term used by get to say something that looks like a commit so it’s some sort of hash or something that can be calculated into a hash right uh the D- soft option is useful if you want to go back a previous commit but keep all of your changes committed changes will be uncommitted and staged while uncommitted changes will remain un are staged or unstaged as before so our current branch is right here it should be a commit J now we should be able to go to commit I um by doing a soft reset so I can go like this uh get reset soft now normally it’s said to go uh in here and go get log one line and go and grab I and do this right here and go and get reset I you don’t have to do that you can also go if it’s directly in history you can go get reset soft and go head which is where I’m pointing to and then the amount of steps you want to go back so I want to go head one back so that’s going to be to I there we go we did a reset soft that if I go like this get status you’ll see that I have the titles get diff uh staged you’ll see that I’ve deleted everything for internship uh get diff you can see there’s no changes uh no uncommitted changes to the work tree and if I go get log one line-1 you’ll see that I am currently on I pretty cool right so I just did I undid those changes while maintaining the changes available if you don’t see why this is useful in rebase I’ll show you later okay don’t worry we’ll show you we’ll show you yeah it’s good huh I like it I mean I personally like that there we go uh J should be gone for the commit log there we go we should run this thing yes uh yeah git log uh G log uh get oh my goodness I showed this earlier git log p on line is is really nice too uh on line-1 cuz it’ll show you the previous changes so you can see fear’s the mind killer that was definitely I you can see that right there I’m more of a mixed kind of guy okay okay interesting interesting I can’t really argue that can you just keep oh dang I was hoping I could get more I was hoping I could get more uh get add- P do you use this no I never do I never do patch stuff I never do any of that interactive adding honestly it’s that so this right here I would definitely use with an editor it’s way way nicer um I’ve never used I’ve never used uh that no I’ve never used that yeah if you’re going to do patch adding so uh get or um uh man get add uh dasp right this is interactively choose Hun’s the patch so hunk I don’t know how they determine the size of a hunk uh but hunks uh is just like somewhat of a change so long as there’s enough lines between two changes it goes uh here you go here’s hunk one here’s hunk two and therefore you can actually say I want to add this one but remove that one but if we do it with interactive it actually makes it a lot easier here I’ll do it really quickly okay I’m going to do it really quickly okay there we go uh let’s just there we go that’s good enough uh let’s bring it right up into the middle I’m going to just go in here we’re going to go in here I I know I’m screwing things up who cares uh’s let’s just go like this remove me right there we go I’m going to remove me so now when I go in here I can actually go like this I’m going to add one up to the top and one to the bottom and when I go in here you’ll notice that there’s two hunks those are hunks right there so if I were to go uh get add uh that- P you’ll notice it’s like hey do you want to Stage this particular hunk no I’d much rather personally go in here and go like this and so I can go I want to Stage that one and I want to remove this one now I only have one change it’s much easier to use a graphical editor for that stuff split is useful split is useful yeah so anyways all right let me just undo that one uh and then go in here and go get reset uh soft so now here’s a problem here’s a problem everybody I goofed up right now I have this commit that isn’t quite right and all that I bet we could find the other commit couldn’t we oh we could but we’re not going to we’re not going to uh get status there we go get diff uh stage there you go you can see all the stuff I’ve added to it that’s fine all right so get uh hard will undo everything so get hard will not only undo the changes and move your branch back it will also clear out your index and your working tree assignment get run status to confirm this one uh run get reset hard to undo the changes don’t move on before you’ve done this okay there we go so I can go like this get reset hard uh cat titles this now you’ll notice everything’s good there we go so I did a reset hard which will change which will undo the index and the working tree so like changes that are unstaged so that is not no because un well unstage yes it does unstage so it just depends so watch this so if I go like this uh let’s go like this I’m gonna add a line right get status this is an unstaged change to the working tree get reset hard get status it’s gone very important but so if I uh get back here but if I CLI this Foo and I say Foo get status this is an untracked change very very important so when I get reset hard get status you’ll notice that the untracked change because it hasn’t added my working tree yet this is an unknown file it does not get reset hard important to understand that okay important to understand those things there we go we did all that let’s grab that let’s paste that in untrack get so fun with get ignore it can be very annoying with get ignore yes uh there we go danger I want to stress how dangerous this commit or this command can be if you were to simply delete a committed file it would be trivially easy to recover because of the uh it is tracked in get however if you use get reset hard to undo committing that file it would uh it would be deleted for good yes you can delete by accident forever so if you have a change that you never committed you have an unstaged change hanging out and you do a get reset hard you can lose all of it very important to be careful about that so be careful about doing that okay be careful reset to a specific commit if you want to reset back to a specific commit you can use get reset hard command to provide that and you have to provide a hash this will reset your working uh directory and index to the state of that commit and all changes made after that are lost okay so this is this isn’t technically true uh I don’t this must have escaped my eyeballs but they’re not technically lost forever you can still recover them via uh ref log or by looking at uh you can you can peruse through a lot of the G stuff and you can cherry pick back in this is true but it can be a bit of a pain in the ass to do that right again be super careful in part two of the course we’ll cover more advanced stuff uh ref log has saved me many times it should ref log is very very good get reset hard blank undoes the commit changes delete uh deleting the changes forever unfortunately that is not sure I’m not sure how that escape me it perceiving deletes them forever it removes the changes from your branch and moves your branch head so it appears that they never existed you can still get them right anyways I want to stress oh let’s see hold on when provided a hash get reset hard blank moves your current Branch back to an older commit and destructively discards uncommitted changes correct there you [Music] go all right get remote uh often our FR ofies read co-workers make code changes that we need to begrudgingly accept into our pristine bug free repos this is where distrib uh distributed in the distributed Version Control System comes from we can have remotes which are just external repos which mostly the same get repo history as our local one all right that’s the nice part it’s a distributed Version Control System right you get you get the idea uh when it comes to git the CLI tool there really isn’t a central repo GitHub is just someone else’s repo only by convention and convenience have we as developers started to use GitHub as a source of Truth for our code so GitHub is just is just another version of your repo and that’s very important connection to make because if you don’t you might find yourself fairly confused by a lot of stuff let’s create a second repo called webflix local and let’s see as a sibling directory to our original webflix so we’ll do a little CD blah blah blah blah so I’m going to go make derb back webflix uh webflix local there we go all right let’s see run and submit the CI test from inside this one oh we need to get AIT to create a new empty repo all right uh let’s go like this let’s CD back back webflix local get AIT jump in here jump over here paste that in all right we’re moving we’re moving fast adding a remote and get another repos called a remote the standard convention is that when you’re treating the remote as the authoritative source of Truth such as GitHub you would name it origin there’s also some like basic rules around origin that can be applied there’s some convenience defaults and all that by authoritative source of Truth we mean that it’s one uh one you and your team treat as the true repo it’s the one that contains the most up-to-date version of the accepted code some people call it Upstream Upstream can be kind of unique uh if you do your repo so this depends on your uh working order some people will have Upstream in a different fashion um so then origin if you’re working in a bigger team you’ll often find that origin is your fork of the of the remote and Upstream is the authoritative one Upstream there you go does that make sense it’s good to kind of know this and you you’ll see this often uh origin is typically the one you uh work with and so if you’re on a small teamworking by yourself you don’t need to do this this would be kind of stupid you just need this uh you don’t need to create a bunch of process for no reason but you do want Upstream when there is a lot of people working that’s when it makes sense Upstream is usually when you’re working from a fork in common F yes yes uh There He Go is that on top of branching yes a remote is a repository right so so we’re going to do that right here so here’s the Syntax for adding a remote and it can be a URI remember a UR URI is very very important to know that so what we’re going to do is we’re going to go like this get remote add origin back up webflix remember a remote is just another repo there’s nothing that says says it can’t be local okay it’s good to know that cuz sometimes people think remotes are only available like on GitHub it’s not true it’s not true it’s not true anyways oopsies I ACD went back all right let’s go forward there we go let’s copy this one all right so let’s copy this thing there we go we have our remote POS uh properly set so we can fetch adding a remote to our get repo does not mean we automatically have all the content so if I go like this get log you’ll know there’s nothing here nothing ain’t there fetch brings in all the changes this is very important so if I go fetch it’s going to bring in all the changes this is fantastic right so if I go like this get log not look what happened look what happened look at it would you look at it nothing’s happened right well the reason why nothing has happened is because we didn’t actually update our stuff and that’s important it didn’t update our branches yet this is good to know this is very very good to know and so we can also go in our get objects and we can find things so I can go like this get uh I can go uh find get uh let’s just find and get you’ll see that up here you’ll see a lot of these things right in here and you’ll be able to recognize some of these there should be a 78 right a 78 in here there you go there’s our first one right there that’s our first commit that’s commit a if I’m not mistaken 7805 uh get cat cat file- p785 look at that look at that a how nice is that huh get fetch money it’s like it’s like it’s for free okay so there you go so you can see that we have all of our commits they’re just not integrated yet so that’s important it’s important to understand that that happens there we go fantastic so now we actually need to uh you know we need to do something about it now bringing the remote uh into this we need to run get fetch oh I apparently I did that apparently I uh apparently this one is it didn’t actually check to see if I did a fetch first easy I ran ahead I ran ahead I ran a little too fast okay I ran a little too fast all right to demonstrate this run get log which we already did we actually already did all that I’m sorry I ran so fast all right I can’t help it so look at this beautiful thing we can actually do this right here you can actually log a remote Branch versus uh versus the origin like we can actually you can see the differences between them as long as we’ve fetched and did all that so pretty pretty exciting time so I can go uh so if I go get log doesn’t work get log main nothing really in there if I go origin main you’ll see all these fantastic absolutely beautiful uh oh did I actually screw up our uh I think I might have screwed up our stuff no I didn’t all right let’s go let’s go I’m a genius I’m an actual genius all right all right merge we can merge branches with a single uh local repo so we can actually merge in the remote Branch yeah yeah exciting what music is playing the music that is playing is going to be bits and something what is it bits and hits which is this is Skyrim but Loi you are a genius I’m not sure about that okay uh can you explain the difference between branches and Upstream Origins origin or remotes so the second part of your question are called remotes remotes oh this guy’s being really annoying here hold on there you go you’re banned forever from YouTube I don’t know how to undo it so if I don’t click this button it’s done it’s forever uh dang it just it literally just left sucks to suck all right uh these are called origins or not Origins these are called remotes now remotes are just repos branches well they’re branches they’re just they’re just pointers to to uh commit within a repo and so there’s a big difference there so an a repo can contain many branches and they don’t have to be the same set of branches branches are just pointers to commits does that make sense so again a remote would be or a repo is just a collection of commits a branch is just a pointer to a commit it’s a mutable pointer to a commit a tag is a non-mutable pointer to a bit uh a commit it took me a couple times to get that right GitHub is just one large gate repo that’s all it really is it really is just one large gate repo they do a lot of really crazy things so all right so now let’s merge this stuff in so I’m going to go like this get merge uh origin uh main so I’m going to merge the main origin into my origin right here uh so if I go get log now you’ll see all the beautiful stuff this Curious Case of Benjamin Button everything’s looking real real nice fantastic so I’m going to go like that I’m going to grab that we’re going to grab this bad boy in confetti time [Music] yes there is no so this idea of local and remote it’s it’s remember git is a distributed Version Control one repo is not somehow the authoritative source and another repo the downstream Source every every repo is its own repo running and you’re sinking between them so you can actually have many authoritative repos it’s just typically to make life super easy you have one which is GitHub and then you pull and push that so everybody can pull and push to the same thing does that make sense there we go all right GitHub blah blah blah blah so remember GitHub is not git is not GitHub GitHub is a product by Microsoft git is a source control GitHub is a way for Microsoft to make money and to scrape your data and to collect it all for the AI in which it’s attempting to create Junior Engineers that cost less but still cost a lot and then to uh and then to use that to get companies to pay them yeah okay now that we understand what github’s purpose is which is to steal your data that’s why they give you free free repos now let’s look at this all right AI alert yeah create a GitHub account we already did this one assignment all right run all checks ensure that your GitHub user exists and is authenticated there we go I already have it I already have it authenticated and all that fun stuff so there we go all right get up repo just like we created webflix local repo and use webflix as a remote GitHub makes it easy to create remotes that are hosted on their site all right perfect we can create a new repo so hold on before we do that I got to go like this GitHub the primin web flick I believe it should be there or did I name it something else I didn’t name it anything so what I’m going to do here settings let me go all the way down to the Bippity bottom delete this suppository I want to delete it uh I have read the instructions uh the primagen SL webflix there we go delete this one holy cow I’m going to need to do I’m going to need to give a stool sample after this to really get everything done whoopsy daisies wrong thing there we go do that thing all right assignment so I may have to darken my screen for this because I don’t know if I have to type and stuff create a new repository on GitHub called this okay let’s do that right now uh go on here actually I can just go right here create new repository let’s call it a web Flix there we go select owner the prim engine there we go create go here we have a new remote right there fantastic looking good oh no we have too many tabs open all right authenticate your uh local G configuration with your GitHub account I recommend installing the GitHub CLI with one quick installation I already have that uh GH authoriz authorization and then do that one let’s see which one are we doing that in let’s see add a remote in your webflix repo there rep points that one okay so that’s webflix get remote add origin for webflix which is right here there we go be sure to place your username and do get LS remote to make sure it’s all done correctly get a uh LS remote there we go I just have that bad boy right there do I need to push up my changes I don’t think I need to push up my changes it doesn’t seem like I have to push up my changes but we’ll find out yay I don’t have to push up my changes all right so there we go get push origin main all this does is pushes up your branches changes to the remotes right so I can actually so with webflix local I can actually push into webflix and so therefore from webflix I can push into the remote um so here just to just to show you that I go like this get Branch uh get switch uh we’ll call it Foo and go get push origin Fu there there we go so if I go back to this guy I can go get branch and you’ll notice fu is now there Fu was just pushed up from one remote into the next that’s all we’re doing is I’m pushing it to a repo and you can put permissions and all that on what can be done and blah blah blah blah blah that’s what that’s uh that’s what it does so there you go the GitHub is not like that crazy complicated in that sense it’s just git the crazy part about GitHub is all the managing and making it scale and all that other stuff uh get Branch uh defu there we go all right all right what do we got to do here do I got to push up all my stuff yeah yeah yeah yeah yeah yeah yeah get push origin main there we go I push my main throw that in there run all checks confetti out of my mind there we go have we gotten to rebasing yet we went past the basic rebasing yeah yeah yeah yeah yeah let’s see pull H fetching is nice but most of the time we actually want the file changes yeah there we go we can go pull remote Branch we already did that in webflix and so if we were to do this again uh we’d be able to do it uh from you know up from the remote let’s use GitHub UI to commit a change to our repo and then pull it down navigate to GitHub uh navigate to Classics uh edit this file add a new line all right so we’re going to do this right here watch this one this is going to be a little bit wild we’re going to navigate to Classics we’re going to edit this one by hand we’re going to throw that in right there we’re going to commit changes and how do we want to commit these changes I want to make sure I have the correct name just in case to pull the let’s see hold on Commit the changes but uh add the message J update classic vs okay there we go J commit changes boom committed out of my mind all right let’s go commit the change using the UI okay we did that on your command line make sure you’re on Branch main merge the changes from update d okay so get check out main get merge uh update Dune there we go uh get run get pull origin which will pull in the most Regent recent command all right get pull uh origin main there it goes it P pulled it in oh no I have diverging branches por Maria I’m not supposed to have merging branches yet this not supposed to happen oh my gosh I have diverging branches I was messing around too much and now look at me now look at me I’m 4 foot2 exactly this is where I give up ah it’s not that bad all right so this isn’t too bad so oh you should also do this oh did I uh did I do that let’s see if you if if you get diverging branches run get config pull rebase false make sure get will uh merge on poll and try again so get status so there we go so if I go like this get config uh list uh GP rebase do I not have it weird I thought I did did I not have that on uh get config add local uh rebase what is it is it pole rebase pole rebase false it’s like I planned I pre-planned for this there we go beautiful right beautiful can we agree with that I did do I I actually probably deleted it by accident there we go now I have a nice merge now I have a merge commit which we you know jeez and so we got a merge commit with a K there we go there we go we did all that one uh make sure everything worked with get log on line uh get log on line there we go a b CDE e f g h i j k there we go there’s my main right there isn’t that nice little annotations by the way origin that’s where my origin’s at or at least where I think my origin’s at this is where I’m at this is where my update do at there we go perfect first commit was in fact not bat man pretty poor move on my behalf honestly not naming my first commit Batman it’s really the way you got to do it oopsies I forgot to do this uh assignment switch to a new branch called ad Classics my bad add another line this one okay we’ll do uh get switch C uh add Classics this stuff is kind of easy I don’t think there’s anything very interesting here that’s going on that’s why we’re kind of just moving rather quickly we’re going to do a poll request if you’ve never done a poll request they’re really not they’re not hard at all they’re very very simple oh my eyeballs there we go by the way did was I supposed to no I don’t think I was I don’t think I was anyways I just want to make sure I didn’t goof up anything all right there we go so we’re going to do this thing we’re going to add the classics um let’s see uh Classics there we go Alfred hitch hok hitch hitch HW Hitchcock Hitchcock uh get status have the classics what do we want to call this thing this is an L we’re going to take the L get add this get commit sorry this this part I I I mean I maybe some people are you know uh find this stuff uh they don’t know how this stuff works to me it’s very very boring right have you ever if you haven’t done any of this stuff it’s very very simple and you’re going to do this can you do a PO request directly in git well poll requests are something of github’s more nature so we’re going to be doing a a poll request you can use the GitHub tools you can’t do it directly from that because git does not know about GitHub if that makes sense all right so there we go we did all that and so now I just simply need to push the new Branch at the GitHub navigate to GitHub do a pull request click new polar request set the base Branch to this one add Classics we want to merge this one create the polar request but don’t merge it yet there we go very very simple so jump in here get push origin ad Classics notice that I do get push remote Branch you don’t technically have to do that if you set up tracking Alfred hitch HW interesting compare there we go add classics classics goes into main create po request bada bing bada boom look at this beauty right here you can see these two things because we’re not quite up to date with all the stuff I’m not reading chat chat is unhinged today absolutely unhinged all right there we go run all checks looking good absolutely unhinged all right my workflow well on this topic of whole request I want to share uh my 90% of the time uh and all let’s see I keep all my serious projects on GitHub that way if my computer explodes I have a backup and I see and if I if I’m ever on another computer I can just clone the repo this is true uh I configured my git to rebase by default that’s why we had that you know this what I do uh rather than merge so I keep a linear history right I like the linear history because I just part of what I’ve always done is I always have this as true it’s just you know I it’s hard for me not to get config um let’s see local uh unset local what is it it’s poll. rebase there we go uh that’s this is what I do I just do this I do very simple stuff when I’m working by myself I just add my changes and push it up you know I think when you’re when you’re working by yourself you don’t need to practice all the greatest things because it doesn’t really matter right uh when I do my team workflow I go on here and I do the ad and I make sure I rebra everything and I make sure it’s all the ways exactly the way I want it to be and I do all that and then I do the the merging is it a good practice to add it to the global uh I I added to local because I wanted local Behavior here I don’t like to do things on the global scope if it’s something I don’t want done for everything since I wanted to turn off rebase I didn’t want to put it globally on in case I forgot to turn it off right so if I go get config global global list Global list we’re GL we’re damn Global list there we go uh re re-enabled see I got to turn that off see I don’t even have it up on here see I must I must have deleted it on axent get config uh add Global uh poll rebase rebase true there we go push on Save of course yeah it’s one of those things that’s really hard to REM it’s why I try to do whenever I’m doing things like this I do it to the local as opposed to the global because I always end up effing stuff up just like that I I I take off all these things and I forget to add stuff delete my feature Branch repeat yep there you go so you know that when working solo do I use many different branches in pquest workflow no I don’t I think it’s a waste of time personally I think it’s it’s a huge waste of time my workflow while let’s see while the topic of PLL request I want to share oh I did this all right when working with the team uh yea Force push no work on a branch feature Branch then open a poll request for review that’s how I do it just makes sense right so if you ever want to commit to open source you obviously need the fork you need to uh create a pull request you need to do all that stuff right get ignore is really really really really really important because obviously node modules if you don’t know about them they’re horrible uh so you need to get ad commit some message here get push origin problems will arise uh get ignore file just simply allows you to say here’s a specific file or a class of files to ignore you can also go with the inverse which is you can ignore every file and then just add the files you want to have it’s kind of like a fun way to do stuff um if you’ve never done that kind of stuff right and so you could have is this the first or second this is the this is the first part so we’re going to create a node of modules or we’re going to create a get ignore file that has node modules in it right so if I go like this Vim get ignore oopsies I already have Vim open here whoopsies we don’t want to do that uh I want get ignore and go node modules modules by doing this if I go like this makeer uh Fu and then I go back to here let’s see and I go back in here and I go in here and go like this uh bar. MD save that and then I go one more and go node modules and I go in here and add uh fu. MD right bam if I go get status you’ll notice something Fu hasn’t been added yet right so it doesn’t have any idea what’s underneath so when I go get add everything and do this you’ll notice that it only adds Fubar it does not add node modules and that’s very important and that’s because this matched anything it’s just a match so you got to be careful careful careful careful include bid and build you coward no another cool thing about G I’m not sure if I talk about this here I’m going to I’m going to go in here and I’m going to erase that right erase that get add this get status you’ll now notice uh node modules is now added right awesome so that means here’s an interesting thing I can do I can go in here and go get ignore you can do uh let’s see let’s go bar anything with the word bar in it get status now you’ll notice we have this and it didn’t really quite do it I believe I had to go MD exact match can I exact match it get add this get status I think because I already added it it causes a weirdness get restore uh staged uh Fu bar. mty get status there we go it’s gone right it doesn’t exist it’s already been staged so I had to unstage it there you go so if I erasee this and go back here get status you’ll notice that it’s now able to be added back so you can actually do inner directory get ignoring which is pretty nice I’m a big fan of that if you want to do it you don’t have to do it but it’s cool it’s cool to know that it’s possible and one last thing that you can do as well is there’s a file called um called uh what’s it called get info exclude you can see it right here there’s the path things that are ignored in here are ignored for your local repo they’re not ignored for everybody and so this is a really cool little file right here if you don’t know about it I’m not sure if I talk about it but you should like say you like for me one thing I always do is I go like this I always I always have like an out file that I always have so instead of adding it to my get ignore I can just add it to my excludes and by adding it to my excludes uh when I so you know when I run some sort of program Echo Fu and pipe it to my out file when I go get status my out file just doesn’t show up but nobody else has to know about my outs ignore I like keeping all the ignores in one place it doesn’t make sense if you’re working on a team right when you’re working on a team I have a bunch of Stupid Files that I create regularly out out to and so I don’t want to have out files inside the G ignore so I put it inside the git uh git excludes list which is kind of like that special one there’s also home get ignore I didn’t know about the home get ignore is this like one uh is this a global project uh ignore see I mean G has a lot of features so I didn’t know that this is the same as a global level get ignore of your work oh cool all right Perfect all right so here we go assignment create two files in your repost secure password. text and create a let’s see first create this thing all right and create that all right we’re going to do that and then guilty pleasures all right perfect get check out main I assume we’re supposed to be on the main branch are we on the main branch yeah yeah yeah yeah yeah yeah yeah yeah yeah uh get status uh rmrf Fu let’s get rid of all this get status all right get add this get stat status uh there we go oopsies oopsies uh what is it called webflix there we go uh we’re going to here I’m going to get rid of that thing get ignore and go in here oh that’s not what we wanted in there we wanted it in secure and then what did he say passwords do text or some crap like that and is that what he wanted password. text yeah and then one called guilty pleasures all right guilty pleasures. MD boom The Notebook let’s go guilty guilty AF finally create a get ignore with both with Ensure both of those files are ignored ignore the entire secure directory and then um all right perfect uh secure and then guilty pleasures all right and then let’s see with the message starting with M all right get commit we got to do a little M message uh get ignore uh my uh my notebook Pleasures okay you don’t know you just don’t even know how good the notebook is all right there we go Nest to get ignores oh I actually already went through this we actually talked about this exact thing didn’t we oh my goodness we already did this all right which is ignored all right hold on what are we doing here here’s the let’s see here’s the contents all right we have these contents uh here’s the contents which is this Source assets get ignore which is going to be only devs and main.py and this one’s going to be Vin bin activate so that one’s going to be this one uh right here and this one’s going to be only Dev and what’s the other one main.py and main.py okay here’s the here’s the contents wait hold on what’s the question which is ignored they’re all ignored aren’t they all ignored aren’t they all ignored does not necessarily have to be at the root it’s fairly common to have this one am I am I misreading things I mean this one will be ignored yeah this one should be ignored and this one should be ignored okay oh oh yeah of course not I’m so stupid okay sorry I’m so stupid this one’s um main pie which does not exist at this level okay I wrote this I actually wrote this this one won’t be ex and then this the grot one has ven has ven V been activate which this one should be ignored as well right am I wrong here shouldn’t that one be ignored just equally whatever there we go only devs I want a main cupcake you can’t have one wrong what am I missing there sell Boozled yeah it’s not one of the options oh act let’s see activate is a shell script not a folder ven is in Source oh V is in Source my bad okay I just wasn’t looking hard enough okay your G ignore file does not necessarily need to be at the root of your project I haven’t looked at this in a little bit okay I wrote that to try to be clear uh it’s fairly common to have multiple G ignore files yeah um there you go we’ve already talked about this one here’s the Let’s see we have already done this one which is not ignored okay so Source ven bin this one okay this makes sense now we got it uh test. Pi which one let’s see test. Pi that one’s not even in there there we go we got it skill issues I’m skill issuing come on shut up uh it would be rough if get ignore only accepted exact file path sections luckily uh they don’t let’s go over some wild card common patterns dude the star that’s the one that’s the one that always works I do it constantly root patterns uh patterns starting with the slash are anchored to the directory containing the get ignore file for example we ignored main Pi in the root directory but not any subdirectories with that negotiation or negation you can even negate patterns with prefixing with an exclamation mark this is useful if you want to ignore an entire directory except say an example file I find that to be really really useful is that that kind of move right there I I really do like that you can do comments that’s just like typical shell comments but how do you make a use of multiple G ignores save some notes or something uh if you want if you just want something ignored a certain way you can do that I found it really useful when it came to uh monor repos so if you’ve ever done mono repos in uh with like node or something you want to be able to have a get ignore for each one of those repos it seems to be really nice that way so yeah data directories yeah exactly you just have like these little get ignores so that way you don’t have one giant get ignore that’s super hard to figure out what the hell is happening instead you can just do that so it’s nice all right assignment use this get ignore file to answer the question uh all right so that’s a comment we’re going to ignore everything with a with a text file except for the ones with name and then we’re going to do Source Main and then content Source content is ignored so this one is ignored Source content MD because this one is an exact file name that matches this one and it’s not anchored so it should be is ignored let’s go patterns it would yes we already talked about patterns we already did all this uh what’s the other question all right Main JS is main.js ignored no it’s not cuz that’s a comment it is not ignored let’s go nice try trying to bamboozle my own questions all right here we go they’re trying to bamboozle me all right assignment Part D we’ll do that soon all right here we go Let’s ignore a generated file we ignore generated files because they can easily be regenerated from stuff we do track in this case we’re going to use pandoc to generate HTML from markdown files we’ll ignore the HTML files uh but commit a markdown file first install pandoc Brew install I don’t have that but we do have this guy I can’t show you guys this screen all right here we go uh there we go look at that look at how good that is look at how good that is fantastic there we go we installed pandoc we can run pandoc version to see what that is so I can go like this um uh pan up uh hashr pandoc uh my password is big boobs everyone knows that big boobs 69420 all right here we go running pandoc all right create a new file at the root directory called advert MD with the following content all right so let’s do advert that one while supplies last there we go uh Vim at oh uh let’s go to this one Vim advert MD paste all this stuff in there we go and then run the markdown let’s see run the following command to generate the HML document from that there we go pan doc Bop get status so now we have the we have this one advert HTML beautiful uh for Fun open up the markdown HTML and see what let’s see we can do that XD I don’t want to do that we don’t want to do that because I had to go like I don’t even think XT xtg open does that work on look at that look at that Beauty look at that be would you look at it would you look at it there we go uh we’re going to do we’re going to do a get ignore I think I have to do a get ignore here oh it doesn’t technically say okay see finally add the file oh the get ignore there we go uh Vim uh get ignore what is it called it’s advert HTML bam get status up get stat get status so I think I should be able to do that nope do I have to add stuff finally add the get ignore oh and commit the change serving with 10 get add get status get add get commit n was it n yeah Foo bar screw it got him there we go I finished it we finished the entire course just like that I’m level 12 you would even understand what level 12 is you wouldn’t even understand it uh what’s your opinion on how organization should handle PR merges in main squash uh merge merge commit or rebase which is most useful when you are responding to an incident which is the most useful for Dev happiness overall in a proud environment well I mean here we go again I know here we go again damn uh I’ll here I’m GNA I’m going to say it this way I personally like to rebase and squash I like Fast Forward merges I like to be prepared for the eventuality I need to uh revert a changes that’s it now some people it depends on your size honestly if you have just a couple people like why even have a policy I’m going to be real out there why even have a policy at all some people like to rebate some people like to merge screw it let it all happen do you really want to set up a whole bunch of red tape for you and one other person like why why why add more to your life here I’m going to throw something out here no matter what you choose merge chaos fast forward merges only rebase squash no matter what you choose there will be a group of people that complain about it so we’re going to start this one so this one is a little bit different okay this one is a bit different this one is going to go over a bunch of like conflicts and stuff okay hey I know you’re about to take learn get to and I really wanted to show you a couple quick techniques to make it a little bit easier because inevitably you may mess up at least some of you are guaranteed to mess up you didn’t read the instructions well maybe it’s not quite as clear as it needs to be and so these are two little commands that are going to help you a whole bunch so the first thing I’m going to do is I’m just going to show the contents of the previous commit that’s going to show Foo with a message of Fu 3 now every now and then you may have goofed up a little bit with your commit message and you just want to change it you can go get commit amend this will give you a chance to change your message but as a warning it does change your Shaw so obviously this is a destructive history altering item it allows you to change the last commits commit message so if I go like this get log one more time you’ll see now it’s Foo 4 and you can see that and if I go get Foo let’s see if I do two of these you’ll notice that there’s not a foo three three in here anymore looking at the change you’ll see that all it is is a new file called Foo previous file was Devol meaning there was no other file so it’s just a new file called Foo with a single line called Fu now if I actually want to undo this commit completely I can go get reset soft head TIY 1 this will undo that commit so now if I go get log just one line you’ll notice it’s not that anymore but because it’s soft and it leaves changes in your index and work tree if I go get status you’ll see right away new file F okay we can work with this get reset hard would not only undo that commit by one it would also remove the file so if you ever have to say change something within a file or you need to change the commit message consider get commit amend or consider get reset soft now I use actually get reset soft quite a bit when I’m doing a rebase merge conflict this does happen every now and then where I’m rebasing and I go okay I fix all my changes and then I actually get commit those changes as opposed to calling get rebase continue if you make that mistake you can actually use get reset soft head till one to undo that commit and then rebase continue it’s kind of like a you know it’s like a it’s a lot of IQ and it’s really really nice so I just wanted to give you those two tips because honestly this course can be a bit meaty and without these two things kind of fresh in your mind you might accidentally find that you get your yourself into a bad State and it’s hard to undo it’s actually pretty easy to undo these bad States the name is the gagen all right here we go let’s do this let’s get going okay welcome to G part two I wrote this also where you learn how to use G with a team if you haven’t taken the first G course I’d recommend starting with it because it contains all these basic operations okay uh the stuff in this course is great let’s see the stuff in the first course is great if you work by yourself but you’ll need more if you want to stand a chance as a developer Mega Corp where we sell synergistic CRM customer relationship Management Solutions to Enterprise that’s right we do hey look I’m wearing the same shirt I’m wearing the same shirt what are the chances uh this course assumes you’ve completed uh number one so you’ll have all this crap that we’ve already done we have already blah blah blah blah so we’ve already done that thing same shirt what are the chances there we go I’m just going to run this because we’ve already done this okay we’ve run it we’ve done it you need your own Fork of Mega corpse starting repo a fork is a copy of this one so we need to go here I’m going to first need to jump in here I’m probably going to need to uh can I fork or is it not going to allow me I can’t tell if it’s going to allow me or not nice let’s go I’ve done it please select owner Fork already exists shoot okay it’s K sensitive today I learned it’s K sensitive there we go I thought I just deleted that but apparently I didn’t delete that there we go and create all right we got the fork we’re forked out of our mind all right let’s let’s let’s do this let’s do this all right so we got a fork we did that we pressed the fork button we did hey look at that hey look that’s me hey that’s me doing that all right boom boom boom boom boom boom boom run check pasting your link we’re going to paste that link all right there we go all right what is a fork uh we created a fork of the official a Corp repo inside your giup account it’s a copy of the original that you can modify without affecting the original you may have noticed that there is no manual entry for get Fork git Fork is not a real thing right why forking is not a git operation but is a feature offered by many GI hosting servfaces such as GitHub gitlab and bit bucket those Services Fork a repo by creating a new copy of the repo and associating it uh as a fork of the original there’s something called like a fork Network or something like that with GitHub which is very confusing it’s like one Super Repo and there’s some sort of thing that they do underneath that’s a little bit more confusing this is gamified git tutorial this is a g tutorial I wrote and I’m going through when you Fork someone else’s repo on GitHub you simply clone their repo into your local machine you create a new branch of The Originals well technically I think it has something to do with this in the fork creation network but I don’t really know how it works create a copy of your own let’s see of the repo and your own GitHub account boom let’s go that’s what we did all right I’m not working TC no okay GI Fork is a command line operation that takes no f false all right now let’s clone it down let’s clone Mega Corp uh RM RF let’s get rid of webflix let’s get of webflix local let’s get of uh Mega Corp Mega Corp uh get clone the primagen get clone get clone primagen Mega Corp Bim we’re in we’re in we’re in in there we go perfect all right we’re we’re in okay so let’s get let’s let’s start doing this whole thing because this is this is the one that in involves a bunch more stuff uh when you Fork someone’s a repository like a platform like GitHub you can copy a repository into your account this is the standard way to contribute to someone else’s open source project uh steps are typically Fork the repo to your account clone the fork to your local machine create a branch or feature make the changes commit the changes create a poll request bada bing bada boom you’re probably asking yourself why should I Fork a repo instead of cloning it cloning is a lot easier well that’s a good question you first have to answer the question am I interested in contributing back to the main line or do I just want to peruse the repo if you wish to just simply peruse the repo then a clone is just fine whereas if you wish to contribute to the open source project then it does require a fork here’s usually my workflow when it comes to forking and making changes one I just Fork the repo two I will clone down my forked repo three I’m going to make the changes to my main branch four four I’m going to push my changes up to my Fork’s main branch five I’m going to open up a PR with my changes from my Fork onto the original repo along with a nice detailed explanation of what I have changed and why and finally I get rejected go home cry a little bit skill issues but nonetheless I tried and that’s what really counts doesn’t it it’s also worth noting that whenever I clone down my Fork I also add a second remote that I call Upstream that points to the original repo and the reason is that when the original repo changes I can bring in their changes and that way when I fix something I know that I’m fixing on the latest version I’m Not accidentally fixing something somebody else has already fixed this also avoids having conflicts during PRS and if you wish for your PR not to be rejected here’s some pretty helpful hints number one whenever I make a PR before I hit that button and say make it live to everybody I review my code on GitHub this weird thing happens to me whenever I review code on GitHub I seem to catch things that I don’t catch when I’m in my own environment I kind of think of this as editor blindness you’re so used to everything that when you see it in a concise different way you just see mistakes you’ve made so much easier probably most importantly is make sure the maintainers want these changes spend the time looking through the repo issues make sure you’ve searched and validated that this really is an issue and if there’s no mention of it open up an issue tell the maintainers you’re willing to fix it and see if they want you your fixes you may find that maintainers actually do not wish for you to participate or others they may want you to fix it but in a completely different way as long as you’re polite in your communication and you’re very clear as to what you’re trying to fix you will find that often maintainers are very happy to have you come on board and help out okay so assignment I want to make sure people know how to do this okay I want to make sure people knew how to do this like fun little bit add a file in your forked and cloned version of Mega Corp to the repo uh to the repo contributors directory uh the file should be named let’s see your get up username text replace your username with a good one okay let’s see add myself to the contributor okay Bam Bam Bam Bam Bam Bam Bam Bam let’s go in here and go here okay well I’m already there the primagen 2. text oh my gosh oh my gosh all right there we go there we go we got that let’s do that let’s go like this get add uh uh get whoopsies all right there we go so we’re going to push this up right so I’m going to do all this I’m going to push this up push my changes to my GitHub uh to an add contrib Branch oh gosh get checkout add contrib oh I’m not supposed to use checkout sorry it’s just I can’t help it I can’t help that I do who the hell does that who Noob Noob Noob he’s a noob I’m not even sure oh I I copied it from the boot. dev site remote add origin all right there we go fixed fixed you wouldn’t understand understand fixed you wouldn’t understand you don’t understand because you’re you’re you’re sore loser boom I think it told me to create a pull request let me just make sure that that’s what we’re doing here all right there we go all right with the poll request open submit the test all right there we go run all checks let’s go owned it head mean where me at now for those that don’t know who grug is grug is the best I always go down here and just I just read this line whenever I think of gr grug apex predator of grug is complexity complexity bad say again complexity very bad you say now complexity very very bad given choice between complexity or one-on-one against T-Rex grug take T-Rex at least grug see T-Rex complexity bad all right let’s go like this okay for example you should be on main branch of your local clone of your fork of Mega Corp repo which which means head is pointed to the main branch like all things and gets eternals head is just stored in a file right here manually uh check to see what’s in head yeah let’s do that cat uh get check out main get cat uh dog I think it should be I think it should be the name of the thing there you go yeah it’s just a it’s just a path path to the uh to the branch or the tag if I’m not mistaken G yeah you got to G it baby you got to G it get that son of a bee all let’s see if that just works okay what did I I didn’t read all right what’s the thing oh uh get Branch d add I must have missed deleting that did it say to do that okay my bad I didn’t look I did not in fact look we’re going G grug no read all right get reflog command pronounced a reflog not reflog is kind of like Get log but stands for reference log and specifically logs uh the changes to a ref that have happened over time T the default one is the head by the way grug no read grug never read where head is now one move ago two moves ago three moves ago you are already familiar with how git log Works how it shows your current branch and all the history of the commits so if I had a brand new repo with three commits a b and c and I execute log I should see the following output and if I execute ref log I should see this following output is reflog just a verbose log well no it’s actually not it’s very very different and to illustrate the point let’s remove commit C I can remove commit C by using git reset I can walk back one branch and as you can see with Git log I now only have b and a but if I use get ref log you’ll notice that I don’t have two entries I actually have four entries I have a b c then back to B and notice that it contains the command I use to get to B which means that if you need to get the contents of C you can actually use some of the plumbing of git plus reflog to be able to retrieve back out the contents of C even though it’s gone from your branch I cannot tell you how many times reflog has saved my bacon by walking back and getting some commits that have been long forgotten so what is reflog well the definition from get SCM is reference logs or ref log records the tip of branches and other references whenever they are updated or in layman’s terms reflog tracks the changes of a branch or other references other references being head this means as you move your head around from Branch to branch or from commit to commit it tracks every last little step I personally only ever use reflog to look at how my head has transitioned over time and Rescue out of commit if I need to all right assignments run get reflog to see what its output is all right here we go get ref log look at that look what it is going from ad contrib to main from uh from Main to ad contrib to this commit to the Clone cool right you get to watch it kind of move around it’s kind of cool I like it reflog is nice and it’s really not all that bad all right switch to a a new Branch off of it called slander get uh switch C slander look at that I remember to use that uh let’s see create a new file called slander. MD and have this one all right Vim slander. MD paste that in uh Mega Corp CEO Lane enjoyed the live action last air bender movie this Mega Corp CTO Prime is a fan of the notebook okay Lane mayor or may not had a little bit of fun editing some of these things okay I don’t know if I didn’t choose all of the stuff I’m just saying you know the notebook’s not a bad movie okay what I feel I even have to commit it okay it’s not it’s not bad okay it’s not bad Ulta movie was a good terrible movie too did you cry I didn’t cry I’m not crying SL slanderous slanderous filth I’m not even sure if I spelled slanderous right um boot. Dev run that okay what am I not even doing here all right expected this contains all this one oh I had to do b. slander goodness gracious uh reset soft uh head I okay I got to start reading you guys are not helping me um uh be slander you guys got to quit but by the way did you see that nice usage of get reset soft huh ha did you like it I could have get commit amend I could have we could have amend but this one is great okay it’s okay it’s okay to cry it’s I don’t cry I work out I know we could have amend okay but we didn’t okay delete Branch every ever uh shipped a bug to production main branch created a new Branch to fix it bug fix fixed the bug and committed the changes switch back AC deleted deleted the fix bug Branch all right switch back to Main and delete your slander Branch get Branch D whoopsies get check out main get Branch oh I’m supposed to use switch but I I just I can’t I cannot use switch okay I can’t use switch I can’t I can’t use switch all right I want to use switch Boomer brain I know so you’ve deleted your branch that had a unique commit On It All Is Lost or is it remember get reflog keeps track of where everything has been so let’s do this get ref log look at this bad boy that’s where we did this one look at this commit right here the commits right there the commit is right there okay that means what we could do like here’s one one way to do it which I’m not saying this is the way you should do it I’m just saying this is one way you can do it you like this you can go like this you can go uh get cat file- P remember when we learned about all this and you can actually go through all of the little internals and snatch out the slanderous file get cat file- P look at this right there there’s me enjoying the notebook right we were able to Plum through things if you wanted to if you wanted to get deep in there and kind of go through the whole thing you could so there we go we grabbed that and so we can actually grab this and do that and do a recovery message right so I could do this right there’s other ways I could also do stuff right this is just one way you could also get merge and since I already have this thing I could actually just merge over that change into it we’re not going to do it but you could imagine we could do that so instead I could just take the contents of this one file and I can remake it if I wanted to as well even though it’s not true commit that file with B recovery get add this commit dashb Rec recovery Boom Confetti out of my mind all right cherry pick would have been what I would want to do really I would have just merged it over right I mean it it just depends do you want the history or do you not want the history like what happened if there’s 10 commits then you have to cherry pick all the commits let’s see using get internals is exceptionally inconvenient we had the copy and paste from cat file three times I would not recommend doing it this way I just wanted to drive home that at this point you can always drop down to the plumbing commands if needed luckily there is a better way get merge I just haven’t talked about Cherry commit that’s why we haven’t talked about that so I can do reflog this one find the commit kit that one so I can do get cat file do all this crap which we don’t want to do I can also do this right right I could have just merged over exactly what it said from reflog right let’s see do I still have that reflog thing or did it open it in one of those windows uh I think it did that one of those windows right yeah do I do no pager no page I can never remember what that line is oh that’s right you don’t do it there it’s a get no pager there you go so as you can see you can see right here so I could actually do get uh head at the second position back right why does get ref log allow us to potentially recover commits on deleted branches because it keeps a record of where the head has been yes that’s what it is there you go little fun little fun reflog stuff merge all right let’s see what can you merge with only tags commits branches a commit commit tag ref log entry anything that can resolve to a commit so that’s why you’ll see me use the term commit quite a bit in this [Music] course all right uh working with Git is a dream when all of the developers in the project are committing changes to different lines of code things get a little hairy when changes are uh to the same lines are made at the same time one commit isn’t the parent of another let’s break some stuff remember Mega Corp is Enterprise CMR Service uh backed by the power of git Essen it means that we store lists of customers data in a get repo truly Cutting Edge stuff you should be on the main branch uh create a new branch called add customers all right get branch no wait it’s get is it get switch see there we go all right there we go we got that one and we’re going to grab this one uh to customers a CSV all right all is it all like that one yeah there we go so we’re going to add it to all customers and then we’re going to also do orgs partner. text right there Boot and startup so we’re going to do orgs partners. text there we go beautiful we’ve done those two make commit your changes with the thing C okay we’re we’re going to kind of cruise through these easy Parts because I assume at this point you guys understand adding committing doing all that um because this is all easy stuff right none of this stuff is crazy all right get status get add this get commit I think I said c right yep see uh uh such Carson much HDMX all right there we go and now we’re going to switch back to Main and we’re going to do this to customers uh get check out main uh go back to here edit this thing jump up here customers all add Json gross HTM Z contributor get add this get get commit what do we need to do with d That’s right d uh Jon is better than uh Carson more like cars off all right so do you do you see what we’ve just done here do you see how this is going to cause problems so if I go like this uh get log uh on line um on line- P1 main you’ll notice that I edit customers with one line right below company title if I do the exact same thing but I do it uh with the add customers Branch you’ll notice that I do the exact same thing to the same customer files in the same location in other words we both modified the same line and by modifying the same line G doesn’t know what to do because git doesn’t understand anything about code it only understands things about modified lines if two lines have been altered in some way it creates a merge conflict there we go I believe that should just work there we go and let’s go conflicts yeah yeah yeah yeah yeah yeah yeah so merge conflict occurs when two commits modify the same line and get automatically decide which changes to keep and which change to discard consider the following commit history ABC this is pretty much what we have now except for it’s a c and d uh the main branch has something like this uh is nice returns this one feature has this one is nice 420 right if we try to merge feature into main G will detect that the return line was changed in both branches independently which creates a conflict so this is good this is good to understand right when a conflict happens usually as a result of merge or rebase git will prompt PRP you to manually decide which changes to keep it’s okay when the same line is modified in one commit and then again in a in a later commit the problem arises when the same line is modified in two commits that aren’t in the uh in a parent child relationship all right if the line changed in B was all the conflict change in B’s parent a the htx guy writes an essay about it that’s true Carson will probably write an essay about it uh that’s perfectly fine get knows a happened first then be yep that’s the thing you can’t conflict yourself like that right you just can’t all right if two developers on separate branches modify the same line of code what happens when the branches are merged HTMI htx guy relaunches the project with a new name facts it’s perfectly fine false conflict arises there we go assignment it was stupid Greg stupid Greg who merged his new customer data into main commit D while you were working on your new customer data in ad customers Branch commit C because his change made it into main first stupid Greg it’s up to you to resolve the conflict stupid Greg now because your manager is a lite that learned a code before Version Control was invented he asked you to merge instead of rebase absolutely this is all true switch to your add customers branch and merge main into it all right there we go we should get this one let’s go let’s go get check out add customers hey uh get Branch d add uh add contrib wait why is contri still there I thought I just deleted it why is there why is there multiple ad customers whatever that’s confusing whatever I don’t got time for this damn it Greg leptos mentioned leptos potentially mentioned get merge main all right boom we got ourselves a conflict okay uh if we run get status you can confirm that we’re in a conflict so if I go get status you can see right here you have unmerged paths fix the conflicts and run get commit and use a get merge abort to abort the merge so we can actually stop the merge by doing that get out of here okay there we go get run status like this to confirm that you’re in a conflict we can see that so let’s run this thing boom Oh wait what oh my gosh this thing is incorrect lane lane Lane we have a problem this is this is wrong our Direction somehow got out of conf out of out of stuff here I know which means I go like this get uh merge abort get check out main get merge uh get merge uh add customers there we go kind of BS Lane all right right here I’m going to go back here I’m going to report this uh wait does it am I wrong here did I just maybe I just didn’t hold on get uh merge get merge aboard get check out maybe I did this wrong yeah I used the wrong one lane it’s not right lane you’re right you’re right this whole time I’m the bad one I’m the bad one I’m the bad one shut up get check out you dumb folk I know I messed up isolate to changes and merge correct you merge yourself correct resoling conflicts is a manual process when they happen get marks the conflicted files and ask you to resolve the conflict by editing the files in your editor so here we go open up the customer all and you should see this all right so here we go here’s our customer so you can see two you can see a couple things here just so everybody knows in emerge conflict this represents uh hours is the top one hours is where our head at here’s the change in hours the change ends with the equal sign and then this is the one and then the bottom one represents the incoming Branch theirs so theirs is main ours is head and this is the change in theirs this is the change in ours okay it’s pretty good to know those things right uh let’s see delete the conflict Mar markers and leave both changes and Greg’s changing the file it should look like that so we can actually you can actually have both changes at the same time right nothing says you have to change it it’s up to you to resolve how to to do this you can accept both totally reasonable uh sa file and do this okay yeah we can we can accept both there’s nothing that says you can’t accept both right all right resolution after manually adding any conflicted conflicting file sometimes it’s more than one file or more than one section of a file you simply need to add and commit the changes this tells get that uh you’ve resolved the conflict and can continue with the merge okay awesome we can do that so let’s let’s resolve with this nice message right here it’s a nice beautiful message get add this get commit uh- M all of that oh my goodness stupid Greg oh no all right there we go apparently I don’t know how to do that there we go got it first try and now we can do log to examine the homework you should see c and d and commits come together and E commit all right get uh log on line look at that beauty and then we can go on line graph there you go it all comes together in E we resolved the conflict bada bing bada boom very nice absolutely liked it absolutely enjoyed that all right all right you just ran get merged and you’re now seeing this okay I just realized what was happening I was like wait a second uh which code in the conflict is yours and which is theirs so if we ran get merge that means this is ours this is their theirs the top is the top is mine the bottom is theirs it’s all mine stay away I prefer that answer honestly um all right you just ran get merge and you’re now facing this conflict oh let’s see what does head refer to it’s another name for the master branch no it’s another name for the main branch no it points to the latest commit in the other Branch you’re comparing to no it points to the current Branch’s latest commit boom it’s pointing to where head points to everybody knows that is that easy back to me your manager at Mega Corp is not happy it turns out you were never supposed to add customers to the all. CSV file at all only Greg is allowed to do that stupid Greg this is what you get from making changes without 10 design meetings and an alignment of stakeholders what were you expecting to be productive this is Mega Corp process over productivity get back in line I don’t want to hurt anybody’s feelings but at the same time I know a lot of people just got bruised by that one statement I’m sorry I’m sorry that right there’s some of you that hurt that paragraph hits home I know it does let’s just say I’ve written a design document for the the dumbest thing stakeholders are okay in the 10th design meeting but have problems when the implementation hits BR always every single time assignment let’s fix our hastiness by uh doing a git hard of the merge commit this will allow us to take a different approach to resolve the conflict luckily we haven’t borked main yet we just uh need to fix our ad customer Branch while on ad customer Branch reset to commit C all right let’s do that oh my goodness um let’s go like this let’s go what is it called Mega Corp yeah yeah yeah get reset uh hard uh head till the one there we go we’re back to C everything is great we’re looking good we’re feeling good there we go we do all that nice stuff so I just I I literally just took the change moved back my Branch ones and discarded my index my work tree changes bada bing bada boom easy peasy pumpkin seedy that’s just that all right uh let’s fix our hastiness by doing a hard reset yeah we already did that luckily we haven’t borked main yet so we’ll just uh fix all right here we go try merging main into customers again this time resolve the conflict by keeping only the changes for main I want to see something cuz I may accidentally have uh R re on and if I do then it’s going to say it’s all fixed nice I don’t have R re on uh get config list uh Global grap re re oh I do wait shouldn’t re read take care of that doesn’t wouldn’t Riri re jump into that am I confused here am I be what what I thought it did well then why didn’t it it should have Auto conflict it record yeah record resolution was solved was added weird Why didn’t it just Why didn’t it auto resolve right here shouldn’t have just Auto resolved oh wait oh oh my goodness I am so stupid I am so stupid it did it automatically using previous resolution so if I go to customers oh my goodness I’m so dumb look at this the conflict is gone the reason why the conflict is gone is I knew I had re re-enabled so since the customer doesn’t have a conflict in it we need to disable R re get uh config I’m just going to do a local one uh I’m just going to go like this add local re re re enabled false right so I’ll just add a local one so I still have my Global one so it still continues to do what it’s doing uh get merge abort then get merge um get merge main which should now there you go I now have the conflict without re taking over and I should be able to just go into here uh and I should be able to go to all and now we have this again so now this time we’re supposed to select Greg’s change which is theirs so I can go like that boom Greg’s change selected uh there’s some other ways you can do that to make it easier but this is good so we’re going to go like this find Greg have this one boom uh we’re going to go here and go get St status get add this get commit dasm with that one there we go um and then jump in here do that there we go there we go all right I think that’s good all right ours versus theirs uh in a merge conflict ours refers to the branch you are on merging into theirs refers to the branch being merged this is important get merged their Branch ours is the branch you’re on right uh get terminology last time we manually edit the conf uh conflicting files this time let’s use get built-in merge resolution tools to make the uh let’s see use the terms hours and theirs to refer to the branches being merged you should currently be on ad customers with this kind of History right now switch back to Main and merge ad customers into main this would result in a fast forward merge bringing C to e into main delete ad customers all right get check out main get merge add customers get Branch delete uh add customers boom look how fast I am all right so let’s do a better let’s do an ours versus theirs merge because this is really good to know uh all right so we got a multi conflict so far we’ve only dealt with one Conflict at a time that’s a small that’s small potatoes let’s see what happens when we have multiple conflicts to resolve all right so let’s switch to a new Branch off Main called delete records uh get switch C that uh and then let’s see edit customers all and delete the jesson line okay there we go deleted it edit org partners and delete the boot dodev record okay org Partners there we go boot dodev record boom Oh we want to keep the line there we go uh let’s see six let’s see switch back to main uh and edit customers oh commit the message with f we got to commit the message with f get status so I’m going to I’m going to use uh I’m going to use what’s it called fugitive for this part cuz it’s just easier and faster and you guys don’t really care about committing right what do we need to do F uh F uh uh delete those records right I just prefer that uh get check out main just makes life easier being able to use that because we can move faster there we go uh all right so we have this one so edit the ORS partner and add a boot dodev record uh to Sales Inc oh change it and change the boot to Sales Incorporated yeah yeah yeah yeah yeah yeah yeah yeah so I can go like this Sales Inc um there we go we did that one so now we should have this one and do a g there we go and uh ccg uh such Inc there we go we now have that one run and submit the test there we go wait is that all we had to do did I miss something I thought I thought we were doing multiple oh we forgot to do that we forgot to do that one we forgot to do that one Carson uh gross that’s right all right uh customers all and go Carson gross go here s there we go so I just all I did was I just did right there for those that don’t know I just did a uh I did a get uh commit amend no edit and so by doing a get commit amend no edit I simply just um I know I wrote shut up shut up it just means I merged in that change right so I merged in that change right there and I did that one you know cuz I’m not going to lie to you it is very nice to be able to use the tools I’m used to you know what I mean I don’t always do everything by the command line there we go all right so we did all that one we have these nice commits now we have these two things and so now all we have to do is just cause the conflict let’s go wait what did I do oh oh my goodness here I forgot to do that there you go I’ll show you what I did get status so I have this one get add this one get commit uh amend no edit there we go so I kept the same the same uh line just not everything else wait what am I doing wrong here Carson grow hmx Creator what I’m not good at reading I’m not good at reading okay I’ve never said that I was good at reading all right first try let’s go first try check out the conflict we’ve manually edited files to resolve the conflict but it turns out git has some built-in tools to help us the git checkout command uh let’s see can check out the individual changes during a merge conflict with theirs an ours flag while on Main merge delete records all right get merge delete records so now we should have two conflicts you can see the two conflicts right here get status you can see the two conflicts right here unmerged path both of those get diff should show each one of them having the problem right here which means that I can go like this uh how do we do this we’re going to keep theirs for customers all and keep ours for partners so I can like this get check out theirs uh that’s going to be uh customers uh all there we go so now I have uh theirs and then ours is going to be orgs uh Partners there we go so now if I go like this get uh diff you’ll notice that we have no changes everything looks good get status perfect get add this if we look at them in here you’ll notice right away there we go so that’s the deleted one that we kept and then from orgs and partners you’ll notice that we have Sales Inc from our side so Sales Inc from our side deletion from their side by using uh get checkout there’s an ours hours it’s pretty nice what do we need to do here we need to do this with an ah uh M uh H uh let’s see such uh resolution conflict you’ll also notice something else notice that orgs is not a part of any changes here do you see that there’s no orgs a part of changes that’s because that wasn’t changed by accepting my change this commit doesn’t contain any change does that make sense because that file only had one change to it which was my change so by me uh accepting it the difference between these two goes to zero it’s good to know so that’s why sometimes those things can change and it can look a little bit confusing it’s actually not all that confusing it just means that something goofed up oh my goodness how am I so bad at this oh yeah let’s go all right something you may have noticed when resolving merge conflicts is that you don’t get the standard merge uh merge commit message right no you don’t you have to manually provide a message typing uh it actually makes sense when you think about it g doesn’t know what you did to resolve the conflict and it’s encouraging you to document your change via the uh message that makes sense right I think everybody understands that uh what commit message is used after resolving that the standard one unhinged commit message for example we should have rebase instead I actually like this one that’s my favorite one but we’ll do a custom commit [Music] message now we’re going to do rebase one this one’s going to be a good one all right rebase uh full disclosure a lot of rebases bad rep comes from conflicts fear not it’s nothing you can’t handle with just a SCH smidge of practice rebasing feels scarier because it rewrites get history which means you are not if you’re not careful you can lose work in an unrecoverable way but as long as you understand what’s going on it will make your and your teams get history cleaner and easier to understand and more so easier to revert when needed it is impossible to revert your change with several merge uh merge commits and all that I’ve seen some pretty nasty ones where you’re trying to do that assignment create a new branch called band a copy of main branch and add a new file customers band all right there we go scabi toilet merch when get checkout dasb band I didn’t use switch didn’t use switch it happened it happened but we’re going to get keep on going for it band. MD is that what it was no uh band. CSV boom put it in yeah Sam Sam controlman closed AI classic really true AB absolutely actually true there we go so we have this one we’re going to do get message I so I’m going to go in here c c i uh control man there we go and so now let’s go like this get check out main do one of those and then how do we want to do here we want to have the same Sam controlman but a different but a different one of these there we go um and then jump up here and go c h oh no wait J you’re right H comes before H before I except after C’s right is that how it goes I’m on chapter 7even section four right now all right well let’s go let’s go all right so there we go so we have all this one so we should be able to run this to make sure it’s all actually the way we want it to be so I’ll go like this we’ll run this bad boy it’s going to do all this bada bing bada boom bada bing bada boom all right beautiful we are just crushing through this course okay people were feeling good make the conflict before we move on I just want to remind you that it is often uh not often that you’ll be creating your own conflicts we’re doing so because you probably don’t have any friends to practice with I don’t actually Kid Art users uh but even if you do have many developer friends let’s just make all the changes ourselves so you don’t need to bother them let’s see you switch to a new Branch fix bug which is just a copy of main while you’re fixing the bug someone else merch is there changes the domain you fix the bug and it happens to edit the same file uh you open up a poll request rebase fixing domains get tells you the conflict you resolve the conflict you uh complete the PO request this is like standard operations right we all know this one so we switch the band Branch rebase uh it into main uh which rewrites to get history of band Branch because remember it needs to add that extra commit so there we go we’re going to do that all right so we’re going to go like this get check out band right there get re rebase main my gosh we have a conflict look at that conflict oh no oh no so if I go in here I look at my status you can see right here we have problems don’t we we actually have problems all right well uh you should get a conflict you might also notice something odd this time head pointed to Mains change rather than bands change all right so let’s just jump back for a quick second and just validate this and I’ll explain why all right so notice that this should be band protagonist should be main look ate has protagonist which is Main’s change why is ours Mains even though we did a rebase on band why why isn’t hours hour change why is it Maine’s change does anybody know the commit comes from Maine no cuz that would make it’ make it theirs we move to main then replay our commits on it boom let’s go so this is from section one this is why section one is so important is when you rebase your target Branch becomes your branch that you’re on and then you replay the source branches commits starting from the merge base and forward at the tip of your target Branch therefore let’s write this out because it might be a little bit easier to visualize so this is the most important part remember so when I’m on band and I do git rebase main what happens is I actually check out main which is going to be at the tip I grab the differences between uh uh what’s it called band and Main and then I do band you know if there was multiple commits I’d actually attach each one of them to the front so that’d be like band one uh band two uh band three right so I’d get them all on there so my Branch now looks like this where the tip of main is now the new merge base as opposed to wherever I branched off before which could be somewhere in the history so that is why ours is theirs and theirs is ours during a Reb rebase conflict it’s actually not confusing if you know how rebase works it makes perfect sense it’s that you have to switch branches and then play the commits all right let’s see what happens here let’s let’s see what our assignment is switch the new branch do this uh copy of branch and add the new file customers this this this this this we’ve already done this all right there we go assignment switch to band rebase on domain while uh you should get a conflict you might also know something outd we already talked about why if you had merged main instead of rebase head would still point to band correct because merge does not swap replay it just adds or creates a merge conflict into a single point there we go that’s good to know however you kind of need to think in Reverse with rebase theirs represents the band Branch uh which in reality is our change so we’re going to Branch you’ll notice that you’re not on a branch that’s right that makes perfect sense right because remember it has to create this no Branch situation where it takes Main and then starts applying commits to it so you’re in a no Branch situation right there we go bam look at that look at that confetti man first try first try uh the same get check out theirs and get check ours uh commands we used in merge can be used to resolve conflicts during a rebase you may have also noticed that if you open the file in your editor depending on your editor uh it has UI features to help you resolve the conflict yep so this would be uh VSS codes accepting incoming changes is the same as checkout theirs accepting current changes is the uh is the same as get checkout ours that would be in theirs I don’t know how I don’t know how to use I don’t know how to use vs code all right assignment uh use the appropriate get checkout command to overwrite the band Branch’s changes with the changes from Main so since it’s main that we want get uh status get checkout out hours our Branch remember we’re ding main all right there we go uh let’s see then hit him with the rebase continue get rebase continue There we go and then we get logged to see the new commit history get log look look at how good that looks look at that look at how good that looks all right you may have noticed something did anyone notice that I was gone why was I gone so theirs is main no ours is main during that situation the the number of rules indicates that this isn’t intuitive no it just means that it can be potentially complicated anything that is sufficiently complicated requires you to learn if you only worked on things that are intuitive you would never use recursion like that’s that it has nothing to do with it being the the number of rules have no indication whether it’s intuitive or not understanding the underlying reasoning why or what happens makes it intuitive to understand I understand how you or rebase Works therefore ours versus theirs is intuitive to understand but that’s because I have a understanding of what’s Happening expected a state to contain this way H uh Branch oh I’m not oh I haven’t uh oh uh get rebase continue oopsies did I not get status did I not there we go we’ve continued it gets status awesome all right let’s do this perfect we’re in we did why did the deleted command what happened why was I gone so for those that don’t understand so why where’s I why is I not in here the reason why I is not in here remember this is that I was a change where deleted deleted a specific record and what we do we ignored that one change by ignoring the one change that I was we’ve dropped the entirety of the record since the there is no like there’s no empty commit when the commit is empty the commit is dropped right yes we are working on the band Branch we started a rebase of band onto Main meaning we’re rewriting the history of band to include all the changes of main we effectively removed all the changes of the I commit by choosing to keep the changes from Main instead of band we continued to rebase and get realized that the I commit was pointless because we’re rewriting history anyways just remove it there’s literally nothing in it right there’s no I in team that’s why if our if our changes had been more complicated say we kept some of the changes from I commit and overrided others then git would have kept I in the commit history why did git remove our commit because this is Mega Corp and we have a strict no commit policy uh because rebase is scary and it should be avoided at all cost because it was a essentially empty and rebase is okay with rewriting history bada bing bada boom there’s nothing to commit there’s nothing there it’s just making life easy right uh what if the only part of the commit had been undone during the rebase comp what if only part of the commit had been undone then the commit would have still been let’s see would have still been removed no the commit would have remained in the history let’s let’s go on to this one okay let’s clean up our branches remember during these uh during the rebase of band onto Main we actually discarded the changes of band which actually means that band is now just identical to main anyways so yeah so we’re going to switch back to Main and delete uh band right uh get check out main get Branch D band there we go all right so let’s delete some branches we’re going to delete uh get a branch okay we did that one and now let’s go over here let’s go there we go all right let’s move on all right disable re well uh we it should have already been disabled this this section does need to technically go back cuz already did a local one of those uh I here I think I don’t think I deleted this I’m not sure if I even have it but here I’m going to get rid of it just in case right repeat resolution setup a common complaint about rebase is that there are times when you have to manually resolve the same conflict over and over again this is especially prevalent when you have long running feature branches and even more likely multiple feature branches that are being rebased onto Main re re re to the rescue the get re re re functionality is a bit of a hidden feature by the way this is directly from G sem can you believe that one of the most useful features of all time is just hanging out uh here hold on uh get R re re there we go let’s go get SC look at this functionality is a bit of a hidden feature wait you’re telling me I didn’t have to resolve it every time yikes the name sound let’s see stands for reuse recorded resolution as the name implies as the name implies it allows you to ask G to remember how you resolved a hunk conflict so that the next time it sees the same conflict G can resolve it automatically in other words if re let’s see if enabled a re will remember how you resolved a conflict applies to rebasing but also merging and will automatically apply that resolution the next time you see the same conflict pretty neat right am I right all right assignment create a new Branch off of Main called faves all right good check out B faves didn’t use switch suck it new commands create a file called uh faves. MD with the following contents let’s go uh jump back in here go here go here wait customers okay customers uh faves faves. MD there we go cool uh commit that with message K create a copy of faves branch called fave 2 all right here we go uh we’ll go in here we’re going to go here we’re going to CC we’re going to K uh ma faves is the uh heisen right boom boom get check out dasb faves 2 so now we have the same Branch twice okay okay the same Branch twice all right now we’re going to switch back to uh Main and create a file called faves with a different content all right here we go get check out dashb main get U Manny main oh crap I created Manny get check out main get Branch D Manny got him first try uh and then go in here and put and put that in there and get status get add this get commit dasi what is it called should be with an L take the L take the L bam all right so now we have these right here we have main on L faves on K faves 2 on K the the changes from L and K naturally conflict run the test let’s go we’re going to run the test we’re running the test let’s go we’re running it confetti out of my mind are you ready for the confetti out of my mind enable the re re feature by running the following command all right so I’m just going to like this get uh get config unset local re re re enabled cuz I have a get conf config uh list grip re re re there you go I already have it globally true for everything because I like the setting switch to faves and rebase it on to main all right get check out uh faves get brand or get rebase main there we go so notice this we’re going to do this conflict we’re going to be doing this recorded pre-image for customer there we go we’re getting ready we’re re re reing okay so we have a conflict let’s do this let’s solve this conflict notice out let’s see hold on accept both changes all right let’s accept some changes okay e yes yes yes changed get add this get rebase continue all right so now what are we going to do with the naming um stage and rebase leave the commit message as K all right boom got it note that git May automatically open a file on your editor in which you can edit the commit message Simply Save and close and continue when you’re done you should see something like this so you should notice that we should see something like this recorded resolution recorded resolution yeah we’re read out of our mind we’re read out of our mind now switch to faves 2 and rebase may it on to main all right get check out faves to get rebase main now look at this we have a conflict but it’s already resolved right it’s already resolved because we already we already resolved this specific commit so now we don’t have to resolve it again it already knows what to do it already knows what to do so now I can just I can do the exact same thing I can do the whole get uh rebase continue so R is really really nice because it’s one of those things that if you do it right it is uh fantastic uh why is re disabled by default because it can lead to confusion so if you don’t know what it is it’s probably dangerous to have it created what’s foot comes with Riri let’s say you have a change that results in a conflict but you want to resolve it differently but instead it automatically resolves it for you you could feel pretty confused right so that’s why it’s nice to have it as a feature you opt into because that way you don’t accidentally screw it up all right let’s go on merge back in PH now we have two branches faves and faves 2os that are ahead of Main in the same way we don’t actually need both faves and faves 2os so switch back to main try deleting fave 2 with lowercase D flag now actually delete it with capital D we’ve already we’ve I think I’m not sure if we’ve actually done that get check out main if you don’t know if you go if you try to delete a branch that ends there it terminates uh your commit history it’ll be like yo um You probably don’t want to do that and so you have to give them the old you have to give them the old capital D and when you give him the D it then does it then merge faves into main this should result in a fast forward merge deletes the faves Branch there we go get merge faves get Branch d uh faves boom let’s go grab it paste it all right accidental commit uh you know uh how let’s see how with merge uh conflicts you can commit the resolution but with rebase you have to do continue dude I’ve done this so much in my life I cannot tell you how many times I’ve done this dude I know I’m telling you which is me telling me I cannot help this one how do you undo that dude get res dude this is the greatest thing in the universe right there this solves that problem if you ever accident you’ve never done it really oh my gosh when I re when I when I get when I get rebase when I when I resolve a conflict I do get ad dot it immediately I go get ad rebase or get or get commit Dash app and I commit it and I’m like and I just hate it but if you just do a reset soft remember a soft takes the commits changes applies them to your work tree and moves your branch back once so you get all of your you get your rebase right there now I believe this has been largely fixed I believe now you can actually do a rebase uh continue even after you’ve committed it and it just works you just get that you get that new message instead before it used to not work I love this one why does get reset help you if you acent commit during a rebase because you can undo the commit and continue the rebase yes exactly that’s why I love it okay we’re going to go over a quick bit of squashing okay every Dev team will have different standards and opinions on on how to use git some teams require all poll request to contain a single commit While others prefer to see a series of small focused commits if you join a team that prefer single commit you’ll need to know how to squash your commits together to be fair even if you don’t need a single commit squashing is useful to keep your G history clean yes and it makes it easy to revert again if you have a feature that could be dangerous in production and it’s spread out over 12 commits that have like 18 merge commits it is really really annoying versus just having one commit at the end score squash it easy to put in easy to pull out okay what is squashing exactly well sound let’s see it’s what it sounds like we take all the changes from a series of commits and squash them into a single commit okay all of them A B C D to ax easy assignment let’s get ready to squash some commits push your current changes up to your forked repo on GitHub just in case your machine goes swimming don’t skip this okay here we go get push origin origin main go all right uh create a new Branch off Main called temp main get check out temp m-b let’s go all right so now that we have that we do all this let’s go let’s go we’re back in um to be completely fair I I mean I am just absolutely I I have what someone oh get checkout DB temp main yeah there we go all right how to squash perhaps confusingly squashing is done with get rebase command it may not be intuitive but remember re base allows you to apply or reapply history this will make sense more here’s the uh steps to squash the last end commits start an interactive rebase with get rebase head uh or slash or Dash ey I think they call it tack ey in the military get rebased hack I head till the end where n is the number of commits you want to squash get will open your default editor with a list of commits change the word pick to squash or S save and close the editor the I flag stands for interactive and allows you to edit the commit history before get applies the changes head till the end is how we reference the last end commits head points to the current commit there you go does that make sense uh why does rebase squash remember rebase is all about replaying changes when we uh rebase onto a specific commit end till the or head till the end we’re telling get to replay all the changes from the current branch on top of that commit then we are using the interactive flag to squash those changes so that rebase will apply them all in a single commit assignment Mega Corp Executives do not like your last few commits as a result your manager told you to squash the last three commits J L and K into a new single commit message J redacted squashing is destructive operation which is why you’ve decided to make the change to Temp main before moving it to main while on temp main squash these three don’t forget to pick or squash it and edit J redacted let’s go uh so I’m going to go like this get rebase or first get log so we want to go all the way to J so 1 2 3 uh get rebase I head 3 Let’s Go so I always go like this there we go you’ll notice right here it says it right here that you can do that s stands for squash use the commit and meld it into the previous so that means s uh go let’s see how does this go it goes this let’s see this one goes into the previous and then this one I forget how exactly how these things end up but either way it ends up it ends up good I forget the exact merging order uh redacted right there we go there we go so if I go get log uh one line you can see that J is redacted and the rest are all right there perfect right but they still can change the change set so if I go- P it still has the whole change set it just doesn’t have uh what’s it called it just doesn’t have the individual commits all right override now that temp main is in the state you want and hopefully you verified that with Git log we need to do uh what the boss asked delete the main branch rename the 10 Branch into main ensure that t main branch is gone resubmit now obviously this is a very dangerous operations we rewriting public history we’re doing it just for fun because hey why not uh but we’re doing it okay so don’t don’t do that by the way Branch delete main get check out um get oh don’t actually do uh temp main main this is this is dangerous okay there we go we did some naughty stuff we squashed main which means that because our remote main branch on GitHub uh has commits that we removed git won’t allow us to push our changes because they’re totally out of sync git push has a command called Force flag which allows us to override a remote Branch with our local branch it’s very dangerous but useful flag that overrides the safeguards and just says make this Branch as same as the branch so by doing this we’re actually changing that stuff and that could be obviously you would never want to do this to a main okay just so you know go ahead and force push your local main to the branch on remote main uh I know by the way you should never actually do this okay this this is this is crazy okay squashing is scary when you squash commits for example ABCD and you into a single commit you’re removing history from a project so all the changes are still there but the individual markers of each changes are gone it’s one big commit now in the last few lessons we erased all the commits meaning we can’t go back to the individual checkpoints anymore or you can’t go back easily we can still use git plumbing and reflog to actually rehydrate everything and reput it back into it we can but we’re just currently not doing that when you squash commits you lose history of the individual commits that’s what happens you can still get it back it’s just that it’s just non-trivial right when you squash commits the content stays the same correct the content stays the change it’s just that you change the commits yeah never squash Master never squash master I put that in there so I could talk about it and why it’s crazy we did some weird thing squash commits to m now let’s do a common thing squash all commits on a feature Branch for a poll request if your team prefers single commit poll request we will likely be your workflow create a new Branch off Main go about your work when you’re ready to get your code into main squash all your commits into a single one push your branch to the remote One open up a poll request merge it uh once it’s approved all right assignment first let’s just do points one and two Mega Corp needs to add a new feature to the content management system specifically they need a script that will automatically scan for sensitive information in the repo create a new Branch add scanner off of Main all right this is where things are going to get a little bit wild here get Branch or uh check out dasb I know it’s switch I can’t I don’t want to do it I don’t want to do it I’m too much of a lite um all right in the scripts directory there’s a file called scan sh replace uh the to-do comment with this all right I can’t help it okay all right in the scripts uh thing scan f8 write the script there we go we got it um all right there we go we have that one run the code from the root repo all right look at that we have oh my gosh we have so many social SEC or credit cards so many co credit cards just flying everywhere finally now we can do social security numbers add another few lines to the script all right there we go uh run the script again to ensure it works oh did I not oh I forgot to commit oh I forgot to commit I forgot to commit hold on k um uh credits there we go wait why isn’t that working oh did I did I actually delete oh crap all right there we go now we can paste this in there we go all right there we go so now I can go CC and this one should be J right this should be L yep okay so this one will be L um this one will be uh Social Security numbers my bad my bad I accidentally did that one out of order now we should do phone numbers there we go add add one for phone numbers added it for phone numbers there we go there’s some phone numbers in there CC uh and this is HJ K LM uh phone numbers there we go looking good run the script one last time make sure it works there we go all right I actually uh I accidentally uh I accidental your commit I know happens there we go all right so we got ourselves set up for this nice next one squash series remember the full workflow we’re going to be doing which we already talked about this creating your branch making your commits squashing it making the pull request let’s tackle point three squash uh KLM into a single uh new commit starting with k remove L&M all right so do it again get rebase I head till the3 do these ones uh SS there we go and go into k there we go Bam Bam Bam Bam got those two uh we are rewriting the history of our own uh Branch let’s see to make it look as if we did all the work in a single Commit This is normal and fine because it’s our Branch yes it’s our Branch now it’s okay to do right now it’s okay before it wasn’t okay to do and we did it on Main which we shouldn’t have done it on Main but it’s give me something to talk about give me a reason not to do that our Branch all right so now we’re going to do four and five uh use get push to add scanner and open a PO request all right get push origin uh add scanner there we go we’re going to do that and we’re going to go to back end we’re going to go to GitHub the prime gen which update Mega Corp and there we go P requests new pull request add scanner let’s go create pull request create it let’s go looking good looking good oh my goodness how do you not have my repo name I thought you had it all right I’m just going to copy that one and bring it back in here and go the primagen there we go and run all checks oh am I doing it oh uh to main on your mega Corp oh crap I did on I did it on your mega Corp I didn’t read the instructions good I in fact did not read good instructions here I in facted terrible instructions reading there we go uh apparently I can’t change uh where my remote is pointing to which is kind of weird that’s fine GitHub the prime engine um mega Corp there we go so I effed it up I effed it up apparently the UI doesn’t let you change the base reading instructions are required for squares yeah losers add scanner there we go sorry the previous one didn’t require me to required me to do it on a different one so it got me a little bit confused all right there we go merge the poll request remember we did all that one now let’s tle pack point six merge your pull request from uh ad scanner into main you can also do so by clicking the Big Green merge request button uh when you’re done you switch back to main branch locally here’s the scary part delete your local ad scanner Branch pull the latest change it from Main and your local main branch should have a now commit K yeah some people get freaked out it’s okay when you have centralized merge stuff it’s not a big deal hit the big green button confirm the merge get check out main get Branch Big D delete add scanner right boom get it out get uh pull oh my gosh I didn’t set I didn’t set that there we go get pull my Branch wasn’t pulled there we go look at that good yeah there we go we got the energy we got it all done absolutely fantastic it’s all in all right wait did that mean I did it [Music] okay stash all right so now we’re going on to stash are you guys ready for some stash all right you’ve been at Mega cor for a while three whole days and to your mother surprise you’re still employed here’s the workflow you’ve been using as a junior developer commit some let’s see commit some changes to a feature branch open a poll request from that feature Branch to Maine check out the new feature branch and and start back to the next task today however is a big day all right today is a big let’s see big day let’s see the customers are complaining about a critical bug and the CEO saw you first she asked you to drop everything and fix it immediately but you’ve got a bunch of unstaged changes that you’re not ready to commit yet and you don’t want to lose what do many git noobs would create a second clone of the git repo at this point a huge mistake you’re better than that that’s right you are better than that uh the get stash command records the current state of your working directory and the index staging area it’s kind of like your computer’s copy paste clipboard it records those changes in a safe place and reverts the working directory to match the head commit the last commit on your current Branch to stash your current changes do get stash yeah and stash list to list your changes don’t look at that my stashing workflow looks a little something like this I usually have some amount of work that’s in my index or my work tree and I get a request in that says hey can you please investigate this bug or hey you need to pull in the latest changes because if you pull in the latest changes the feature you’re developing will have a couple extra apis that you need which means I’m going to have to take my changes create a commit pull in the new changes finish off the change I wanted to make create another commit then squash those two commits into one or I could just stash my work tree and my index pull in the changes and then pop off my stash when I need to get back to doing what I was doing and finish the change I was trying to make now the the times that I don’t do that approach the times that I don’t choose stash which often I do is whenever I had to pull in a change but I’m already in several commits into a change I’m trying to make typically I try to keep my changes pretty small but every now and then you’ll have like a thousand line change and whenever I have a big change like that I try to make small commits along the way as nice checkpoints in case I screw something up so bad that I can just roll back to the last known working commit and then start again so if that happens I simply make another temporary commit rebase in my changes and then at the end of everything I’m doing I already have worked in that I’m going to squash everything down to one commit anyway so it doesn’t bother me all right assignment while on Main update readme.md in the root of megga Cort repo to do this one B bam just after updating read me uh that the CEO approached you stash the changes once you’re stashed make sure that they are uh safe in your list let’s see they are safe by listing now it’s okay you would be able to single see a single stash list okay all right um let’s go into here let’s go to read me uh let’s let’s see let’s delete that and go to this one there we go GS we have look at this look at this we have our read me but bam we got to stash some changes so I’m going to jump in here and go uh so for those that don’t know get stash all it does uh is it takes whatever you were doing and puts it into like a special area it’s kind of like uh it’s kind of like it it’s kind of like a commit uh so if I look at get status you’ll notice there’s nothing there get stash list uh you’ll notice that there is one right here if we go get stash list I believe it’s- P you can see the change right here right it’s just like a special place to be able to put changes for a moment I never use it longterm if you use it long term you’re crazy don’t do that that’s absolutely nutty to do right absolute nutty to do all right stash has a few options get stash pop list the pop command will by default uh apply your most recent stash ENT to your working directory and remove it from the stash list it is effectively UND does the stash command it gets you back to where you were this is called a stack and that’s important okay pop your stash change back out you should see it working get stash uh pop so it’s a stack and that’s really really important to know because if you push two things on top of your stash you will have your latest one on top the stash command stores your changes uh in a stack Pho data structure also I wouldn’t say uh I wouldn’t say Pho okay I’m last in first out I’m more of a lifo kind of person Lane again your copy editing hurts my feelings here I’m a lifo not a pho or not a I’m a lifo not a pho yeah for sure that means that whenever you retrieve your changes from the stash you always get the most recent changes that’s true bada bam uh Pho is greater than lifo W Lane false all right stash is a collection of changes that you have not committed they might be raw working directory changes or they might be stage changes both can be stash for example example make some changes to your working directory stash those changes make some more CH let’s see make some more changes without stage them stash all of that when you do that the stash entry will contain both staged and unstaged changes and both your working directory and index will be reverted to the state of your last commit it’s very convenient way to pause your work and come back later git stash is a very convenient feature of git in which allows you to store your index and your work tree into a special area known as the stash and then later on to be able to pop off those changes and reapply them to your work tree /index but what is the stash well it’s a data structure that is a stack so every single time you have a change to your index SL workor tree and you want to save it for later when you call G stash it actually creates something that’s like a commit and adds it to this data structure pushes it onto the stash stack any files that were not a part of your index slthe work tree will simply be ignored when you call get stash pop it’s actually going to take the last thing that you added to the stash and apply it to your current work tree /index X that means if you stash three changes a b then C if you pop something off you’ll be popping off C then the next time you pop off it will be B then the final time you pop off it will be a if you’re unfamiliar with a stack it’s actually pretty simple think of a stack of plates if I add a plate then add a plate then add a plate if I wish to remove a plate I would never try to grab from the bottom IID just grab one from the top then the next one then the next one Whatever order you put in is the reverse order of what you take out in other words it’s a last in first out data structure you can inspect your git stash by simply executing git stash list which will show you in the order in which you pop out your stashes often I use the stash in a very one-dimensional way I have some changes that I need to pull in from Main so I’m going to stash my current changes pull them in pop off my current changes and continue on my work I never use the stash as like a long-term storage place just because my code changes so fast that it often gets out of date super quick what is not staged unchanged uh unstaged changes to the track let’s see to the tracked working directory stag changes committed changes you can’t stage a commit okay you can’t triple triple stamp a double stamp if you push three sets of changes into the stack let’s call the first one a the next B the last one C what happens when you run get stash pop the changes from C are applied to your working directory but the stash entry is not removed the changes from c i remember clicking this last time it got me this changes from C are applied to here working directly and the stash entry is removed let’s go multiple stashes you can stash changes with a message I rarely use stash in fact I never use stash messages that I can remember I’ve used it like once or twice the big reason why I don’t do that is whenever you’re doing this this means that you actually want to come back much later which to me just says this needs to be a branch in which you keep somewhere and then you can edit the commit if you want to you can rebase the commit uh for me stashing is a very very like temporal operation assignment restash the changes to readme with the message good marketing update the readme uh file again with the following contents right get stash uh message uh good marketing boom right and so we’re going to go back here and I’m going to go delete and I’m going to have this one there we go now let’s see stash those changes with bad marketing uh get stash bad marketing there we go and now we should do a stash list get stash list you can see these two different ones right here so that means if you add a p in here you can see the difference unite Marketing sales and service in a single app try Mega Corp starter Suite today there is nothing uh to install no credit card required the only thing standing between you and more customers are you are your terrible salespeople get started today it’s a pretty good that’s a pretty good one that’s feels good feels good all right so there we go all right unrelated commit now that you’ve safely stashed your current work let’s tackle the CEO’s urgent matter CG uh Mega corpse APO script or shell script truly is a feet of engineering it behaves exactly as the shell borne shell language but with the word let’s see but if the word shell or sh is ever mentioned in the standard out it will replace it with APO it’s a feature that customers love but it’s not working let’s see test by running scan with the APO language for Shell there we go we’re going to grab this one there we go so you can see it right here it’s all right there okay uh the grap command let’s see the grab command should filter out the output to the lines that contain sh uh you should see a couple lines which means APO sh isn’t doing its job uh the culprit is this line yeah yeah it should be replaced with SH not bash all right we’re going to update the script we’re going to update the script right all right let’s update the script man customers love just the craziest things huh uh scripts Apo there we go wait a second there it is we got the Apex okay you’re right get status get add this get commit get commit L the L stands for lovely reading the primin there we go all right now that we got that apply without removing from the stash so you can actually do that I’m not really sure the purpose of this but it does exist uh you can apply without or you can you can remove from stash without applying this makes more sense Lane W Prim L yeah I know it happened reference a specific stash so you can actually do it in one of these locations with the at sign so that means we probably we’re going to have to do the one run uh get stash list see what uh see the stashes you have apply the changes from good marketing stash index without REM moving it from the stash list so we just have to do a little apply do one of these bad boys get stash list um paste that in there one there we go uh get add your changes to the index drop good marketing stash pop the only remaining one bad marking you should notice that you have a conflict resolve it by keeping the changes from good marketing stash commit the changes M all right let’s do that uh get stash drop um stash uh at one there we go get stash or get add this get stash pop wait oh whoopsies uh hold on get what happened get status did I miss what happened here uh Vim read me there we go I missed the message that said it it did the wrong thing so there we go I’m going to remove the bad marketing one call it a get I missed the conflict message how did I miss that oh it’s right there it was right there the whole time I just missant again it’s that reading thing you know what I mean okay it’s that reading thing that really gets me [Music] okay all right revert when reset is a sledgehammer revert is a scalpel uh revert is effectively an anti- commit it does not remove the commit like reset but instead creates a new commit that does the exact opposite of the commit being reverted it undoes the change but keeps the full history of the change and it’s undoing so it’s kind of like the Spider-Man thing you know I mean grug reading for a living but grug no read yeah I know it’s sometimes you feel right all right to revert a commit you need to know what commit the are the commit hash of the commit you want to revert you can do it with Git log all right and once you have it you do a little get revert hash with a committes assignment uh in your great haste of pursuit of greatness at Mega Corp you forgot to write a white paper and get approval from the l69 distinguished staff architect for your marketing documentation change the l69 has requested you revert the change and sure you are on Main revert commit M it should prompt you to write a commit message and we’re going to call it n let’s do it all right so we’re going to go like this uh get log one line so what do we need we need this guy right here bam get revert that one and save get log on line you can see right here here looks like this get log um on line- P2 so look at this you can you can see that it’s literally the inversion of it the starter repo for the G course 2 that one removed it this one added it back this one added this this one removed it this one added that that one removed it so it’s like an inversion so that’s what a revert does it literally does like an anti-matter commit to your history and then it turns it into a commit so you actually have it as a part of your graph Oh shoot that’s not right right that’s not right that’s not right did I mess that up I must have messed that up yeah see it says get revert M okay that’s my bad uh get commit uh amend all right there we go that was my fault that was my fault still doesn’t read I still I literally cannot read the get diff command shows you the difference between stuff differences between commits and the working tree Etc I frequently use it to look at changes between the current state of my code and the last commment um I use it to look at I I primarily use it to look not at that I primar well I mean yes actually that’s exactly I my current state sorry that red funny what my current changes are I rarely use it for uh staged stuff if you want to do stage you have to do dash dash staged uh show the changes between the working Tre the last commit uh you can do that you can do difference between branches you can do difference between two hashes I’ve tried to do this for bigger ones in bigger projects once you get to a certain size it’s like impossible diff the changes between n and M commits remember n is the version of changes and paste the full output in here get diff uh a head till one I believe is all I need to do I think I can’t remember submit boom yeah there we go bro do you even diff I diff I diff okay just copy P into notepad Plus+ with the differences extension wait what why would you do that revert versus reset reset soft undoes the Comm but keeps the uh stage changes undoes the commit and discards the changes revert creates a new commit and undoes the previous commit there you go when to reset if you’re working on your own branch and you’re just undoing something you’ve already committed say you’re cleaning everything up so you can open a poll request then get reset is probably what you want however if you want to undo change that’s already on the shared branch especially if it’s an older change then get revert is the safer option it won’t rate any history and therefore you won’t step on your co-worker toes don’t look at that don’t look at it when do you use reverse versus reset well they’re actually quite different operations so you just need to understand them fundamentally and it’ll become obvious when you use one versus the other whenever I use reset it’s because I want to be able to take a commit undo that commit make some edits and recommit and in the case of get reset hard I actually just want to throw away that commit this means I’m working on my own Branch not on a branch everybody else uses I’m able to edit the history and get it into the way I would like it to be whereas a revert is more for the public Branch what this means is that you have a problematic commit and you need to be able to remove that commit but you could never do that to a public branches it’s going to break everybody so instead you make like an anti-matter commit right this commit contains changes a this one reverts changes a and this also has the added benefit that if you want to go back in time you can go back to a and actually fix the bug and then reintroduce a along with its bug fix now I find that I revert when I’m on a larger team because often you’re in this position where where somebody needs this change to go out such that a new customer feature or a new Ab test that’s high priority has to get out but your changes have broken the build and we’re not discovered until we released into production so we need them out right away there is no waiting there is no waiting to fix forward so therefore you simply revert your commit fix the change create a new commit with the fixed code and all the changes back in and then next release your code can go out and hopefully it’s not broken but if you find yourself reverting a lot it’s likely because you have a pretty unhealthy process your cicd is not up to Snuff your tests aren’t quite there your automation is no good production is the ultimate place to test but it should not be the only place you test which creates a new commit revert let’s go Which rewrites history [Music] reset all right there we go cherry pick everyone loves cherry pick this comes a time in every developer’s life when you want to yink a commit from a brand but you don’t want to merge or rebase because you don’t want all the commits get cherry pick is another one of these very useful git operations but you infrequently need to use it cherry pick is when you want one change from a branch but you don’t want the entire history of the branch you only just want say a singular commit or two commits Where cherry pick is obviously useful is when you have a branch that’s called release and then you have your main development line every now and then release gets cut and that Branch gets updated now let’s pretend you’ve been going in their there’s hundreds of commit in Maine but we discover a bug in production well we can fix the bug in Maine and then just transfer over that one in singular commit to release and then reproducti release thus fixing the bug but we don’t contain all of the changes from Maine because those changes are largely untested or may they contain half-baked features that are not ready to go out quite yet so This Is Where cherry pick Works a switch to a new Branch off of Main called ad Partners update the partners organization to be this one commit the changes with o update the same file again with P all right let’s do that uh all right get Branch let’s see what branches I have all right cool get uh check out dasb still not doing it still not using it Lane was just like we should use switch and I was like dude I’m all About That C about that c get check out I just didn’t I can’t help it I can’t help it I I just I just have to all right there we go won’t sub if you don’t use switch nope then don’t sub I’ll ban you how about that one how about that one tough guy get commit d o okay the setup we’re going to do the setup my face oh than wait yes so now we got to do p all right uh Vim Partners uh dap paste let’s go here get status get status get add get commit dasp on the electric fence huh little call back to Ren and Stimpy I think I spelled fence wrong whatever that’s close enough you know what we’re close enough that’s a little Ren and Stimpy call back okay it’s been a long time since I’ve watched some Ren Stimpy okay close it enough all right what theme of V code is this you know exactly what theme it is can read nor write all right how to cherry pick uh first you need to clean uh clean working tree no one committed changes identify the commit you want to cherry pick typically with get log is a good one run get cherry pick commit or commit would be better get log to grab the first uh of the two commits we just made oh that’s the one we want get log there we go I’m going to grab this bad boy my oace then we’re going to go in here cherry pick o on to main ensure that it let’s see it worked by checking the partners one delete add Partners boom get Cherry uh pick that oh I just did it onto my own thing get uh get status it uh I didn’t even change branches uh abort abort abort boom oh my goodness I have a revert in Pro oh my goodness wait how am I how do I have a revert in progress how did I do that okay when when when did I do this all right hold on uh get log all right so I have the revert right here all right so that’s already been committed so that’s not a problem get uh get Branch we have our two branches I’m on Main uh let’s see no Cherry pit oh I have a board am I actually calling aort oh dude I’m so stupid I didn’t even see that I was doing aort okay I am really not reading it’s been a long day I don’t know if you guys know this but I’ve been streaming for track hours nine hours okay it’s been a long day all right there we go so I moved over this right here so I can go get log DP so we can see right here closed ml one of our favorite startups right can’t even read the timer okay shut up shut up it’s been so long I’m not good at doing this much this much stuff at a time all right we need to delete the ad partners get uh Branch delete ad Partners there we go the man’s losing I’ve lost it I fully lost it I’ve lost it I’ve lost it let’s go first [Music] try oh yeah we’re up to bisect do you like bisect you guys you guys want a BCT all right so bisect is fantastic let’s do this okay let’s do this get bisect is yet another get command that does sound quite intimidating to the uninitiated but once you learn how works it is actually quite simple get bisect allows you to find a commit in which introduced a bug really fast and it does this by using a technique called binary search let’s just pretend that we have a branch that has many commits on it our latest commit contains a bug and a 100 commits ago does not contain the bug how are you going to find when the bug was introduced well you could go step by step through it until you find where the bug’s at but that would be tedious if it takes couple minutes per try it could take all afternoon or multiple days but since commits are ordered by time in which they are merged we can actually pretend they are an ordered array and do a binary search across it so this is how git bisect Works let’s pretend that we have a known state that is bad and a known state that is good and we have a bunch of commits in between all of this we’ll call it X amounts of commits if we test the middle commit and let’s pretend we found this middle commit is good we know that all of this is good in other words we’ve cut our space in half we have x / 2us 1 left commits to check and if we repeat the process we can continue on finding smaller and smaller regions to go check for our commits if we find one of these are actually bad then we know that all of this direction is bad and we repeat this process until we’re able to find a singular commit that is the commit in which the bug was introduced if x was a th000 it would approximately take us 10 checks to find the bug and using git bisect is really simple you set the good commit you set the bad commit you say start and it will start doing that exact same process of cutting the known space in half asking you if this commit is good or bad if you answer good then it knows all the commits earlier are good if you answer bad it knows all the commits that are ahead are bad this can save you days of searching so we know how to fix problems in our code we can either revert the commit with a uh the bug this is more common on large teams or fail forward by just writing a new commit that fixes the bu this is more common on small teams well it’s if you have the time that’s the this is the ideal in my head is to be able to always fail forward right that is my favorite uh but there’s another question how do we find where the bug was introduced that’s where get bisect command comes in instead of manually checking all the commits that’s Big O O right Big O N I mean get bisect allows us to do a binary search which is login so that means after like what 10,000 it’s only 14 checks it’s the way to go so if you don’t know how to do bisect you bisect is fantastic if you’re working on a slightly old code base that has thousands or hundreds of commits right all right let’s see BCT isn’t just for bugs you can do anything so the nice part about this is anytime you have a change you’re looking for and you have a script that you can check then bi sector can be used to find where that say Improvement and performance Improvement was Ed introduced performance uh regression was introduced anything so bisect is fantastic the B the purpose of bisect is to split the repositories into two separate repositories split the commit into two find a commit that introduced a bug or change say it that way uh a commit to find a change that was introduced there are seven effective steps to bisecting that’s it there’s only a quick seven now you know you know me from reading right am I right you know my skills at reading so we’re about to go deep on this one okay yeah yeah all right start the bisect with get bisect start select a good commit select a bad commit uh get will check the commits between them and find it execute uh get BCT good or bad to say the current commit is good or bad uh loop back to step four exit with this one get bisect receip or uh reset there we go assignment your boss just chewed you out because the scan a sh script should never have been added to the repo not only does she want the contents of the script erased but she wants to know when the script was added and for you to fix it with get revert so the history of your Royal screw up is preserved considering you can’t remember when you wrote the script you decided to use get bisect start BCT you know the head commit is bad so Market is bad you know the first commit a is good so mark it as a if the script content is pres uh present not just a to-do comment Mark the script as bad otherwise mark it as good repeat step four until get bisect completes it should give you the hash of the commit all right so this should be pretty easy do you understand here right boss should have been in code riew yeah I know boss boss yapping but boss wasn’t wasn’t reviewing that’s what I’m seeing right now people lot of yapping not a lot of looking uh all right let’s see revert the commit that introduced the script with commit message P am I right am I right all right so let’s find out when that happens so we’re going to go like this I’m going to do the following I’m going to go get uh Buy uh um start right so we’re going to start it waiting for both good and bad commits so I’m going to go get a BCT uh bad so that just says oh did I BCT there we go I literally could not see the difference there bad so you don’t actually have to provide a commit if you want to use the current one so there we go I just used the current one uh get log one line go all the way down to the bottom get uh BCT good we know is somewhere right there so now notice that it has six rever Visions left uh to test after this roughly three steps so we can go we can go cat uh scripts scan word count line all right so there is one line so this was just the to-do right so when it has one line it is the to-do okay so that would be get bisect good we like that one this one has 10 lines so that one’s bad this one’s bad all right this one’s so this one’s also bad all right this one’s good I’ll explain what’s happening in more detail here for a second there we go you can see exactly where this has happened and you can even see right here K credits so all right I think this is good uh get log DP this thing you can even see right here this is where the changes were made to the uh scan script so what actually happened there it’s actually not that bad you can imagine that at a that’s our first commit and I forget what our uh head is right whatever commit that was head how a bisect actually works is that remember each Comm has an ordering to it this is an ordered array therefore the ordering of course being merge order or it’s going to be like say time and so that means we’re going to go b c and all the way up to head that means if we check the middle element and it’s bad that means this entire side is bad but if we check the middle element and it’s good that means this entire side is good so since the first one was good we know that all of we know that all of this let’s see hold on shoot which one is that if we know this one was good we know that the rest of these were good right here so that means we went in the middle of this one so then when we checked here and it was bad we knew that all of these were bad so then we went into the middle right here and when we checked this one since it was bad as well we knew that all these are bad so we went and checked right here and since that one was good then either the one right after it since there’s only one commit left between these two it was able to say that this one was the bad one it’s a binary search that’s effectively what happened right sorry for my fairly shoddy explanation but that’s all it is bisect is really simple right it’s it’s it’s really easy you can think of this like an ordered array imagine you have an array that goes 1 2 3 4 5 6 7 8 and you wanted to find out if it has the number six well what you could do is if this is zero and this would be uh8 right the ending it’s of length eight you could do 8 minus 0 ID two which gives you four and you can check this one is this six no it’s not is it greater than it is since it’s greater we need to check this one okay that means we need to update our lower bound to this one so now that’s going to be three 0 1 2 3 we still have eight as the length so we do it again what is 8 – 3 / 2 which is going to be what two 2 and a half two then add it to three so we got to go to five which is going to be four five is this one it yes it is we’re done say we’re looking for seven then we do the exact same thing again which we’d have to go to Five 8 – 5 is 1 divide by two that or that’s three divid by two that’s one add it to one all right seven check here is this it yes it is good so that’s all it is it’s pretty easy um binary search is really really easy to do right and it’s great it’s actually really really great so that’s all bisect was doing was that so now that we have that we’re going to go like this uh get uh BCT uh reset oh my goodness BCT I I I can’t read that word get uh revert that one p there we go sounds like successive approximation well whenever you have an order you can search the space more efficiently given an input if you don’t have an order you cannot search space efficiently that’s why things like uh that’s why eventually you just have to do a linear search through everything if you have no order linear is quote unquote slow linear is slow but it’s not as bad as like quadratic or uh even more that was annoying now imagine if testing wasn’t as simple as just looking at a file manually running an automated test can take a long time as compiling uh a gasp J Java Enterprise project absolutely uh for the man get BCT you can do bisect run now this is cool okay bisect run allows you to be able to do that process we just did but in an automated way now this is very important because sometimes you have to sit there for 30 minutes for something to tell you if it’s correct or not so it’s much nicer to be able to just have this thing run and then you go play I don’t know play game basketball whatever you do I’m not sure what you do okay so there we go there we go let’s create a new script in scripts called BCT sh with this contents so that means if we find scanning in the scan we exit with a bad exit code if we don’t find it we exit with a good exit code in other words uh BCT when you run it uses the exit code to determine if it’s a good or bad build so let’s go in here Vim this thing up go into scripts go BCT Dosh go in here do that make it executable uh I prefer to hit a oh yeah I guess I don’t need to do I don’t need to do a shebang there we go and now I need I can go into here and do the exact same thing and I can run this script now so I can go like this we already chimed it we can do a bisc start and go get uh get BCT uh start get BCT bad get BCT good that there we go so we have our head to our tail and now we’re going to run through and do this thing even though technically we’re doing a bad with our current one you know there’s a little bit of something weird here so I can go cuz we reverted it so technically our head break our whole ordering but don’t worry about it we we can skip that get bisect run um scripts bisect and I believe we don’t need to yeah there we go we don’t need to provide any arguments so when we do this one there we go it found it is able to run that script super fast and find it immediately there we go and now we know where the problem was see bisect is pretty cool what does automating bisect require uh an automated test that can programmatically inform git if the current commit is good or bad that’s pretty much it there we go all right work trees uh we’ve been saying work tree all throughout this course but I have been misusing it I am sorry it’s not technically what we’re on is not called it’s not work tree precisely uh it’s the main work tree which is more precise because you can have more than one working tree what is a work tree a work tree or a working tree or working directory is just the directory on your file system where the code you are tracking with Git lives usually it’s just the root of your git repo where the dogit repo is it contains tracked files untracked files modified files right everyone know everyone can fundamentally understand what a work tree is your main working tree just makes sense the work tree command get as a work tree command that allows you to work the work trees the first subcommand we’ll worry about is simple get work tree list it lists all the working trees you created all right so let’s see what working trees we’ve created you’ll notice there’s only one working tree right yeah which is my current my current work tree right linked work trees uh we’ve talked about stash temporary storage for changes branches parallel lines of development clone copying an entire repo work trees accomplish a similar goal allow you to work on different changes without losing work but are particularly useful when you want to switch back and forth between two change sets without having to run a bunch of git commands not branches or stash you want to keep a light foot print on your machine that’s still connected to the main repo not a clone so this work trees effectively allow you not to have to clone out a repo for a second version of it there’s some like requirements there’s some rules I think I go over the exact rules in here the main work tree contains a git directory that’s important with the entire state of the repo heavy lots of data in there to get a new main working tree requires get clone or get a knit uh a link work tree contains a git file with a path to the main working tree it’s effectively as light you can think of it as almost as light as a branch it’s just like a little bit heavier than a branch U let’s see uh can be complicated to work with when it comes to end files and secrets this is where things kind of usually go off the rails for work trees is work trees can be a pain in the butt when you have uh say node modules node modules can be really annoying so we can create a new work tree like this we do this uh whenever you do a path on an ad if you do not include a branch name it takes the the uh first baster of the path and uses that as the branch name and it’ll actually create it so we can create a linked working tree uh as a sister directory to your main working tree called alra Corp uh use the default Ultra Corp Branch so watch this so I can go uh oopsies uh get uh get a bict uh reset forgot to do that get a work uh tree ad what is it it’s path which is going to be let’s call it Ultra Corp there we go so prepared to new work tree it’s called alra Corp so if I go here back out and go Ultra Corp you’ll notice that Ultra Corp is on Branch alra Corp because that was the Bas that was the first base dur of the path that I did so if I would have done like Ultra Corp SL fuar then the branch would have been bar if that makes sense and so now if I go like this cat get you’ll notice it’s literally just a pointer to where it needs to be right so there it is primagen personal Mega Cort get work trees Ultra Corp so it’s saying where it’s located at pretty cool right I’ve been programming for 12 years and I like to think of get as magic under the hood it’s really it’s it’s it’s shockingly it’s not the most complicated piece of software I’m sure the actual operations for like creating and deleting files and stuff like that is complicated but everything else is uh like how it works is actually not like the most oh my gosh how could this possibly be right all right no duplicate branches linked work trees uh behave like normal get repos you can create branches switch branches delete branches create tags Etc but there is one thing you cannot do you cannot work on the branch that is currently checked out by another tree branch navigate to ultra Corp attempt to switch to main so when I try to switch out main it says already used right makes sense right yeah tracking so how does your main tree uh main working tree know about your linked working tree well the reference is stored in G work trees directory list the contents of this directory so if we go like this if we go to here and go uh ls- La get work trees this is a new one you’ll notice that Ultra Corp is right here so if I go in here you’ll notice that it has effectively the entirety of everything you need to know about it where its head is pointing it’s like a mini little it’s like a little mini git experiences going on right here here and even has a g dur and you’ll notice that the G dur if we look at it will actually be like the inversion of the other one whoopsies there we go oh my goodness how did I get that there we go it’s the path to where we’re going so that’s how it know it exists that’s why when I go work tree list it’s able to actually find this if I were to delete Ultra Corp it’ actually say like dead or prune or something like that removed I forget what it says but it says something how does the work tree keep track of it the main working let’s see the work Tre directory contains references to them yep Mega corpse IT staff manually logs it in Juro their project manager software actual magic which one is it all right when you make a change in a linked work tree the change is automatically reflected in the main work tree it makes sense the linked work tree doesn’t have a g directory so it’s not a separate repository it’s just a different view of the same repository you can almost think of a linked work tree as just another branch in the same repo but with its own space on the file system run get branch on your main work tree uh and answer the question so if I click this get Branch look at that you can even see the little plus sign right there that’s because it’s being checked out in a work tree it’s kind of fun thing uh how can you tell if a branch has checked out uh in a different work tree uh the branch will have no prefix that has a plus prefix let’s go plus prefix let’s go deleting work trees you may never need the stash again this is the nice part about working with work trees is you don’t actually ever need the stash ever again you can have two work trees that are always you know you can switch between them you can always check out a new one every time you work on a branch I had somebody at my old uh job tell me that stashing or switching branches is an anti- pattern you should just always work tree um anyways however at some point you need to clean up your work trees the simplest way was to remove the subcommand you can do a remove but you can also do something cooler which I actually prefer you can just delete the directory watch this one uh let’s see hold on does it say that remove alra Corp cool get uh rmrf backback alra Corp there we go so if I go get work tree list again you can see this right here see prunable I knew it said something I couldn’t remember the word it said but now that means if I go get work tree prune it’s able to tell what to prune because remember when we did this when we CED the gter ultra Corp had a directory so when it goes and it goes here it cats out this thing it stats that file when that file doesn’t exist then it knows that it doesn’t work that this thing has been detached what about npn modules you have that I mean you can copy you can create a script right I just I talked about that the whole environment part of work trees can be difficult right there we go bam I always had like two or three working trees and I would actually just switch between them so whenever I needed to do something I could actually just grab that and change it all right tags uh we’re going to wrap up this course with an easy one tags tags again I showed this at the very beginning of the course tags has the craziest user manual but it’s so simple to list all the tags you can just do get tag so get tag I have no tags very very easy tag is just an immutable pointer to a commit very very nice we can create a tag by just doing this tag a give it a tag name give it a message all of that all right create a tag on the latest commit p with the name candidate and a descriptive message all right get tag uh a see so we can go get tag- a if you want a name so the name can be candidate like that right and then you can do a message message such candid candidate boom get tag look at that beauty right there you can you can also if I’m not mistaken you can also create a uh tag without having to do this right there you go you don’t have to use a a it’s like the default first parameter there we go now tags remember you cannot edit a tag so when I check out a tag get check out tag let’s you get check out candidate I go into a detached head State like you can’t make edits to a tag tags are immutable pointers it’s very important to remember that and also one last thing get log one line you can also see uh tags when you have decorations which is nice why would one use a tag oh very very simple let’s go like this let’s go to uh GitHub uh react let’s just go check out the react Library let’s check out what tags they have tags do those look familiar if you’ve kept track at all react server components exist in 18 right people typically use tags to point to versions that are released in public so this is like a very normal Behavior Uh that you should see tags for they’re usually some sort of release uh now you can do stuff with sver this is typically how people do this with just sver it’s kind of weird to just name tags any old thing we’re developers we like structure sameness and sometimes even bike shedding I love bike Shing sver semantic versioning is a name and Convention by the way I’ve been bit so hard by sver because of this one right here minor sometimes it isn’t a safe feature if people change default parameters just so you know default parameters don’t technically break major versioning of sver and can screw you just so you know just in case you’re wondering note V isn’t actually a part of the sver correct major this means a change to the API in which will break compiling code minor means a an additive change to the API that won’t break a code patch means no change to the API at all there you go um that’s the easiest way to say it uh the sort let’s see to sort them from highest to lowest uh you first compare the major versions then a major minor versions then finally patch versions for example major version 2 is always greater than major version one regardless of the minor version absolutely if I’m using some code that’s on V1 124 and I see a new version 224 is available should I expect to be able to safely upgrade without making any changes to use it no major versions are not backwards compatible or typically are not major are not backwards compatible good thing to know you know what I mean good thing to know what’s the highest version 422 422 let’s go I’m so good at this I’m so good at this conventional tags um tags are used for all sorts of reasons but sometimes they’re used to uh to denote releases in that case tags follow the sver are common right here so tags this is very normal right fun fact pretty much anywhere you can use a commit hash you can use a tag uh name when working with Git right it’s a commit let’s see assignment add another tag to this let’s see to the same latest commit right commits going have multiple tags which we already did and then there we go boom uh get tag V 1.0.0 that’d be like oopsies that’d be like a normal one get push uh tags there we go push them all up let’s go got it tags okay guys stop making fun of my tags there we go we’re done I just did two git courses thank you very very much I hope you enjoyed this presentation of boot dodev GS course in which I helped create quite a bit the name is the primagen boot. deprime use it

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • The Muslim World’s Struggle for Identity

    The Muslim World’s Struggle for Identity

    The provided text is a collection of excerpts from a work exploring the complex identity and challenges faced by Muslims. It examines historical and contemporary issues, including religious practices, political conflicts, and the struggle to maintain cultural identity in a diverse and often hostile world. The writing reflects anxieties about minority status, cultural preservation, and the internal conflicts within the Muslim community. The author uses historical and religious references to illustrate these concerns, weaving together narratives, anecdotes, and reflections. Ultimately, the text advocates for a more unified and tolerant approach to Islam and its place in the world.

    Islamic Thought & Identity: A Study Guide

    Quiz

    Instructions: Answer each question in 2-3 sentences.

    1. According to the text, what is the significance of a mother’s death in the context of poverty and how does it compare to the status of Maulvi Mir Hasan?
    2. Explain how the text uses the concept of “tribe” and its associated deities in relation to various religious traditions.
    3. What is the central issue surrounding the “Nazar doctor” and his relationship with the individual who is presenting the issue?
    4. How does the text portray the relationship between the Prophet Muhammad and Mecca, and what is the significance of the Masjid-e-Haram in this context?
    5. Describe the tension presented in the text between the desire for Muslim unity and the reality of internal divisions and fears within the Muslim community.
    6. What is the author’s view on the role of religious fanatics and their impact on the perception of Islam?
    7. Explain the author’s assertion that “Muslims are neither getting destroyed nor are being thrown into the well” in the context of their political engagement in non-Muslim states.
    8. According to the text, what is the author’s view on maintaining one’s identity and how does it relate to the broader goal of human unity?
    9. What is the author’s position on the need for political activity and what is the connection to the history of religious communities?
    10. What is the central point the author is trying to make about the importance of humanism and unity?

    Quiz Answer Key

    1. The text suggests that a mother’s death due to poverty is a profoundly significant event, elevating her status above a figure like Maulvi Mir Hasan, whose mistakes are considered unforgivable. This highlights the immense value placed on motherhood and the impact of socio-economic hardship.
    2. The text uses “tribe” to connect ancient deities and religious practices, such as those of the Greeks, Egyptians, and Hindus, to the idea of distinct communal identities, similar to how the concept of God Israel is used in the Bible. This shows how different cultures have had their own ways of representing God, creating varied forms of religious devotion.
    3. The “Nazar doctor” is presented as someone with authority, possibly a leader or figure of importance, who is being challenged by a Muslim seeking recognition as an equal. The central conflict involves the tension between religious identity and human equality.
    4. The text suggests that the Prophet of Mecca stands above the history of the book and the Masjid-e-Haram, highlighting the central role of the Prophet and his teachings for Muslims. The Mosque acts as a symbol of religious community and identity, further establishing the historical significance of the city and Islam.
    5. The text highlights an internal conflict where the community desires unity and solidarity, but is hampered by internal fears, anxieties, and divisions, such as between sects. These divisions are an obstacle to a united Muslim identity, with these fears and conflicts becoming major issues.
    6. The author views religious fanatics as problematic, suggesting that their actions and narrow interpretations of Islam negatively impact the broader perception of the faith, creating further division and fear within the world. Fanatics are seen as a source of trouble for everyone, not just non-believers.
    7. The author argues that Muslims are navigating political landscapes in non-Muslim states effectively, achieving their goals, rather than facing destruction or persecution, suggesting a degree of resilience and agency in their political strategies within various states. They are also using non-Muslim states to their own benefit.
    8. While the author believes that maintaining one’s identity is important, it should not come at the expense of human unity. The text seeks a balance between individual identities and the collective goal of a shared humanity.
    9. The author argues that political action is acceptable if it is designed to promote human rights and freedoms and religious rights. The text points to the importance of maintaining and recognizing political rights for a religious community.
    10. The text advocates for a universalist view of humanity, emphasizing the importance of compassion, unity, and love for all people, regardless of religious or cultural background, positioning these virtues as the essence of Islamic thought and teachings.

    Essay Questions

    1. Analyze the complex relationship between religious identity and political engagement as portrayed in the text. How does the author navigate the tensions between maintaining Muslim identity and advocating for universal human rights?
    2. Explore the recurring theme of fear and anxiety within the Muslim community as described in the text. What are the sources of these fears, and how do they affect the community’s sense of identity and belonging?
    3. Discuss the author’s critique of religious fanaticism and its impact on the perception of Islam. How does the author propose balancing religious devotion with a commitment to humanism and tolerance?
    4. Examine the ways in which the text uses historical and religious figures and events to illustrate contemporary issues faced by Muslims. What are the key lessons and insights derived from these references?
    5. Evaluate the author’s perspective on the role of the individual in shaping their identity and the collective identity of the Muslim community. To what extent does the author emphasize personal responsibility and agency in addressing the challenges facing the Muslim world?

    Glossary of Key Terms

    Al-Kitab: (Arabic: الكتاب) Literally “the Book,” referring to the divine scriptures, often specifically the Quran in Islamic context, as is true in the provided text. It can also refer to scripture in general. Baitul Muqaddas: (Arabic: بيت المقدس) The Arabic name for Jerusalem, a city of significance to Muslims as well as other religious groups. Bani Saleel: A term used in the text, referencing people or a community that is not fully defined; it is a contested term used in the text that refers to people seen as an outgroup. Darvesh: A term used in the text referring to a person who is seen as a holy man. Dawat: The Arabic word for invitation. In the context of Islam, it often refers to the invitation to Islam or the call to faith. Geeta: Refers to the Bhagavad Geeta, a revered Hindu scripture. Gupta Nazar: A contested term in the text, the meaning is unclear, possibly referring to someone’s opinion or gaze as interpreted by a religious tradition. Haram: (Arabic: حرام) Forbidden or prohibited in Islam. Refers to actions, objects, or behaviors that are deemed impermissible according to Islamic law. Hijra: (Arabic: هجرة) The migration or journey of the Prophet Muhammad and his followers from Mecca to Medina in 622 CE, a pivotal event in Islamic history. Jamiat: A term used in the text, referring to a group or association of people; this is a common term, used in many contexts. Jihad: (Arabic: جهاد) The struggle or striving in the path of God. This can encompass personal, spiritual, and, in some contexts, military efforts. Kufri Dab: A contested term in the text that refers to something associated with not believing, perhaps an anti-Muslim sentiment. Mashriqi: A term used in the text, likely referring to an Oriental or Eastern person/influence in relation to the Prophet of Mecca. Masjid-e-Haram: (Arabic: المسجد الحرام) The Sacred Mosque in Mecca, Islam’s holiest site. Maulvi: A Muslim religious scholar or cleric. Medina: A city in Saudi Arabia, also known as Al-Madinah, where the Prophet Muhammad established the first Muslim community after migrating from Mecca. Mughal: Relating to the Mughal Empire that controlled most of India from the 16th to the 18th century. Mushabat: The text is likely referring to Mushabihat, meaning similarity or likeness in Arabic. Nazar: (Arabic: نظر) “Sight” or “gaze.” In some contexts, this can also relate to religious beliefs about the evil eye. Nawab: A term from India referring to a ruler or noble. Purvanchal: A geographical and cultural region located in Eastern India. Qibla: The direction of the Kaaba in Mecca, toward which Muslims turn in prayer. Quran: (Arabic: القرآن) The holy book of Islam, believed by Muslims to be the word of God as revealed to the Prophet Muhammad. Ras Mufti: A contested term in the text, likely referring to a leading religious or legal official. Shakush: A contested term in the text; this could relate to a challenge or personal issue in the context of religious and personal identity. Sharia: Islamic law derived from the Quran and the teachings of the Prophet Muhammad. Vedas: A collection of ancient Hindu scriptures. Yagya: A Hindu religious ritual that is often a sacrifice.

    Muslim Identity, Global Politics, and Internal Conflict

    Okay, here’s a detailed briefing document analyzing the provided text, focusing on key themes, ideas, and significant quotes:

    Briefing Document: Analysis of “Pasted Text”

    Introduction:

    This document analyzes a complex and at times fragmented text that appears to be a personal reflection on Islam, Muslim identity, and global politics, seemingly from the perspective of someone deeply invested in the issues but struggling with internal contradictions and external pressures. The text meanders through personal anecdotes, historical references, religious interpretations, and observations on contemporary events. The writing style is very informal and at times unclear, potentially due to translation or transcription issues.

    Main Themes and Ideas:

    1. Internal Conflict within Muslim Identity: A major theme is the internal struggle of Muslims attempting to reconcile their faith with modernity, political realities, and diverse cultural contexts. The author grapples with the challenges of maintaining Islamic identity while living in non-Muslim majority nations, expressing fear of cultural assimilation and the loss of tradition:
    • Quote: “Muslims of India are victims of severe anxiety and confusion with regard to the Muslim community. They are filled with fear every moment.”
    • Quote: “Most of the Muslims are sad from inside. They feel this pain deeply that their children are becoming Islamic. They are sad that even then the Islamic culture is not getting the status which it deserves in their eyes.”
    1. Critique of Religious Dogmatism and Fanaticism: The text critiques rigid interpretations of Islam and the actions of extremist groups, highlighting how they undermine the core values of the faith. This is juxtaposed with a longing for the unifying, humanistic aspects of Islam:
    • Quote: “Today, we are troubled by the strict religious fanatics. They have a complaint on their thoughts that Mohammed is less rich.”
    • Quote: “Today’s increasing human sugar level has reached to a minimum then this is a pocket of humanity… Without any compulsion or feeling of complaint…”
    • Quote: “The fight of Muslims with the bad festival is not justified, those who cite the demand or search of the Prophet for the lack of Hazrat, they are also the pride of human nature”
    1. Historical and Theological References: The author draws from Islamic history, scripture (Quran), and other religious traditions (Bible, Vedas) to contextualize their points. They emphasize that historical figures like the Prophet Muhammad were not above criticism and change, suggesting a more nuanced reading of religious texts:
    • Quote: “…we can see the document of this tanzar with both the wrestlers, whisky in Medina…”
    • Quote: “In the very last part of his Meccan life he wrote a great paper on such issues but it will be interesting to know about it when he compared his question on Mecca with the history of the book.”
    • Quote: “Just as we see mention of God Israel repeatedly in the Bible, similarly we can read about the racial gods and goddesses of the Greeks and Egyptians in their Deity and in Hinduism as well.”
    1. Global Politics and Muslim Persecution: The text frequently addresses the plight of Muslims in various conflict zones, attributing much of their suffering to political interference and Western powers, with particular emphasis on the role of the US:
    • Quote: “Their huge population is looted. In the three states of Kashmir, Chechnya and Bosnia, various types of Muslims have been kept with the Muslims. Whatever America is doing in Afghanistan, it is at the heart of it.”
    • Quote: “With the force of propaganda, Muslims are spreading the news in videos that which stories they consider as attacks and we are ready to debate on each name and every village.”
    1. The Importance of Humanism and Unity: There is a consistent call for a universal understanding of Islam that prioritizes humanism, tolerance, and unity among all people, transcending religious and cultural differences:
    • Quote: “The world is God’s family, and God only likes those who love his goons…”
    • Quote: “You are explaining in this way the tolerance of humanity…”
    • Quote: “humanity is the power of our religion… its invitation is not an invitation to inferiority but to humanity.”
    1. Fear of Marginalization and the “Other”: The author expresses concern over the rise of Islamophobia and the perception of Muslims as inherently separate or threatening. They are critical of the ways in which Muslim identity is often defined by external, often negative stereotypes:
    • Quote: “Sometimes a strange issue arises, sometimes the dress and beard and sometimes the symbols of Muslim are given to the Manro of the Masajat and the wait begins that our identity, story, blurred weakness should not be spoiled…”
    • Quote: “They complain that like other people, Muslims should also settle in Magra. Despite being benefited by all the Musabahs, they consider our society to be poor.”
    • Quote: “The truth is that Muslims in Magra Today people give Islamo phobia to the things…”
    1. Critique of Nation-State and Political Manipulation: There’s a questioning of the modern nation-state and its impact on Muslim identity. The text implies that the formation of Pakistan has created more problems than it has solved. It suggests that political machinations by both non-Muslim and Muslim actors have led to increased suffering for the Muslim population.
    • Quote: “The Muslims of India are victims of severe anxiety and confusion with regard to the Muslim community.”
    • Quote: “Today, Muslims all over the world who are living their lives in non-Muslim areas through the politics of their cities, are achieving the goals of non-Muslim states in the light of principles. Due to this, Muslims are neither getting destroyed nor are being thrown into the well.”
    • Quote: “They had come giving advice that they are not going to look at us as loyal citizens of their country Hindustan, but in the first or second year of Pakistan’s assembly, while putting up their list, they clearly declared in the book that now neither Hindus will stay here nor Muslims.”

    Key Observations and Interpretations

    • Fragmented Narrative: The text’s lack of structure and frequent shifts in subject make it difficult to follow a linear argument. It reads more like a stream of consciousness reflecting the author’s ongoing engagement with complex issues.
    • Personal Struggle: The personal and emotional tone indicates a deep internal struggle to reconcile religious belief, cultural identity, and observations of global conflict.
    • Call for Self-Reflection: Despite the criticism directed towards others, there is a strong element of self-reflection within the text, urging Muslims to introspect and reconsider their approach to their faith and their place in the world.
    • The Importance of Historical Understanding: The author emphasizes that a true understanding of Islam requires a deep engagement with its history and context rather than just a superficial reading of religious texts.
    • Emphasis on Human Equality: Ultimately, the message seems to be a plea for recognizing the common humanity of all people, regardless of their religious or cultural backgrounds.

    Conclusion:

    This document indicates the complexities involved in understanding the Muslim experience in today’s world. The author’s perspective reveals the intense inner struggle of identity, and the external pressure of global politics and cultural misunderstandings. The document does not provide easy answers but serves as a valuable lens through which to observe the contemporary challenges of Islamic faith in the 21st century.

    This briefing document should provide a thorough overview of the main themes and ideas present in your text. Let me know if you would like further clarification on any point.

    Muslim Identity in a Complex World

    FAQ: Key Themes and Ideas

    1. What is the central conflict or tension explored in this text regarding Muslim identity?
    2. The text grapples with the internal conflict of Muslims navigating their identity in a complex world. It highlights tensions between maintaining religious and cultural traditions, while also participating in modern society. There is a struggle between the desire to maintain a distinct Muslim identity (e.g. through dress, practices) and the fear of that identity being marginalized or attacked, both internally by fanatical elements and externally by other groups. This conflict is exacerbated by a sense of being both a minority in some places and a majority in others, and the corresponding pressures and anxieties that arise from both positions. There is a consistent fear that Muslim identity will be “spoiled” or lost, whether through external forces, internal divisions or modernization. The text also addresses the tension between a more universal humanitarian vision and a more insular, particularist approach.
    3. How does the text portray the relationship between Islam and politics?
    4. The text presents a conflicted view of the relationship between Islam and politics. There is an acknowledgement that political forces have historically shaped the Muslim world, and that Muslims are engaging with politics in both Muslim-majority and minority countries. However, the text also seems critical of attempts to impose a singular political vision on all Muslims, stressing that a person’s political engagement is not a measure of their faith or their commitment to Islam. The text suggests that Muslims should focus on a wider sense of community and humanity, rather than adhering to strict political identities. A strong distinction is made between the need for political agency and the pitfalls of a singular political identity that can lead to division and conflict. The text questions the relevance of old political models like the Caliphate and seems to support an individual right to political expression even while stressing a universal identity.
    5. What does the text say about the role of tradition versus modernity in Muslim life?
    6. The text is deeply concerned with the relationship between tradition and modernity, and it doesn’t offer a simple answer. There is a clear appreciation of traditional practices and the deep history of Islamic civilization, but also an awareness that many things have changed. The text acknowledges the impact of modernization on Muslim societies and cultures around the world and sees that modernity poses challenges, such as cultural assimilation, loss of identity, and a fear that new generations are losing their connection to Islam, but also opportunities. The text does not condemn modernization, however, but rather encourages Muslims to engage with it in a way that honors their values and does not lead to intolerance.
    7. How does the text address the issue of religious diversity and tolerance?
    8. The text advocates for a more inclusive and tolerant view of religious diversity. While it acknowledges the importance of Islam to Muslims, it also highlights a universal notion of humanity where all people are seen as deserving of respect and dignity, and even as part of the same extended family. It criticizes those who use religion to justify hatred, oppression, or division, and promotes the idea that the core message of Islam is one of unity and humanity. The text also points to historical examples of tolerance and religious coexistence. The text sees the true essence of Islam as a message of human unity, tolerance and compassion. The text recognizes that conflict may exist between various groups, but that this conflict is not a function of religious differences alone but of political and power dynamics.
    9. What does the text suggest about the fears and anxieties faced by Muslims today?
    10. The text paints a vivid picture of the fears and anxieties that many Muslims experience today. These include the fear of oppression, violence, and discrimination, both in Muslim-majority and minority contexts, and an internal fear of losing their identity. There is anxiety about a perceived decline of Islamic culture, the influence of the outside world on the youth, and a concern about the internal conflicts that divide the community. The text points to the emotional toll these fears take on individuals and the need for Muslims to find inner peace and stability. The fear of “group phobia”, is identified as a key source of concern. These fears are shown to be related to both external aggression and internal conflict.
    11. How does the text define the relationship between individual identity and communal identity?
    12. The text presents a complex interplay between individual identity and communal identity. It emphasizes the importance of Muslims maintaining their distinct cultural and religious identity while also urging them not to lose sight of their shared humanity and their universal connection. It encourages individuals to have the freedom to express themselves without compromising the communal values and the need for tolerance and mutual respect. The text recognizes the importance of belonging to a group, but also stresses that individual agency should not be suppressed. It highlights that the group identity should be one of peace and progress and not one of hatred and conflict. A person should be able to be both Muslim and a citizen of the world and to contribute to society at large while maintaining their values.
    13. What is the significance of references to historical figures and events in the text?
    14. Historical figures like Prophet Muhammad, Moses, and Mughal emperors, and historical events such as the Hijra, Mecca’s history, are used to illustrate key arguments. These references serve several purposes. They provide a sense of historical context, grounding the current struggles in a longer narrative. They also offer examples of how Muslims have navigated difficult times in the past, emphasizing the endurance of their faith. By comparing current events to historical precedent, the author seems to encourage a thoughtful approach to resolving the internal and external issues Muslims face. By using both shared Islamic figures and examples from other groups, the text is stressing both the uniqueness of Islamic experience and the importance of a broader, human history. The text seems to be invoking historical references as a means of both grounding Muslims in their tradition while also encouraging adaptability and universalism.
    15. What overall message does the text seem to be trying to convey?
    16. The text conveys a message calling for a renewed understanding of Muslim identity rooted in both cultural heritage and universal human values. It advocates for a path that embraces tradition while also engaging with the modern world, emphasizing the importance of tolerance, compassion, and unity. It calls for Muslims to address their internal conflicts, to overcome their fears, and to recognize their shared humanity with all people. The text encourages a dynamic approach to faith that promotes a deep and thoughtful engagement with the world rather than a retreat into narrow and divisive identities. It also stresses that faith should serve humanity and lead to constructive actions. The message is one of hope and progress and not division and hatred.

    Islamic Identity in a Changing World

    Okay, here is a timeline of events and a cast of characters based on the provided text, which is quite dense and at times, difficult to parse due to its unusual phrasing and structure. I have done my best to extract what seems to be the most relevant information.

    Timeline of Main Events:

    • Early Period (Implied, not explicitly dated):
    • References to historical figures and events such as:
    • Biblical figures: Moses and Israel
    • Greek and Egyptian deities, and Hindu scriptures (Geeta and Vedas).
    • Mecca and the idols Latnath and Hubble.
    • The Prophet Moses and Medina
    • The Prophet of Mecca
    • Discussion of the concept of racial gods and goddesses.
    • Mention of early Islamic figures and practices, including the Hijra.
    • Debate about the call to prayer (adhan).
    • The establishment of a new “Tariq Tanzeem Yajmat” with a separate identity.
    • The Prophet Muhammad’s time in Medina and his interactions with the community.
    • Later Period (Also implied, but more recent, with contemporary references):
    • Concerns about the identity of Muslims in the modern world.
    • Fears about the oppression and marginalization of Muslims in various places.
    • Mention of India and Pakistan, suggesting a post-partition context.
    • References to Kashmir, Chechnya and Bosnia.
    • Mention of Afghanistan
    • Anxiety regarding the loss of Islamic culture and identity among Muslim youth in Western countries.
    • Concern about the influence of Western culture and materialism on Muslim communities.
    • Discussion of conflicts in the world and debates about terrorism.
    • References to contemporary issues such as national identity, and the need for unity within the Muslim community.
    • Debate about the relationship between Islam and politics.
    • Arguments for a balance between maintaining religious identity and engaging with broader society.
    • Discussions about the nature of humanity and tolerance.
    • The notion of God’s family and all humans as children of God.

    Cast of Characters and Brief Bios:

    • Afzal Rehan Azam: Mentioned in the opening as someone whose impact is described as an “Islamic poem”. The tone suggests a figure respected within the community.
    • Mother Respected Doctor Khalid Masood: A mother held in high regard because of her poverty, contrasting with the respect accorded to religious figures like Maulvi Mir Hasan.
    • Maulvi Mir Hasan: A religious figure whose actions are deemed “haram” (forbidden) by the author, who sees the actions of Mother Respected Doctor Khalid Masood as more virtuous
    • Kaushal: Someone who brings “sushimara of the hand of Allah.” Mentioned also as being Gujarati.
    • Darvesh: A person grateful to “doctor sahib” (possibly Dr. Khalid Masood) for an opportunity to see Nasir in the Vedas.
    • Nasir: Someone who Darvesh is grateful to have had the opportunity to see in the Vedas.
    • Qibla (doctor sahib): A respected figure who states that Muslims are Islamic by his reference and who is treated with great respect
    • Gupta Nazar: An unspecified popular topic associated with the “Nazar doctor.”
    • Evelyn Mukadhin Sardarni Qureshi: A woman who is named as going to Mecca with someone else who is trying to face his “Tashkush”. In the text, there is also mention of her authorization of the freedom of religion.
    • Prophet Moses: A key religious figure from the Bible, often mentioned in comparison to the Prophet Muhammad.
    • Prophet Muhammad: The central figure of Islam, referred to frequently in various contexts and situations.
    • Umar Farooq: A well-read friend of the author whose learning inspires him.
    • Ikhthar: Someone who is described as being afraid.
    • Fahd: A person linked with having an opportunity for insurance.
    • Syed: A person who claims to be on a mission to kill a member of “Bani Saleel.” Also linked to Medina under the Seerat of Musa.
    • Pol Rasool: A person who opened the opinion of recognizing “Kalam of Dawat”.
    • Nawab of Ruhal Kuchh: A person that Pol Rasool has a mission to make.
    • Ibrahim: A relative of the author through a relation company, who is also described as an brother of Moses Arun and Mohammed.
    • Moses Arun: Brother of the author through a relation company, who is also described as a brother of Ibrahim and Mohammed.
    • Mohammed (Shakas): Brother of the author through a relation company, who is also described as a brother of Ibrahim and Moses Arun.
    • Salamat Sheikh: Someone who should not say bad things, although the minority has its own Muslims in the Jamiat.
    • Manro of the Masajat: The symbol of the Muslim identity, which people begin to worry about its “blurred weakness”
    • Chandravesh: Someone who is called “Malik Nimki Kashish”.
    • Siddhartha: Possibly refers to Siddhartha Gautama (Buddha), with an implication that there is an analogy between the Siddhartha treaty and terrorism.
    • Bin Safia and the tribes: Group that is described as powerful Turks and that the Americans have kept the Muslims at bay from.
    • Ras Mufti’s mother: A woman whose vision and action are enjoyed by Muslims.
    • Nazia: Someone whose invitation should be used to attack the whole world,
    • Rasul: Someone whose belief in the “pure” is what is desired by the narrator.
    • John: Someone who is not being allowed to “sit below anyone”
    • Didi: A person in the text who has “ground under”, that others want to put pressure on and destroy.
    • Purvanchal: Place that has a universal identity.
    • Karan: Person with a type of salty phobia (group phobia).
    • Tahir Raj Tarana: A person who tells about the news that has been taken from Sari to Magra.
    • Sandeep and Babli: People who should not consider themselves higher than others.
    • Hazrat: Someone that the text complains has become three times more popular in society.
    • Taskin: A person who is described as “humble” with a beneficial identity in the world, with their opinion about Congress being proven wrong.
    • Comyat/Shariat: Concepts linked to the foundations of Allah.
    • Komal Surya Hashmi: Person described as special who has kept the scope of different political hopes with reference to Pakistan. Also described as a nachadi foundation.
    • Harshad: Person whose caste is being used as a personal matter.
    • Ashrafiya: An establishment that meant a different country and was refused to adopt the political community.
    • Musa: A prophet who is the subject of debate regarding what has been said under the “Seerat” of Medina.
    • Abu Rera: Described as a Comrade who is surprised by the format that the officer has.
    • Ahmed Unnao: Person associated with immense emotions and having his “challan registered” in his name.
    • Saknath: Someone for whom emotions should be felt.
    • Aladdin: People who may not be the best representatives of the world’s mosques.

    Note:

    The text is very dense and uses a unique style, making it difficult to ascertain precise meanings or definite connections between events and people. The timeline and bios are based on the most plausible interpretations of the text. The text appears to be a combination of historical references, personal reflections, and social commentary, with a strong focus on Muslim identity in the modern world. The author seems to grapple with issues of religious purity, cultural preservation, and the political realities faced by Muslim communities.

    Let me know if you have any further questions.

    Muslim Identity: A Multifaceted Exploration

    Muslim identity is discussed from various angles in the sources, encompassing religious, cultural, and political aspects, as well as the challenges and fears faced by Muslims in different contexts [1-5].

    Religious Identity:

    • The sources touch on the core beliefs of Islam, including the concept of one God and the importance of the Quran [1, 6, 7].
    • There’s a focus on the figure of the Prophet Muhammad and his teachings [2, 6, 7].
    • The sources also discuss the significance of practices like prayer (Namaz), fasting during Moharram, and the call to prayer from the mosque [1, 6, 7].
    • Some sources contrast the idea of a universal Islamic identity with specific cultural and ethnic expressions of Islam [1, 2, 4].

    Cultural Identity:

    • Muslim identity is sometimes expressed through cultural symbols such as dress and beards [3].
    • There are references to Muslim civilization and its contributions to the world [5].
    • The sources also show how Muslim identity can be tied to specific places, such as Mecca and Medina, or to particular historical figures and events [6, 7].

    Political Identity:

    • The sources describe a tension between religious identity and political realities [2-4, 8].
    • There’s a discussion of the challenges faced by Muslims as minorities in various countries, including fear of oppression [2, 3].
    • The text also mentions how Muslims are impacted by political conflicts and power dynamics [3, 4].
    • Some sources argue for the importance of Muslim unity and solidarity in the face of adversity and injustice [4, 9].

    Challenges and Fears:

    • The sources highlight the anxieties and fears of Muslims in various parts of the world, including India [2, 5].
    • There are concerns about the erosion of Muslim identity and culture in the face of global influences [3, 5].
    • Some sources mention the issue of Islamophobia and the misrepresentation of Muslims in the media [3, 5].
    • The texts also discuss how Muslims grapple with internal conflicts and differences within the community [2, 3, 5].

    Diverse Perspectives:

    • It is noted that Muslims have diverse opinions and that not all Muslims share the same agenda or viewpoints [2, 3].
    • There is an acknowledgement of different interpretations of Islamic teachings and practices [1, 6, 7].
    • Some sources suggest that Muslims should focus on their own welfare without harming others [3].
    • The sources also convey the idea that Muslim identity can be shaped by both religious principles and political circumstances [4, 8].

    Internal Conflicts:

    • There are references to internal divisions within the Muslim community, including the conflict between Sunnis and Shias, as well as the tensions between different cultural and ethnic groups [1, 3, 10].

    Universality:

    • The sources also express an idea of a universal human identity, where all people are considered children of God, regardless of their religion or background. [9]
    • Some sources argue that Muslims should focus on common goals with other people [9, 10].

    The sources emphasize that Muslim identity is a complex and multifaceted concept, influenced by religion, culture, politics, history, and personal experience [1-11].

    Religious Tolerance: Ideals and Challenges

    Religious tolerance is discussed in the sources, with varied perspectives on its practice and importance.

    Acceptance of other faiths:

    • One source describes a historical instance where the religious and ideological freedom of Prophet Islam and his followers was accepted, including the right to choose a new religion [1].
    • The sources also mention a concept that all human beings are children of God and worthy of respect [2]. This implies a universalistic view that values all people, irrespective of their faith.
    • There is also a statement that any thing related to goodness or courage is something that Muslims should embrace, wherever it is found, suggesting a tolerance towards other cultures and traditions [2].

    Challenges to religious tolerance:

    • Some sources mention the fear and anxiety of Muslims in the face of oppression [3], which can be a barrier to tolerance between groups.
    • There are references to a “strict religious fanatics” [3], which suggests that some individuals and groups are not tolerant of other faiths.
    • The sources note that some groups believe that other marriages apart from their own are “infidels” [4]. This indicates a lack of tolerance for those outside of their own group.
    • The sources also mention the existence of a group phobia, which also relates to a lack of acceptance of those outside one’s group [5].
    • Some sources note the desire of some to impose their religious views [4], which is contrary to the idea of tolerance.
    • There is also mention of hatred and doubt, which can be barriers to religious tolerance [3].
    • Some sources express concern about the loss of Islamic culture and identity in the face of outside influences, suggesting a possible struggle with tolerating differing cultural and religious norms [5].

    Arguments for religious tolerance:

    • One source suggests that Muslims should focus on their own welfare without harming others [6]. This suggests a principle of non-interference in the affairs of other religious groups.
    • The sources indicate that the purpose of religion is to invite humanity towards unity and brotherhood [7], which suggests that tolerance is essential to the proper practice of religion.
    • There is the idea that one should not hate the children or family members of someone that one loves, suggesting that tolerance should extend to those of other faiths [2].
    • One source indicates that the fight of Muslims should not be against the bad festivals of other groups [1].
    • Some sources express that the “whole world is God’s family” and one should love all of God’s people, suggesting that religious tolerance is a key principle [2].
    • It is argued that, by freeing themselves from the “shackles of slavery”, people can adopt the thinking of human welfare [2].
    • There is also a suggestion that the preachers of unity have raised their voices against those who have turned their back on humanity and fought against them [2].

    Internal divisions:

    • The sources also discuss internal divisions within the Muslim community [5, 6], which are not necessarily related to religious tolerance, but do reflect a lack of acceptance of different views and beliefs within their own group.

    In conclusion, the sources reveal a complex picture of religious tolerance. While they provide examples and arguments for acceptance, they also highlight the challenges and barriers to achieving it. The sources suggest that religious tolerance is both an ideal to strive for and a practical necessity for building a peaceful and harmonious world.

    Muslim Cultural Preservation in a Changing World

    Cultural preservation is discussed in the sources, mainly in the context of Muslim identity and the challenges it faces in a changing world. The sources reveal a concern for maintaining cultural traditions and values in the face of both internal and external pressures [1].

    Key aspects of cultural preservation discussed in the sources:

    • Maintaining Identity: The sources show that there is a strong desire to maintain a distinct cultural identity [1-3]. This includes things like religious practices, traditions, and values that are unique to Muslim culture [1]. There is a fear that the loss of cultural identity will lead to a loss of distinctiveness [4, 5].
    • Resistance to Change: Some of the sources suggest that some Muslims are resistant to change and want to preserve their traditions [1, 4]. This resistance may be driven by a fear of losing their identity, or by a desire to maintain their unique way of life [4]. The sources mention concern about the influence of Western cultures and a desire to prevent their children from adopting non-Islamic lifestyles [1].
    • Cultural Symbols: Cultural preservation also involves maintaining cultural symbols, such as dress and beards [5]. The sources note that these symbols can be very important to people’s sense of identity and their desire to be part of a community [5].
    • Transmission to Future Generations: The sources express concern over the fact that some Muslim children are growing up in western countries and may not be adopting traditional Islamic culture [1]. There is a feeling of pain when it seems that Islamic culture is not getting the status it deserves [1].
    • Balancing Tradition and Modernity: The sources suggest that there is a tension between the desire to preserve traditional culture and the need to adapt to modern life [2, 4-6]. Some sources suggest that Muslims should focus on their own welfare without harming others [5, 7]. There is also a recognition that one must keep the best in the need of society [8].
    • Internal Diversity: It is important to note that the sources suggest that there are diverse opinions within the Muslim community regarding cultural preservation [1, 4, 5, 7]. Some may believe that preserving traditional culture is essential, while others may see a need for change and adaptation [4, 7]. There are references to the problems that stem from “strict religious fanatics” [4].
    • Universality vs. Specificity: While there is a desire to preserve Muslim identity, there are also ideas about universal values and the idea that all people are children of God [7]. Some sources suggest that Muslims should focus on common goals with other people [7].
    • Fear of Loss: The sources highlight the fear of losing their Maxus [5], a fear that can drive cultural preservation efforts. There is a fear of the end of their story and a blurred weakness [5]. This fear may be a result of living in areas with non-Muslim majorities or feeling that their culture is under attack by the outside world [4].

    In summary, the sources suggest that cultural preservation is a complex issue for Muslims, involving a desire to maintain their unique identity, transmit their values and traditions to future generations, and adapt to the challenges of a changing world. The sources underscore the tension between tradition and modernity, and the need for Muslims to navigate these challenges while staying true to their core values.

    Muslim Political Identity: A Global Perspective

    Political identity is a recurring theme in the sources, often intertwined with religious and cultural identity. The sources reveal a complex picture of how Muslims navigate the political landscape, both within their communities and in relation to the wider world.

    Key aspects of political identity discussed in the sources:

    • Minority Status and Fear: The sources emphasize that Muslims often live as minorities in various countries [1, 2]. This minority status is associated with a pervasive fear of oppression, anxiety, and confusion [1]. There is a sense that Muslims are constantly under threat and need to be vigilant in protecting their rights and interests [1, 3]. The sources also highlight the fear of the Hindu majority in Pakistan and the oppression of Muslims by other groups in the world [1].
    • Political Participation and Representation: The sources touch on the issue of Muslim political participation and representation in various contexts [2]. There is a sense that Muslims are often marginalized and excluded from political power [2]. The sources suggest that some Muslims feel they are not treated as loyal citizens in their countries [2]. However, some sources note that Muslims are achieving their goals in non-Muslim states through the politics of their cities [2].
    • The Desire for a Separate Political Identity: Some of the sources suggest that there is a desire among some Muslims for a separate and independent political state [2, 4]. This desire is often rooted in a sense of religious and cultural distinctiveness, as well as a desire to be free from oppression and persecution. This desire is tied to the idea that Muslims should have their own political community, or Ummah [4]. The sources mention that some Muslims had declared their political community, which was not only for Muslims but also for Hindus [2].
    • Political Strategy: The sources present the idea that Muslims may adopt different political strategies to achieve their goals [4]. Some may focus on working within existing political systems, while others may advocate for more radical forms of political action. For example, some Muslims may try to establish their own political organizations, while others may try to influence the policies of existing governments [2]. The sources mention that some Muslims are involved in debates about how to call people to the mosque and how to maintain their identity [5].
    • Impact of Geopolitics: The sources discuss the impact of global political dynamics on Muslim identity [6]. For example, they note that the actions of powerful countries such as the US in Afghanistan have a direct effect on the Muslim population [3]. The sources describe how some Muslims see the world as a battleground between different powers, with Muslims caught in the middle [6, 7]. The sources also discuss the impact of propaganda and media on how Muslims are perceived and how they see themselves [6].
    • The Tension Between Religious and Political Goals: The sources highlight the tension between religious and political goals [2]. There is a question of whether Muslims should focus primarily on their religious identity or whether they should engage in political action to advance their interests [2]. There is also a discussion of whether political aims should be prioritized over religious principles, and how Muslims should balance these two goals. Some sources suggest that Muslims should focus on their own welfare without harming others, while others argue that they need to fight for justice and liberation [3].
    • Internal Conflicts: The sources reveal internal divisions within the Muslim community [1]. These divisions can affect their political identity. For example, some Muslims may prioritize loyalty to their country, while others may identify more strongly with their religious community. There is a concern that some Muslims are so worried about their own community that they neglect the welfare of others [3].

    The Sources suggest that Muslim political identity is complex and multifaceted, shaped by a number of factors. These include religious beliefs, cultural values, historical experiences, and current political realities. The sources reveal the challenges that Muslims face in navigating these complexities, both within their communities and in the wider world. The sources also indicate that Muslims must balance their desire for religious and cultural preservation with the need to engage effectively in the political sphere.

    In conclusion, the sources reveal that political identity is a key concern for Muslims around the world, and is inextricably linked to their religious, cultural, and social identities. The sources emphasize that this political identity is not static or monolithic, but is rather a dynamic and contested space that is shaped by a variety of factors.

    Global Islam: Identity, Challenges, and Transformation

    Global Islam is discussed throughout the sources, though not always explicitly, and often as it relates to identity, tolerance, cultural preservation, and political action. The sources present a complex picture of a diverse global community with shared beliefs and values that is also facing a variety of challenges.

    Key aspects of Global Islam discussed in the sources:

    • Shared Religious Beliefs and Practices: The sources suggest a common foundation of Islamic beliefs and practices that unite Muslims worldwide. References to the Quran, the Prophet Muhammad, and practices such as prayer indicate a shared religious framework [1-3]. The sources also indicate a shared history and a common heritage, referencing historical figures and events [2].
    • Global Community (Ummah): The sources suggest a concept of a global Muslim community (Ummah) that transcends national boundaries [4]. This is reflected in statements about the unity of Muslims, the idea that all Muslims are brothers and sisters, and that they should support each other [5]. The sources reveal that some Muslims prioritize loyalty to their religious community over their national identity [6].
    • Cultural Identity: The sources describe a desire to preserve a distinct Muslim cultural identity, which is felt by Muslims all over the world [7, 8]. The sources express concern that the Muslim culture is not getting the status it deserves and that this culture is being lost to outside influences [8]. The sources also describe a desire to maintain cultural symbols such as dress and beards [7].
    • Minority Status and Challenges: The sources reveal that Muslims often live as minorities in various countries. This minority status is associated with a fear of oppression, anxiety, and confusion [9]. The sources highlight the fear of the Hindu majority in Pakistan and the oppression of Muslims by other groups in the world [6, 9]. They also express concern about the loss of Islamic culture and identity in the face of outside influences [8].
    • Political Engagement: The sources discuss how Muslims engage with the political landscape in various contexts. There is a sense that Muslims are often marginalized and excluded from political power [6]. Some Muslims may focus on working within existing political systems, while others may advocate for more radical forms of political action [4].
    • Internal Divisions: The sources acknowledge the existence of internal divisions within the Muslim community [1, 9]. These divisions can be based on differences in religious interpretation, political views, or cultural practices. This implies a lack of a monolithic global Muslim identity, and suggests a range of different perspectives within the community.
    • Tension Between Tradition and Modernity: The sources highlight a tension between the desire to preserve traditional culture and the need to adapt to modern life [8]. Some Muslims may be resistant to change and want to maintain their unique way of life, while others may see a need for change and adaptation [7]. The sources suggest a need to balance these two needs [4, 8].
    • Impact of Geopolitics: The sources discuss the impact of global political dynamics on Muslim identity [7]. Actions of powerful countries such as the US in Afghanistan have a direct effect on Muslim populations [7]. The sources describe how some Muslims see the world as a battleground between different powers, with Muslims caught in the middle [10].
    • Universal Values: Despite the focus on a distinct Muslim identity, the sources also express universal values, such as the idea that all people are children of God and are worthy of respect [5, 11]. This suggests a tension between a particular religious identity and a shared humanity. The sources indicate that the purpose of religion is to invite humanity towards unity and brotherhood, suggesting that tolerance is essential to the proper practice of religion [5].
    • Fear and Anxiety: The sources indicate that Muslims around the world are facing an increase in fear, anxiety, and confusion [7-9]. This may be due to increased discrimination, political unrest, and cultural misunderstandings. The sources suggest that this anxiety is felt by Muslims both in Muslim and non-Muslim majority countries [9].

    In conclusion, the sources portray Global Islam as a complex and multifaceted phenomenon. It is characterized by a shared religious foundation and a sense of community that transcends national boundaries. At the same time, the global Muslim community is diverse, faces many challenges, and is constantly evolving in response to changing social, political, and cultural realities. The sources suggest that Global Islam is both a unifying force and a site of internal tension, a dynamic space where Muslims navigate complex issues of identity, belonging, and the search for meaning in an increasingly interconnected world.

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • Al Riyadh Newspaper, March 5, 2025 Foreign Relations, Aid to Lebanon, Global Economic Concerns

    Al Riyadh Newspaper, March 5, 2025 Foreign Relations, Aid to Lebanon, Global Economic Concerns

    These articles from the Al Riyadh newspaper cover a range of topics including Saudi Arabia’s foreign relations and aid to Lebanon, its steadfast support for Palestine, and Crown Prince Mohammed bin Salman’s diplomatic activities. They also report on global economic concerns affecting stock markets and OPEC+ oil production, alongside domestic Saudi news such as the King Salman Prize for Quran حفظ, Ramadan استقبالات, and development projects. Additionally, the paper features local community initiatives during Ramadan, sports news covering football leagues and international competitions, and health and cultural events, providing a diverse snapshot of current affairs.

    Study Guide: Analysis of Al-Riyadh Newspaper Excerpts (March 5, 2025)

    Overview of Key Themes

    The provided excerpts from the Al-Riyadh newspaper published on Wednesday, March 5, 2025 (Rabi’ al-Awwal 15, 1446 AH) cover a range of domestic, regional, and international news and commentary relevant to Saudi Arabia. Key themes include:

    • Domestic Governance and Policy: Statements from the Crown Prince regarding the Kingdom’s commitment to serving pilgrims and supporting social services, cabinet approvals for initiatives like investment promotion and heritage mosque restoration, and regional development projects.
    • Foreign Policy and Regional Relations: Saudi Arabia’s stance on the Palestinian issue, its role in supporting Lebanon, its participation in Arab summits, and its perspective on the Sudanese conflict.
    • Economic News: Fluctuations in gold prices, a decrease in used car prices in Saudi Arabia, stable vegetable and fruit prices during Ramadan, and financial results of Saudi Aramco.
    • Social and Religious Affairs: Preparations for Ramadan in the Two Holy Mosques, initiatives to provide services to pilgrims, Ramadan-related social customs (collective Iftar), and the King Salman Award for memorizing the Quran.
    • Cultural and Heritage Preservation: The unveiling of the Islamic Arts Biennale in Jeddah showcasing historical artifacts, and the ongoing project to restore historical mosques.
    • International Issues: The ongoing conflict in Gaza, the humanitarian crisis and sexual violence in Sudan, and international economic developments like US-China trade tensions.
    • Health and Social Initiatives: Health awareness campaigns during Ramadan.
    • Commentary and Opinion: An article on the importance of sustainable social solidarity beyond seasonal charity.

    Key Concepts and Topics to Review

    • Saudi Arabia’s Vision 2030: Understand how the reported initiatives and policies align with the Kingdom’s long-term goals.
    • The Role of the Crown Prince and Council of Ministers: Recognize their functions in setting national priorities and approving policies.
    • Saudi Arabia’s Foreign Policy Principles: Identify the consistent themes in its approach to regional conflicts and international issues (e.g., support for Palestine, territorial integrity of nations, peaceful resolutions).
    • The Significance of the Two Holy Mosques: Understand the continuous efforts to enhance services and facilities for pilgrims, especially during peak seasons like Ramadan.
    • Economic Indicators: Note the trends in key sectors like automotive and commodities.
    • Cultural Preservation Efforts: Appreciate the initiatives aimed at safeguarding Saudi Arabia’s Islamic and national heritage.
    • The Impact of Regional Conflicts: Analyze Saudi Arabia’s involvement and stated positions on conflicts in Palestine, Lebanon, and Sudan.
    • The Importance of Ramadan: Recognize its significance in religious, social, and economic contexts within Saudi Arabia.
    • Humanitarian Issues: Understand the Kingdom’s response and concerns regarding humanitarian crises in the region.

    Quiz: Short-Answer Questions

    1. According to the Crown Prince’s statement, what are the two key areas the Saudi Arabian government remains committed to supporting?
    2. What was the main concern expressed by the Saudi Council of Ministers regarding the situation in the Palestinian territories? What did they urge the international community to do?
    3. What kind of aid has Saudi Arabia been providing to Lebanon, and what is the overarching vision for the relationship between the two countries?
    4. What was the key message delivered by the Saudi Minister of Foreign Affairs at the extraordinary Arab Summit held in Egypt?
    5. What are the primary factors contributing to the recent decrease in the prices of used cars in Saudi Arabia?
    6. Describe two specific initiatives undertaken in the Two Holy Mosques to enhance the experience of pilgrims during Ramadan.
    7. What is the objective of the project to develop historical mosques in Saudi Arabia, and what are some of the features being preserved?
    8. What is the “Peace Arab Initiative” mentioned in the context of Saudi Arabia’s policy towards the Palestinian issue, and when was it adopted?
    9. What is Saudi Arabia’s stated position regarding the ongoing conflict in Sudan, as reflected in the Foreign Ministry’s statement?
    10. What is the main argument presented in the opinion piece regarding social solidarity during Ramadan and beyond?

    Quiz Answer Key

    1. The Crown Prince stated the Saudi Arabian government remains committed to serving the guests of God (pilgrims) and continuing to support the system of social services.
    2. The Council expressed strong condemnation of the Israeli government’s decision to prevent the entry of humanitarian aid into the Gaza Strip. They urged the international community to uphold its responsibilities, activate international accountability mechanisms, and ensure sustained aid access.
    3. Saudi Arabia has been sending humanitarian aid to Lebanon via an air bridge, including food, relief, shelter, and medical supplies. The vision for the future is a “partnership era” with strengthened Arab relations, with the joint Saudi-Lebanese statement emphasizing cooperation on important issues.
    4. The Minister of Foreign Affairs, representing the Crown Prince, conveyed the greetings of the Custodian of the Two Holy Mosques and reiterated Saudi Arabia’s unwavering support for the Palestinian people’s right to establish their independent state on the 1967 borders with East Jerusalem as its capital.
    5. The primary factors include an increase in the supply of used cars in the market due to the availability of new models and regulatory measures taken by the Ministry of Commerce that helped to lower prices. Additionally, allowing the import of used cars has increased competition.
    6. Two initiatives include the experimental launch of “Al-Tahallul from Nusuk” service using mobile carts within the Haram to serve pilgrims and the development of a baggage storage service with electronic tracking and six designated locations.
    7. The objective is to rehabilitate and restore historical mosques for worship and prayer, preserving their original architectural authenticity and highlighting their cultural and historical dimension for the Kingdom. Features being preserved include the traditional Najdi architectural style, such as roofs made of mud, wood, and palm fronds.
    8. The “Peace Arab Initiative” is a vision presented by Saudi Arabia at the Beirut Arab Summit in March 2002, which was adopted by Arab leaders. It aims for a comprehensive and just peace in the Middle East.
    9. Saudi Arabia expressed its rejection of any illegitimate steps or measures taken outside the framework of Sudan’s official institutions that could undermine its unity or disregard the will of its people, including calls for forming a parallel government. It reiterated its support for Sudan’s security, stability, and territorial integrity and called on Sudanese parties to prioritize Sudan’s interests.
    10. The opinion piece argues that social solidarity should extend beyond seasonal charity during Ramadan to become a sustainable effort focused on empowering those in need, providing opportunities, and improving the quality of life through partnerships and initiatives that create lasting impact.

    Essay Format Questions

    1. Analyze the interconnectedness between Saudi Arabia’s domestic policies (as reflected in the cabinet decisions and development projects mentioned) and its regional foreign policy objectives in the Middle East.
    2. Discuss the multifaceted significance of Ramadan as portrayed in the newspaper excerpts, considering its religious, social, and economic dimensions within Saudi Arabia.
    3. Evaluate Saudi Arabia’s consistent stance on the Palestinian issue as presented in the excerpts, tracing its historical roots and highlighting the key principles guiding its policy.
    4. Critically assess the various challenges and opportunities facing the Kingdom in its efforts to balance economic development (as suggested by investment initiatives and market trends) with its commitment to social welfare and regional stability.
    5. Examine the role of cultural and heritage preservation initiatives, such as the Islamic Arts Biennale and the restoration of historical mosques, in promoting Saudi Arabia’s national identity and global image.

    Glossary of Key Terms

    • ولي العهد (Wali al-Ahd): The Crown Prince, the designated successor to the King.
    • مجلس الوزراء (Majlis al-Wuzara’): The Council of Ministers, the main executive body of the Saudi Arabian government.
    • ضيوف الرحمن (Duyuf al-Rahman): The guests of God, a term used to refer to pilgrims visiting Mecca and Medina.
    • القدس الشرقية (Al-Quds al-Sharqiya): East Jerusalem, considered by Palestinians as the capital of their future state.
    • قمة عربية غير عادية (Qimma Arabiya Ghair Aadiya): An extraordinary Arab Summit, convened to discuss urgent matters.
    • جسر جوي (Jisr Jawwi): An air bridge, a continuous series of flights to transport aid or personnel.
    • الهيئة السعودية لتسويق االستثمار (Al-Hay’a as-Saudiya li-Taswiq al-Istithmar): The Saudi Authority for Investment Marketing (translated based on context of promoting investment).
    • قمة فلسطين (Qimmat Filastin): The Palestine Summit (name given to an Arab League summit focused on the Palestinian issue).
    • الأونروا (Al-Unrwa): The United Nations Relief and Works Agency for Palestine Refugees in the Near East (UNRWA).
    • مبادرة السلام العربية (Mubadarat as-Salam al-Arabiya): The Arab Peace Initiative, a proposal for ending the Arab-Israeli conflict.
    • الحرمين الشريفين (Al-Haramayn ash-Sharifayn): The Two Holy Mosques, referring to the Grand Mosque in Mecca and the Prophet’s Mosque in Medina.
    • بينالي الفنون الإسلامية (Bienali al-Funun al-Islamiya): The Islamic Arts Biennale, a recurring exhibition of Islamic art.
    • صدقات (Sadaqat): Voluntary charitable giving in Islam.
    • الذوق العام (Al-Dhauq al-A’am): Public decency or etiquette.
    • رؤية المملكة 2030 (Ru’yat al-Mamlaka 2030): The Kingdom’s Vision 2030, a strategic framework to reduce Saudi Arabia’s dependence on oil, diversify its economy, and develop public service sectors.

    Briefing Document: Review of “20706.pdf” (Al Riyadh Newspaper, March 5, 2025)

    This briefing document summarizes the main themes, important ideas, and key facts presented in the provided excerpts from the Al Riyadh newspaper, issue 20706, dated March 5, 2025. The excerpts cover a range of domestic and international news, with a significant focus on Saudi Arabia’s policies, activities, and Ramadan preparations.

    I. Domestic Affairs and Policies:

    • Council of Ministers Meeting: The Council of Ministers, chaired by the Crown Prince Mohammed bin Salman, held a meeting in Riyadh.
    • The Crown Prince conveyed congratulations to Muslims on the arrival of Ramadan, emphasizing the Kingdom’s pride in serving the pilgrims of the Two Holy Mosques.
    • He affirmed the state’s continued support for the social services system aimed at providing suitable housing for eligible families, praising the cooperation between governmental, private, and non-profit sectors.
    • The Council approved the organization of the Saudi Investment Marketing Authority to attract individuals to various regions.
    • Support for “Palestine Summit” Decisions: The Council affirmed its full support for the resolutions of the “Palestine Summit” held in Cairo, which aims to reject the displacement of the Palestinian people and end the catastrophic consequences of the war, emphasizing the Palestinian people’s right to self-determination and the establishment of their independent state on the 1967 borders with East Jerusalem as its capital.
    • Saudi Arabia’s Stance on Palestine: The article highlights Saudi Arabia’s consistent and unwavering support for the Palestinian cause throughout history, starting from the London Conference in 1935. This support spans political, economic, social, and health dimensions, driven by a deep-rooted belief and commitment to the Arab and Islamic nation.
    • The Kingdom has provided financial aid, cared for the families of martyrs, and hosted a large number of Palestinians.
    • The article emphasizes the historical roles of King Abdulaziz, King Faisal (who sought to transform the Palestinian issue into a central Islamic cause), King Khalid, King Abdullah (who presented the first Arab initiative for Palestine), and King Fahd (as a political supporter).
    • Crown Prince Mohammed bin Salman reaffirmed that Jerusalem remains in the conscience of the leaders and peoples of Arab and Islamic nations, reiterating the Kingdom’s support until the Palestinian people achieve their legitimate rights and establish their independent state with East Jerusalem as its capital. He stated, “Let the near and the far know that Palestine and its people are in the conscience of Arabs and Muslims.”
    • Saudi Arabia contributed $150 million to the Islamic Endowments program in Jerusalem and $50 million to UNRWA.
    • The Kingdom stresses the necessity of a just and lasting solution to the Palestinian issue based on international legitimacy resolutions and the Arab Peace Initiative, ensuring the Palestinian people’s right to establish an independent state on the 1967 borders with East Jerusalem as its capital.
    • Saudi Arabia’s Ministry of Foreign Affairs stated in February 2025 that the Palestinian people’s right to their land is firm and cannot be taken away, emphasizing that lasting peace will only be achieved by returning to the logic of reason and accepting the principle of equal rights and human dignity.
    • Saudi Arabia ranks as a leading donor country to the Palestinian people, with total aid reaching $5,358,848,461 through 295 projects across various sectors.
    • Support for Lebanon: Despite regional political tensions, Saudi Arabia has maintained a strong presence and launched an airlift of humanitarian aid to support the Lebanese people facing ongoing challenges. Twenty-seven planes carrying relief supplies, including food, shelter, and medical materials, were dispatched.
    • The article suggests a new era of partnership with Lebanon, aiming to strengthen Arab relations, as reflected in the joint Saudi-Lebanese statement issued at the end of the Lebanese President’s visit, which emphasized the importance of enhancing joint Arab action and coordinating stances on key issues of the Arab and Islamic nation.
    • The Council of Ministers noted the joint statement between the Kingdom and Lebanon, emphasizing the importance of fully implementing the Taif Agreement regarding weapons and the state’s sovereignty over all its territories, and stressing the role of the Lebanese national army. It also reiterated the necessity of the Israeli occupation army’s withdrawal from all Lebanese territories.
    • Amir of Riyadh on King Salman Award for Quran Memorization: The Amir of Riyadh highlighted the significance of the King Salman bin Abdulaziz Award for Memorizing the Holy Quran in its content, methodology, and implementation.
    • Amir of Al-Qassim on Water Project: The Amir of Al-Qassim expressed gratitude for the approval of the Jubail-Buraidah water pipeline project, costing 8.5 billion riyals, noting its strategic importance in enhancing water security and supporting sustainable development in the region, aligning with Vision 2030. He praised the collaboration of various ministries and entities in executing the project according to the highest technical and engineering standards.
    • Development of Historical Mosques: The second phase of the Prince Mohammed bin Salman Project for the Development of Historical Mosques has been launched, aiming to preserve their architectural authenticity, restore them for worship and prayer, and highlight their religious and cultural significance. The first phase, launched in 2018, included the rehabilitation of 30 historical mosques in 10 regions.
    • Civil Defense Preparations for Ramadan: The Civil Defense in Makkah and Madinah has intensified its preventive supervision in the central area, accommodation facilities, and vital installations of the Two Holy Mosques to ensure the readiness of fire prevention and protection systems during Ramadan, aiming for the highest standards of readiness to serve pilgrims.
    • Comprehensive Operational System in the Two Holy Mosques: The General Authority for the Care of the Affairs of the Grand Mosque and the Prophet’s Mosque has completed its preparations to receive Ramadan 1446 AH, with a comprehensive operational system focused on managing assets, maintenance, enhancing the pilgrim experience, and coordinating with relevant entities to provide an integrated experience for Umrah performers and worshippers. This includes new services like mobile disinfection units, baggage storage development, increased electric golf carts, and improved I’tikaf experience.
    • Distribution of Iftar Meals in the Prophet’s Mosque: Approximately 227,000 Iftar meals are distributed daily in the Prophet’s Mosque during Ramadan.
    • Decline in Used Car Prices: Saudi Arabia has witnessed a 6% decrease in used car prices, marking the fifth consecutive monthly decline after previous significant increases. This is attributed to increased supply due to the availability of new models, regulatory measures by the Ministry of Commerce, and the opening of used car imports, enhancing competition. Car auctions have also played a significant role in lowering prices.
    • Increased Demand for Vegetables and Fruits in Ramadan: Traders expect a 65% increase in demand for fruits and vegetables during Ramadan, with stable prices due to a balance between supply and demand. They express confidence in the strength of the Saudi economy and the leadership’s vision, attracting suppliers. The Ministry of Environment, Water and Agriculture continues its plans to increase local production, aiming for self-sufficiency in line with Vision 2030.
    • Importance of Sustainable Social Solidarity in Ramadan: An article emphasizes that Ramadan is a season for social solidarity and helping the needy. However, it stresses the need to move beyond temporary seasonal aid towards creating sustainable impact through initiatives that empower individuals and improve quality of life through partnerships. Saudi companies are recognizing this shift.
    • Riyadh Season’s Ramadan Activities: Historic Jeddah is hosting “Ramadan 2025 Season” events, organized by the Historic Jeddah Program under the Ministry of Culture, aiming to revive cultural heritage, strengthen national identity, and offer visitors a unique experience throughout the holy month with diverse cultural and community activities.
    • Saudi Students’ Club in Liverpool Celebrates Founding Day: The Saudi Students’ Club in Liverpool held an event to commemorate the anniversary of the Kingdom’s founding.
    • Biannual Islamic Arts Exhibition: The Biannual Islamic Arts Exhibition in Jeddah is presenting unique artifacts and scenes under the theme “What is Between Them,” showcasing the history of Islamic arts, both ancient and contemporary. Notable exhibits include the “Dome Structure” previously used to preserve the Maqam Ibrahim.
    • Documenting Cultural Sites: The Ministry of Culture has documented historical sites associated with renowned Arab poets throughout the Kingdom, connecting the past with the present through informational signs.
    • “Riyadh Market as Seen by Belinken in 1947”: An article reflects on the depiction of the Riyadh market in 1947 by the British traveler Belinken, as part of tracing popular heritage in Western travelers’ accounts.
    • Ramadan Atmosphere in Mosques: A poem evokes the spiritual atmosphere of mosques in Riyadh during the nights and days of Ramadan.
    • National Awareness Campaign for Early Detection of Diseases: The Riyadh Health Cluster, in cooperation with the Health Holding Company, launched a national awareness campaign titled “Safety in Health” at the Saleh Al-Dossary Center to promote early detection and healthy lifestyles during Ramadan.
    • Saudi Arabian Motorsports Company Project Launch: The Saudi Arabian Motorsports Company, in cooperation with the General Directorate of Passports and the General Authority of Civil Aviation, launched the first phases of the Al-Mazar sports project, aiming to enhance the infrastructure for motorsports in the Kingdom.
    • Traditional Saudi Games: The Ministry of Interior, represented by the General Directorate of Border Guards, in cooperation with the Saudi Arabian Olympic & Paralympic Committee, concluded the first phase of a heritage initiative focusing on traditional Saudi games, considering them a renewed cultural heritage that strengthens national identity and belonging.
    • Ramadan Legacy: An article reflects on the unique spiritual and social atmosphere of Ramadan in Saudi society, emphasizing traditions of unity, generosity, and strengthening community bonds.
    • Community Iftar Gatherings: The article highlights the tradition of community Iftar gatherings in neighborhoods, fostering unity and recalling fond memories during Ramadan, with appreciation for the efforts of local authorities and community centers in supporting these initiatives.

    II. International Affairs:

    • Sudan Crisis: Saudi Arabia reiterates its unwavering support for the unity, safety, stability, and territorial integrity of Sudan, rejecting any illegitimate steps taken outside the framework of official Sudanese institutions that could undermine its unity. The Kingdom calls on Sudanese parties to prioritize Sudan’s interests and avoid division and chaos, reaffirming its commitment to ending the war and achieving peace in accordance with the Jeddah Declaration signed on May 11, 2023.
    • The Ministry of Foreign Affairs statement underscores the importance of continued efforts to halt the conflict and work towards peace, recalling the Jeddah Declaration which outlined commitments by the Sudanese Armed Forces and the Rapid Support Forces to protect civilians and facilitate humanitarian action.
    • Gaza Conflict: The Arab League summit in Cairo adopted an Arab plan for early recovery and reconstruction of Gaza to counter attempts to liquidate the Palestinian issue. The plan urges all types of financial, material, and political support for its implementation and calls on the international community and international and regional financing institutions to provide necessary support.
    • The statement stressed the strategic option of achieving a just, comprehensive, and lasting peace that fulfills all the rights of the Palestinian people, especially their right to freedom and an independent state with sovereignty over their national soil based on the two-state solution, ensuring security for all peoples and states of the region, including Israel.
    • The Arab countries reaffirmed their commitment to resolving all conflicts and disputes in the region peacefully and establishing normal relations and cooperation among all its countries, while firmly rejecting all forms of occupation and aggression.
    • The statement emphasized intensifying cooperation with international and regional powers, including the United States, to achieve a just and comprehensive peace in the Middle East, working to end all conflicts and expressing readiness to engage immediately with the US administration and all international partners to resume peace negotiations aimed at a just settlement of the Palestinian issue, ending the Israeli occupation and establishing the independent and sovereign Palestinian state on the June 4, 1967 borders with East Jerusalem as its capital, living in peace and security alongside Israel, and calling for the convening of an international peace conference.
    • The statement welcomed the Palestinian decision to work on enabling the National Authority to return to the Palestinian territories occupied since 1967, as a embodiment of unity for a transitional period in Gaza. It also valued the proposal from Jordan and Egypt to qualify and train Palestinian cadres to ensure their ability to fully perform their security duties in Gaza, stressing that the security file is a Palestinian responsibility that must be managed by the legitimate Palestinian institutions alone, according to the principle of one law, one authority, and one legitimate weapon, ensuring its continuous stability.
    • The statement highlighted the need to address Israel’s concerns regarding long-term security in Gaza.
    • Conversely, it noted Israeli Prime Minister Netanyahu’s use of withholding aid as leverage to evade the second phase of ceasefire negotiations.
    • The continuation of border closures and prevention of aid entry exacerbates the humanitarian crisis in Gaza, where over two million Palestinians face dire living conditions due to the ongoing Israeli war.
    • Security Campaign in Latakia, Syria: A security campaign was launched in Latakia following the killing of two security personnel in an “armed ambush,” coinciding with alleged Israeli airstrikes on weapons depots in the Qardaha area.
    • UNICEF Report on Sexual Violence in Sudan: UNICEF announced that Sudanese fighters have raped Sudanese civilians, including children as young as one year old, during the ongoing civil war, in what could amount to “war crimes.” The report details harrowing testimonies of survivors and highlights the limited data available, indicating the actual scale of sexual violence is likely much larger. UNICEF calls for an immediate end to this suffering.
    • Alleged “Rapid Support Forces” Bombing in Al-Fashir, Sudan: The “Rapid Support Forces” are accused of shelling a market in Al-Fashir, killing six civilians and injuring an unknown number. The Rapid Support Forces control most of Darfur region and are besieging Al-Fashir, the last major city under the control of the army and allied factions. Famine has spread in areas surrounding Al-Fashir, raising fears it could extend to the city itself.
    • Liverpool vs. Paris Saint-Germain Champions League Match: An article previews the upcoming Champions League Round of 16 first-leg match between Liverpool and Paris Saint-Germain, noting Liverpool’s strong form in the English Premier League and PSG’s dominance in Ligue 1, while highlighting PSG’s less convincing performance in the Champions League group stage.
    • Bayern Munich vs. Bayer Leverkusen Match: An article discusses the upcoming Bayern Munich vs. Bayer Leverkusen match in the Bundesliga, noting Leverkusen’s impressive undefeated run and Bayern’s strong record against Leverkusen at home, predicting a challenging encounter for both teams.
    • Benfica vs. Barcelona Match: Barcelona will visit Benfica, aiming to restore their status as one of the continent’s giants.
    • Al-Hilal Loses to Pakhtakor in AFC Champions League: Al-Hilal lost 2-1 to Pakhtakor of Uzbekistan in the first leg of the AFC Champions League Round of 16, despite taking an early lead.
    • Al-Ahli Closer to AFC Champions League Quarter-Finals: Al-Ahli defeated Qatari side Al-Rayyan 3-1 in the first leg of their AFC Champions League Round of 16 tie, putting them in a strong position to advance.
    • Saudi National Football Team Preparations for World Cup Qualifiers: The Saudi national football team is preparing for a crucial match against China on March 20th in the qualifiers for the 2026 World Cup. The article expresses hope for the team’s success in their quest to qualify for the World Cup for the seventh time in their history.
    • Asian Qualifiers for Under-17s Championship Draw: The draw for the Asian Qualifiers for the Under-17s Championship in January placed Saudi Arabia in Group A along with China, Thailand, and Uzbekistan.

    III. Economic and Financial News:

    • Gold Prices Rise: Gold prices increased due to demand for safe-haven assets amid trade tensions sparked by US President Donald Trump imposing new tariffs on major trading partners. Spot gold rose 0.8% to $2917.61 per ounce, marking the second consecutive session of gains.
    • Gulf Stock Markets Decline: Most Gulf stock markets experienced declines.
    • Saudi Aramco Financial Results: Saudi Aramco announced a net income of 121.3 billion Saudi Riyals (SAR) ($32.3 billion USD) in 2024. The decrease in net income compared to the previous year was attributed to lower revenues due to decreased crude oil prices and refined and chemical product prices, partially offset by higher sales volumes of refined and chemical products.
    • Saudi Aramco’s President and CEO, Amin H. Nasser, stated that the strong net income and dividends reflect the company’s exceptional resilience, ability to capitalize on its unique scale and low-cost production, and reliable delivery to customers and shareholders. He noted that global oil demand reached new highs in 2024 and expects further growth in 2025.
    • The company is progressing with projects aimed at maintaining its maximum sustainable crude oil production capacity and ensuring reliable energy supplies.
    • Saudi Aramco has made progress in its growth strategy across upstream, refining, chemicals, and marketing sectors, with potential additional operating cash flows expected from these expansions by 2030.
    • The company’s spare capacity provides flexibility to meet potential oil demand growth.
    • Chairman of Saudi Aramco’s Board of Directors, Yasser bin Othman Al-Rumayyan, highlighted the strong dividends distributed to shareholders since the IPO and the significant investor interest in Saudi Aramco’s continued growth story through a secondary public offering and issuance of international bonds and sukuk in 2024.
    • Darren Woods of ExxonMobil and Philippe Novac of TotalEnergies on Oil Prices: They commented on the current downward trend in oil prices, attributing it to OPEC+ production increases and US tariffs, along with geopolitical developments related to the Russia-Ukraine conflict.
    • President Trump’s Halt to US Military Aid to Ukraine: This decision, following a disagreement with President Zelensky, and OPEC+’s decision to proceed with planned oil production increases, have influenced oil market dynamics.
    • China’s Response to US Tariffs: Following the implementation of US tariffs, China quickly announced retaliatory import duty increases on a range of US agricultural and food products.
    • Reliance Industries to Resume Activities in India: The Indian company will resume its activities in India from March 5, 2025, after resolving a gas drilling dispute with the Indian government.
    • Trump’s Inspiration from the Saudi Sovereign Wealth Fund: An analysis discusses US President Donald Trump’s stated intention to create a large American sovereign wealth fund, drawing inspiration from the successful Saudi Public Investment Fund (PIF), which is currently ranked among the largest globally. The analysis explores the concept of sovereign wealth funds in the US, noting existing state-level funds, and discusses potential sources of funding and governance structures for a federal fund, emphasizing the need for transparency and independence from political interference.

    IV. Social and Cultural Items:

    • The Value of Water: An article highlights the essential role of water for life, its unique properties, and its abundance in the universe in frozen form, with liquid water being unique to Earth. It emphasizes the human body’s high water content and the intricate system of water on the planet, referencing Quranic verses about the creation of water.
    • Obituary for Moroccan Intellectual Mohammed bin Issa: An obituary commemorates the passing of Mohammed bin Issa, a prominent figure in Moroccan thought, culture, and politics, and the founder of the Asilah Cultural Festival, recognizing his significant contributions and lasting impact.

    V. Health News:

    • Surgical Removal of Pancreatic Tumor: Dr. Mostafa Habib Soliman performed a successful “Whipple” procedure to remove a cancerous hormonal tumor from the pancreas of a patient suffering from severe abdominal pain.
    • The Benefits of Fasting During Ramadan: An article discusses the various health benefits associated with fasting during Ramadan, referencing scientific studies on intermittent fasting and its impact on autophagy, inflammation, insulin sensitivity, weight loss (specifically abdominal fat), and mental well-being through increased serotonin and reduced stress hormones. It also notes potential benefits in reshaping the relationship with food by reducing cravings for sugary items. However, it cautions that prolonged fasting without proper nutrition can lead to adverse effects like dehydration or hypoglycemia, especially for individuals with chronic conditions who require medical supervision.
    • Impact of Ramadan on Sleep: A study from the University of the Emirates found that the quality of sleep improved for participants during Ramadan, likely due to reduced caffeine intake and regulated melatonin secretion.
    • Seizure of Pharmaceutical Products and Fine for Factory: The Saudi Food and Drug Authority (SFDA) reported seizing over 100,000 packages of 29 different unregistered pharmaceutical and nerve medications from a factory in violation of regulations. The factory was fined 1.4 million riyals and referred to the Public Prosecution. The SFDA emphasized the importance of adhering to regulations and called on the public to report violations.

    This briefing document provides a comprehensive overview of the key information presented in the selected excerpts from the Al Riyadh newspaper. It highlights Saudi Arabia’s active role in regional politics, its ongoing domestic development initiatives, preparations for the holy month of Ramadan, and various economic, social, and health-related news items.

    Saudi Arabia: Key Policy Updates and Initiatives

    Frequently Asked Questions

    1. What was the primary focus of the Saudi Council of Ministers’ meeting? The primary focus of the Saudi Council of Ministers’ meeting, chaired by Crown Prince Mohammed bin Salman, was on two key areas: expressing gratitude for the opportunity to serve pilgrims to the Two Holy Mosques during Ramadan and reiterating the Kingdom’s commitment to supporting social services for its citizens. Additionally, the council addressed regional and international matters, including the Palestinian issue, the situation in Lebanon, and international economic developments.
    2. What is Saudi Arabia’s stance on the Palestinian issue, as highlighted in the sources? Saudi Arabia maintains a firm and long-standing supportive stance towards the Palestinian issue. The Kingdom calls for the establishment of an independent Palestinian state based on the 1967 borders, with East Jerusalem as its capital. It strongly condemns the Israeli government’s actions, including the obstruction of humanitarian aid to Gaza, and urges the international community to hold Israel accountable and ensure sustained aid access. Saudi Arabia also emphasizes its support for the Palestinian National Authority in its efforts to govern Gaza and provide essential services. This position is rooted in the Kingdom’s historical and religious commitment to the Palestinian people.
    3. How is Saudi Arabia addressing the situation in Lebanon, according to the provided text? Saudi Arabia is actively engaging with Lebanon to foster a new era of partnership. Despite past political tensions, the Kingdom has sent significant humanitarian aid to Lebanon, including food, shelter, and medical supplies. The joint Saudi-Lebanese statement released after the Lebanese President’s visit underscores the importance of fully implementing the Taif Agreement, ensuring the Lebanese state’s sovereignty and control over its territory (including border control and arms control), and the withdrawal of the Israeli occupation army from all Lebanese territories.
    4. What initiatives are being undertaken to enhance the experience of pilgrims visiting the Two Holy Mosques during Ramadan? Significant efforts are underway to provide a comprehensive and comfortable experience for pilgrims during Ramadan. These include an integrated operational system for managing the Grand Mosque and the Prophet’s Mosque, focusing on maintenance, efficient operations, and enriching the visitor experience. Specific initiatives include the launch of “Tahalul Service” using mobile units for hair shaving (an Umrah ritual), development of a luggage storage service with electronic tracking, increasing the number of electric golf carts for transportation within the mosques, developing manual carts with a unified design, enhancing Itikaf (seclusion) services, improving the electronic booking system for Iftar meals, providing categorized guidance signs, operating centers for children’s hospitality, and offering religious and cultural exhibitions like “First House” which showcases the history of the Kaaba’s construction.
    5. What developments were reported regarding the Saudi economy and specific sectors? Several economic developments were highlighted. The Saudi Council of Ministers approved the organization of the Saudi Investment Marketing Authority. The used car market saw a 6% price decrease due to increased supply and the allowance of used car imports. Conversely, gold prices continued to rise, driven by demand for safe-haven assets amidst international trade tensions. The Saudi stock market generally saw declines, mirroring global trends influenced by factors like potential interest rate cuts and geopolitical concerns.
    6. How is Saudi Arabia preserving and promoting its cultural and historical heritage, as mentioned in the text? Saudi Arabia is actively working to preserve and promote its cultural and historical heritage through various initiatives. The second phase of the Prince Mohammed bin Salman Project for the Development of Historical Mosques has been launched, focusing on restoring and architecturally preserving these significant sites while allowing for non-impactful additions. The Ministry of Culture is also documenting historical locations associated with renowned Arab poets, like the site in Najran where Yaguth bin Abdullah Al-Harthy lived, transforming it into a public park. Additionally, the Islamic Arts Biennale is showcasing rare artifacts and unique displays, such as the former domed structure used to protect the Maqam Ibrahim in Mecca, highlighting the rich history of Islamic art and culture.
    7. What role is Saudi Arabia playing in addressing the ongoing conflict in Sudan? Saudi Arabia is deeply concerned about the situation in Sudan and is actively engaged in efforts to mediate and resolve the conflict. The Kingdom has repeatedly emphasized the importance of Sudan’s unity, safety, stability, and territorial integrity, rejecting any external interference in its internal affairs or the formation of parallel governments. Saudi Arabia hosted Sudanese parties in Jeddah, which led to the signing of the “Jeddah Declaration” in May 2023, outlining commitments to protect civilians and facilitate humanitarian aid. The Kingdom continues to urge all Sudanese factions to prioritize Sudan’s interests over any partisan agendas and to work towards a peaceful resolution, in line with the Jeddah Declaration.
    8. Beyond immediate aid, how is social solidarity and community support being fostered in Saudi Arabia, particularly during Ramadan? Saudi Arabia is moving beyond solely providing immediate, seasonal aid to fostering sustainable social solidarity and community support. During Ramadan, there is a notable increase in charitable initiatives, with institutions and individuals competing to help those in need. Companies are adopting long-term approaches, focusing on empowering vulnerable groups through initiatives that provide job opportunities and support small businesses, contributing to improved quality of life through partnerships. Community iftars (breaking fast meals) are also a significant tradition, strengthening bonds and fostering a sense of unity among neighbors and friends across different neighborhoods. These gatherings, often organized by volunteers and supported by local authorities, highlight the strong social fabric of Saudi society.

    Saudi Arabia and Lebanon: Strengthening Bilateral Relations

    Based on the sources, Saudi Arabia and Lebanon share historical ties and are working towards strengthening their relationship in various fields.

    Historical Context and Support:

    • Historically, the Kingdom of Saudi Arabia has supported Lebanon’s security, stability, politically, economically, and socially.
    • Saudi Arabia played a role in stopping the Lebanese civil war through the “Taif Agreement”.

    Recent Developments and Cooperation:

    • The President of the Lebanese Republic, Joseph Aoun, recently paid an official visit to Saudi Arabia, marking a potential new phase in Saudi-Lebanese relations.
    • The visit aimed to boost bilateral relations and cooperation in various fields, including the economy, in line with the aspirations of the Lebanese people.
    • During the visit, discussions covered various aspects of the relationship and ways to develop it in all fields, in addition to discussing regional and international developments.
    • Both sides emphasized the importance of enhancing joint Arab action and coordinating stances towards important regional and international issues.

    Key Areas of Emphasis in Joint Statements:

    • Taif Agreement: Both Saudi Arabia and Lebanon stressed the importance of the full implementation of the Taif Agreement as the foundation for political balances in Lebanon. Saudi Arabia views the full implementation of this agreement as the sole guarantee to prevent Lebanon from slipping towards a constitutional vacuum or political chaos.
    • State Sovereignty and Security: The importance of extending the state’s authority over all Lebanese territories and confining arms to the Lebanese state was highlighted.
    • Withdrawal of Israeli Forces: Both nations reiterated the necessity of the withdrawal of the Israeli occupation army from all Lebanese territories.
    • Economic Recovery: Agreement was reached on the necessity of the Lebanese economy’s recovery and overcoming its current crisis by initiating internationally required reforms based on the principles of transparency and the application of binding laws. Saudi Arabia has historically sought Lebanon’s stability.
    • Arab Identity: The joint statement emphasized that Lebanon’s Arab relations are essential for its security and stability.
    • Resumption of Exports: Both sides agreed to study obstacles hindering the resumption of Lebanese exports to the Kingdom of Saudi Arabia.

    Challenges and Past Issues:

    • Despite past political repercussions that distanced the Lebanese, Saudi Arabia has continued to provide humanitarian aid to the Lebanese people, including an airlift carrying 27 shipments of relief aid containing food, shelter, and medical supplies.
    • There was a continuous debate within Lebanon regarding the Taif Agreement, leading to the Saudi-Lebanese reiteration of its importance.

    Future Outlook:

    • The recent meeting is seen as a prelude to strengthening relations and looking towards the future under the title of “Partnership for a New Era”.
    • Saudi Arabia blesses every sincere effort that seeks the good of the Arab nation and its unity.
    • Lebanon, looking to turn a page on the past, sees the enhancement of relations with Saudi Arabia as a priority.

    In conclusion, Saudi-Lebanese relations are characterized by historical support, a recent push for renewed cooperation across various sectors, and a shared vision on key regional and domestic issues for Lebanon, particularly emphasizing the importance of the Taif Agreement and Lebanese sovereignty.

    Saudi Arabia’s Support for Lebanon: Dimensions and Commitments

    Drawing on the sources and our conversation history, the support for Lebanon is a significant aspect of Saudi Arabia’s engagement with the country. This support is multifaceted, encompassing historical, political, security, and economic dimensions.

    Historical Support:

    • The Kingdom of Saudi Arabia has historically supported Lebanon’s security, stability, and its political, economic, and social well-being.
    • Saudi Arabia played a crucial role in brokering the “Taif Agreement,” which aimed to end the Lebanese civil war.

    Recent Support and Cooperation:

    • The recent official visit of the Lebanese Republic’s President, Joseph Aoun, to Saudi Arabia underscores a renewed commitment to strengthening bilateral relations in various fields, including the economy. This visit is seen as a potential “new phase for Saudi-Lebanese relations”.
    • Discussions during the visit covered various aspects of the relationship, aiming to develop it across all sectors, alongside discussions on regional and international developments.
    • Both Saudi Arabia and Lebanon emphasized the importance of boosting joint Arab action and coordinating their positions on significant regional and international issues.

    Key Areas of Emphasis in Supporting Lebanon:

    • The Taif Agreement: Both nations have consistently highlighted the importance of the full implementation of the Taif Agreement. Saudi Arabia views this agreement as the fundamental basis for political equilibrium in Lebanon and the primary safeguard against constitutional voids or political instability.
    • Lebanese Sovereignty and Security: A central tenet of the support is the emphasis on extending the Lebanese state’s sovereignty over all its territories. This includes the crucial aspect of confining arms to the Lebanese state. The joint statement explicitly mentions the importance of the Lebanese national army’s role and supporting it in this endeavor.
    • Withdrawal of Israeli Forces: Both Saudi Arabia and Lebanon have reiterated the necessity of the complete withdrawal of the Israeli occupation army from all Lebanese territories. This remains a consistent point of agreement and support for Lebanon’s territorial integrity.
    • Economic Recovery: Recognizing the current economic challenges in Lebanon, both sides have agreed on the necessity of the Lebanese economy’s recovery and overcoming its crisis. This involves initiating internationally required reforms grounded in transparency and the application of binding laws. Saudi Arabia has historically been invested in Lebanon’s stability, which inherently includes its economic well-being. They also agreed to study the obstacles hindering the resumption of Lebanese exports to Saudi Arabia.
    • Arab Identity: The joint statements have emphasized that Lebanon’s Arab relations are fundamental to its security and stability. This highlights a shared understanding of Lebanon’s place within the broader Arab context.
    • Blessing Sincere Efforts: Saudi Arabia has expressed its support by “blessing every sincere effort that seeks the good of the Arab nation and its unity,” which implicitly includes efforts towards Lebanon’s stability and progress.
    • Lebanon’s Perspective: Lebanon, as indicated, prioritizes the enhancement of its relations with Saudi Arabia, viewing it as a crucial step in overcoming past issues and looking towards a more stable future. The Lebanese President’s choice of Riyadh as his first foreign visit further underscores this priority.

    In summary, the support for Lebanon from Saudi Arabia is rooted in historical ties and continues through active engagement and a shared vision for Lebanon’s sovereignty, security, and economic recovery. Key to this support is the emphasis on the Taif Agreement as a foundational element for Lebanon’s stability and the need for a strong, sovereign Lebanese state.

    Global Trade Activities and Interconnected Economies

    Based on the sources provided, there is some information that touches upon aspects of global trade, although none of the sources directly discuss a “global trade war” as a central topic. However, we can infer related concepts and activities:

    • Source mentions that the price of copper fell slightly on Tuesday due to the weight of customs tariffs policies pursued by Trump on the metal. Investors in the red metal were also cautiously awaiting meetings of China’s parliament to gain insight into potential economic stimulus measures aimed at boosting domestic demand. This indicates how national trade policies and economic conditions in major economies can influence global commodity markets.
    • Sources and discuss the import of used cars into Saudi Arabia. The increased availability of used cars from abroad has intensified competition, contributing to lower prices for consumers in Saudi Arabia. Car auctions in the Kingdom also provide an environment for competitive pricing, including for imported vehicles. These points illustrate the flow of goods across borders and the impact of international trade on local markets and consumer prices.
    • Source notes that during the month of Ramadan, Saudi Arabia receives imports of certain fruits and vegetables by air, sea, and land to ensure stable prices and availability. This highlights the reliance on international trade to meet domestic consumption needs, especially during peak demand periods.
    • Source mentions that Saudi Aramco issued international bonds in July, with subscriptions exceeding the initial target size due to strong demand from a diverse base of both existing and new institutional investors. In October, Aramco also completed the issuance of dollar-denominated international Sukuk, which also saw subscriptions exceeding several times the target size. This demonstrates Saudi Arabia’s engagement with global financial markets and the flow of capital across borders.
    • Source discusses a thought-provoking question about where Saudi Arabia’s sovereign wealth fund should invest. It mentions a suggestion that the fund might find it best to invest the majority of its capital in private markets and basic infrastructure in the United States, driven by a strategic mandate and the philosophy of directing funds towards federal priorities. This reflects considerations around international investment strategies and their alignment with national interests and global economic landscapes.

    While these instances do not provide a comprehensive discussion of a “global trade war,” they offer glimpses into international trade activities, the impact of national economic policies on global markets (tariffs), and the interconnectedness of economies through the flow of goods and investments. The mention of tariffs in the context of copper prices is the most direct link to the concept of trade tensions, as tariffs are a common tool used in trade disputes.

    Saudi Arabia and the Palestinian Cause

    Based on the sources, the Palestinian cause is a significant and consistently addressed issue. Saudi Arabia maintains a firm and unwavering stance in defense of the rights of the Palestinian people.

    Key aspects of the Saudi Arabian position on the Palestinian cause, as highlighted in the sources, include:

    • Rejection of Displacement: Saudi Arabia strongly rejects the displacement of the Palestinian people from their lands. This was emphasized during the extraordinary Arab Summit “Summit of Palestine” held in Egypt. The Kingdom reiterates this stance, stressing its categorical refusal to infringe upon the legitimate rights of the Palestinian people through any means, including settlement policies or attempts to displace them.
    • Support for Legitimate Rights: Saudi Arabia affirms the right of the Palestinian people to their legitimate rights. This includes their right to self-determination and to establish their independent state on the borders of 1967 with East Jerusalem as its capital.
    • Condemnation of Israeli Occupation: The sources indicate a strong condemnation of the Israeli occupation and its actions. The need for the withdrawal of the Israeli occupation army from all Lebanese territories is repeatedly stressed, which reflects a broader concern about Israeli occupation in the region. Saudi Arabia denounces the Israeli occupation authority’s crimes against the Palestinian people, highlighting the suffering caused by the occupation and its disregard for international law.
    • Support for International Resolutions: Saudi Arabia emphasizes the importance of the full implementation of relevant international resolutions concerning the Palestinian issue.
    • Humanitarian Aid: The Kingdom actively contributes to alleviating the humanitarian situation in the Gaza Strip and its surroundings. The developmental assistance provided by Saudi Arabia to the State of Palestine and the Palestinian people through the Saudi Fund for Development has reached approximately $4.812 billion, covering sectors such as education, health, housing, and refugee housing.
    • Advocacy in International Forums: Saudi Arabia, under its leadership, consistently underscores its firm positions on the Palestinian issue in various international forums. The Kingdom’s commitment to defending the Palestinian cause is evident in its statements and actions, including the address to the Shura Council, where the Palestinian cause was highlighted as a top priority.
    • Efforts for a Peaceful Resolution: Saudi Arabia supports efforts to reach a comprehensive and just solution to the Palestinian cause. The statement highlights the positive role of Qatar and Egypt, in cooperation with the US administration, in reaching a ceasefire in Gaza and the release of hostages. It also mentions the importance of building on these efforts to develop an executive plan for a lasting solution. The Kingdom, as the chair of the Arab Islamic Committee on Gaza and in partnership with the European Union, supports the holding of an international conference, co-chaired by Saudi Arabia and France, to find and implement a solution to the Palestinian issue.
    • Rejection of Harm to Holy Sites: The statement also affirms the support for the Hashemite custodianship of the holy sites, which is relevant to the status of Jerusalem.

    In conclusion, the Palestinian cause is a central pillar of Saudi Arabia’s foreign policy, characterized by a firm commitment to Palestinian rights, rejection of Israeli occupation and displacement, provision of humanitarian aid, and active engagement in regional and international efforts to achieve a just and lasting solution based on relevant international resolutions and the establishment of an independent Palestinian state with East Jerusalem as its capital.

    Saudi Arabia Economic Activities and Initiatives

    Based on the sources, Saudi Arabia’s economy is multifaceted, with significant activities in energy, trade, investment, and social development.

    Energy Sector:

    • Saudi Aramco achieved profits and cash flows in its 2024 results despite lower oil prices. This indicates the continued importance of the oil sector to the Saudi economy.
    • Aramco issued international bonds in July, with strong investor demand. This reflects the company’s access to global financial markets and the confidence of international investors in the Saudi energy giant.
    • In October, Aramco also completed the issuance of dollar-denominated international Sukuk, which was also oversubscribed. This further demonstrates Aramco’s role in international finance.
    • Saudi Aramco has a keen interest in increasing oil production capacity from its fields to maintain its role in the global oil market in the coming years.

    Trade and Imports:

    • Saudi Arabia experiences imports of used cars, which have increased competition and led to lower prices for consumers. This highlights the impact of international trade on the domestic automotive market.
    • During the month of Ramadan, the Kingdom imports fruits and vegetables by air, sea, and land to ensure stable prices and meet increased demand. This reliance on international trade is crucial for food security, especially during peak consumption periods.
    • Saudi Arabia agreed with Lebanon to study the obstacles hindering the resumption of Lebanese exports to the Kingdom. This suggests an interest in fostering bilateral trade relations.

    Investment and Finance:

    • The Saudi Authority for Investment Marketing is being organized, indicating a government focus on attracting and promoting investment in the Kingdom.
    • There is discussion about where Saudi Arabia’s sovereign wealth fund should invest, with a suggestion to focus on private markets and basic infrastructure in the United States. This highlights the strategic considerations involved in managing the Kingdom’s substantial financial reserves and their potential global impact. Our previous conversation mentioned that Saudi Arabia is a country with sovereign wealth funds due to financial surpluses.
    • Saudi Arabia’s sovereign wealth fund is described by Donald Trump as a “big sovereign fund”.

    Government Economic Initiatives and Approvals:

    • The establishment of the Saudi Building Code Academy has been approved in principle. This indicates a focus on developing expertise and standards in the construction sector.
    • The Council of Ministers affirmed the state’s continued support for the social services system and national initiatives aimed at providing suitable housing for eligible families. This reflects a government commitment to social welfare and improving living standards.
    • The Council also reviewed the progress of major development and service projects underway to enhance the Kingdom’s comprehensive renaissance, including the Riyadh Metro project. These projects signify significant government investment in infrastructure development.

    Social Welfare and Support Programs:

    • The state continues to support social services and initiatives to provide housing for those who deserve it.
    • The “Joud Eskan” (Good Housing) campaign is mentioned, emphasizing collaboration between government, private, non-profit sectors, and individuals to achieve its goals.
    • There is mention of social security being easier and more accessible through electronic means, supported by programs like “Citizen’s Account,” “Hafiz,” “Maharah,” “Reef,” and “Manaa”. These initiatives aim to support limited-income individuals, entrepreneurs, and investors.

    In summary, Saudi Arabia’s economy is heavily influenced by its strong energy sector, particularly through the activities of Saudi Aramco in production and international finance. The Kingdom actively engages in international trade to meet domestic needs and is also focused on attracting investment through initiatives like the Saudi Authority for Investment Marketing. The government demonstrates a commitment to social welfare and infrastructure development through various programs and projects. The strategic management of the sovereign wealth fund also plays a crucial role in the Kingdom’s long-term economic outlook.

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • Express.js: Building RESTful APIs and Dynamic Templates

    Express.js: Building RESTful APIs and Dynamic Templates

    This comprehensive guide covers Node.js and Express.js, starting with basic concepts like Node modules and event emitters, and progressing to building custom emitters. The material then transitions to Express.js, explaining routing, middleware, template engines, and RESTful API development, including how to create dynamic routes. It further explores REST API structure with MongoDB, including setting up a database, creating schemas, and performing CRUD operations. The guide also addresses user authentication, including registration, login, cookie management, and role-based authorization. Advanced topics like aggregation pipelines and document references in MongoDB are then discussed. Finally, the guide introduces TypeScript with Node.js, focusing on setting up a TypeScript project, using interfaces, and integrating it with Express.js and Mongoose.

    Comprehensive Node.js Study Guide

    Quiz

    Answer each question in 2-3 sentences.

    1. What is the purpose of the Node.js module system?
    2. Explain the difference between module.exports and require in Node.js.
    3. What is the module wrapper in Node.js, and what parameters does it include?
    4. What is npm, and what are some key npm commands?
    5. What does the path module provide in Node.js, and give an example of how it’s used?
    6. How does the file system (fs) module work in Node.js?
    7. What are streams in Node.js, and why are they useful?
    8. Explain the difference between synchronous and asynchronous code execution.
    9. Describe promises in JavaScript and how they are used to handle asynchronous operations.
    10. What are async and await keywords used for and how do they relate to promises?

    Quiz Answer Key

    1. The Node.js module system allows developers to organize code into reusable pieces, promoting modularity and manageability. It allows for code to be split into multiple files and then each file can be treated as a separate module. This helps in creating large applications.
    2. module.exports is used to expose functionality (variables, functions, objects) from a module, making it available for use in other modules. require is used to import the functionality that has been exported from another module.
    3. The module wrapper is a function that wraps every Node.js module before it is executed, providing scope and access to module-specific variables. It includes parameters like exports, require, module, __filename (file name), and __dirname (directory name).
    4. npm (Node Package Manager) is the default package manager for Node.js, used to install, manage, and publish packages. Key commands include npm init (initialize a new project), npm install (install packages), npm uninstall (uninstall packages), and npm start (run scripts defined in package.json).
    5. The path module provides utilities for working with file and directory paths. For example, path.join() can be used to combine multiple path segments into a single path.
    6. The file system (fs) module allows interaction with the file system, enabling operations such as reading files, writing files, creating directories, and checking file existence. Functions like fs.readFile() read from files and functions like fs.writeFile() write to files.
    7. Streams in Node.js are a way to handle reading and writing data sequentially, piece by piece, instead of all at once. They are useful for processing large files or data flows efficiently, preventing memory overload.
    8. Synchronous code executes line by line, with each operation completing before the next one starts, blocking the execution thread. Asynchronous code allows multiple operations to run concurrently without blocking, typically using callbacks, promises, or async/await.
    9. Promises are JavaScript objects that represent the eventual completion (or failure) of an asynchronous operation. They provide a cleaner way to handle asynchronous code, avoiding callback hell and enabling better error handling through .then() and .catch() methods.
    10. async is used to define asynchronous functions that implicitly return a promise, while await is used inside async functions to pause execution until a promise is resolved. This syntax makes asynchronous code look and behave more like synchronous code, improving readability.

    Essay Questions

    1. Discuss the advantages and disadvantages of using the Node.js module system for organizing code in large applications. How does this system compare to other module systems in languages like Python or Java?
    2. Explain the concept of asynchronous programming in Node.js, detailing how callbacks, promises, and async/await are used to manage non-blocking operations. Provide examples of scenarios where asynchronous programming is essential for performance.
    3. Compare and contrast the use of streams and buffers in Node.js. Describe situations where streams are preferable to buffers and explain how streams can improve the efficiency of file processing.
    4. Describe the role of npm in Node.js development. Discuss the importance of package.json for managing dependencies and explain how semantic versioning is used to handle package updates and compatibility.
    5. Explain how to use the module wrapper and how it allows for parameters such as require, module, filename, and dirname to be used. Give examples of each one.

    Glossary of Key Terms

    • Module System: A feature of Node.js that allows code to be organized into reusable units called modules.
    • module.exports: A Node.js object that is used to expose functions, objects, or values from a module so they can be used by other parts of the application.
    • require: A Node.js function used to import modules and their exported values into the current file.
    • Module Wrapper: A function that wraps every Node.js module, providing a private scope and access to module-specific variables like exports, require, module, __filename, and __dirname.
    • npm (Node Package Manager): The default package manager for Node.js, used to install, manage, and publish packages.
    • npm init: An npm command that initializes a new Node.js project and creates a package.json file.
    • npm install: An npm command that installs packages and their dependencies into the current project.
    • npm uninstall: An npm command that removes packages from the current project.
    • npm start: An npm command that runs scripts defined in the package.json file, typically used to start the application.
    • package.json: A JSON file that contains metadata about a Node.js project, including dependencies, scripts, and project information.
    • Path Module: A Node.js module that provides utilities for working with file and directory paths.
    • File System (fs) Module: A Node.js module that provides methods for interacting with the file system, such as reading and writing files, creating directories, and checking file existence.
    • Streams: A way to handle reading and writing data sequentially, piece by piece, instead of all at once.
    • Synchronous Code: Code that executes line by line, with each operation completing before the next one starts.
    • Asynchronous Code: Code that allows multiple operations to run concurrently without blocking, typically using callbacks, promises, or async/await.
    • Promises: JavaScript objects that represent the eventual completion (or failure) of an asynchronous operation.
    • async: A keyword used to define asynchronous functions that implicitly return a promise.
    • await: A keyword used inside async functions to pause execution until a promise is resolved.

    Node.js Development: Concepts and Practices

    Okay, here’s a detailed briefing document summarizing the key themes and ideas from the provided text excerpts.

    Briefing Document: Node.js Development Concepts

    Overview:

    This document summarizes key concepts related to Node.js development, as presented in the provided text. The excerpts cover basic syntax, module systems, package management with NPM, core modules like path and fs (file system), asynchronous programming with Promises and Async/Await, basic HTTP server creation, database interaction using Mongoose with MongoDB, project structuring, authentication with JWT, file uploads with Multer, role-based access control, testing with Jest, deployment to Render and Vercel, and GraphQL basics including schemas, queries, mutations, and resolvers. There’s also a section touching on using Typescript with Node.js.

    Key Themes and Ideas:

    1. Node.js Basics & Execution:
    • Node.js allows execution of JavaScript code outside of a web browser environment.
    • Code can be executed directly in the terminal using node <filename.js>.
    • Synchronous code executes line by line. Asynchronous operations (like setTimeout) don’t block the execution of subsequent lines. “See this actually wait until unless this set timeout is getting run right so first time you’re getting this last line of the sync code and then after 2 seconds you’re getting that this message is delayed by 2 seconds.”
    1. Module System:
    • Node.js has a module system for organizing code into reusable pieces. “nodejs has a module system where you will be able to create different different modules and then you can use those modules in a single root module”
    • Each file is treated as a separate module. “each file again I’m repeating each file in nodejs will be treated as a separate modu okay”
    • module.exports is used to expose functionality from a module (similar to export in ES modules). “module. exports is used to expose functionality from a module”
    • require() is used to import functionality from other modules (similar to import). “require is used to import functionality from other modules as simple as that”
    • Node.js uses CommonJS module format.
    • Module wrapper: Every module is wrapped in a function before execution, providing variables like exports, require, module, __filename, and __dirname. “in nodejs every module whatever module that we are creating is wrapped in a function before it executed very very important thing and this rapper function we called as a module rapper function”
    • Demonstration of using module.exports and require to create and use a simple math module (first_module.js) in index.js.
    • Error handling using try…catch blocks. “to do this one right let’s go here okay first I’ll just minimize this one let’s create a very try and catch block now these all are also very basic JavaScript concept so we will take a try catch and catch will give us error right here”
    1. NPM (Node Package Manager):
    • NPM is the default package manager for Node.js. “npm is the default package manager for nodejs”
    • Allows installing and managing third-party libraries and tools.
    • Manages project dependencies. “this package.json file which is nothing but a Json file that contains a metadata about your project”
    • Enables running scripts defined in package.json.
    • Allows publishing your own packages.
    • Key NPM commands:
    • npm init: Initializes a new Node.js project, creating a package.json file. “to create a new package.json inside this folder first I’m going to open in our integrated terminal and let’s close everything and here to create it so we need to do npm it”
    • npm install <package_name>: Installs a specific package. “to do this one we need to use this npm install Command right so you do npm install and then the name of the package”
    • npm uninstall <package_name>: Uninstalls a package.
    • npm update <package_name>: Updates a package to the latest version.
    • npm run <script_name>: Runs a script defined in package.json. “to run a particular script so you can see that there is different different scripts right so you need to do npm run and then the script name and whatever scripts is defined in your package. JS and so that will be automatically run”
    • Distinction between dependencies (required for production) and devDependencies (needed for local development). “dependencies are all the packages that is actually required for your application to run in production”
    • “the D dependencies as the name suggest only needed for your local development and in right”
    1. Core Modules: Path and File System (fs)
    • Path Module: Provides utilities for working with file and directory paths. “path module provides utilities for working with file and directory paths”
    • path.dirname(__filename): Gets the directory name of the current file. “let’s log the current directory name so I’m going to do here console.log and let’s give like directory name right and here I’m going to give path dot so the um this is a method so this directory name and here you need to pass the file name so we’ll do file name”
    • path.basename(__filename): Gets the base name (filename) of the current file.
    • path.extname(__filename): Gets the file extension.
    • path.join(): Joins multiple path segments into one. “I’ll create one more Sal const join path and here we are going to give path. join and you can give different path let’s I want to go to/ user and then after this I want to merge or join documents this is just example”
    • path.resolve(): Resolves a sequence of paths to an absolute path.
    • path.normalize(): Normalizes a path string.
    • File System (fs) Module: Provides APIs for interacting with the file system. “the file system help you to work with files”
    • fs.existsSync(): Checks if a file or directory exists synchronously. “I’m going to check at this FS dot so we have exists sync okay so this here we’re going to check this data folder so this will check whether this is exist or not”
    • fs.mkdirSync(): Creates a directory synchronously. “fs. mkd sync now what again this will do this will create a that data folder right so I’m going to create pass your data folder and I’m going to just do a console.log and I’ll do data folder created”
    • fs.writeFileSync(): Writes data to a file synchronously. ” to create a file we are going to again you need to give the file path like where you want to create the file”
    • fs.readFileSync(): Reads data from a file synchronously.
    1. Asynchronous Programming:
    • Promises: Represents the eventual completion (or failure) of an asynchronous operation. “promise interface that we can use but let’s uh do this one with a simple example so I’m going to create a function I’m I’m going to do a delay function which will take a timer or time and this delay function will return return a promise”
    • States: Pending, Fulfilled (Resolved), Rejected.
    • .then(): Handles the fulfilled (resolved) state of a Promise. “this will give a DOT then right which I’m pretty sure you already know I’m you guys might be thinking that what I’m doing all of this but I think it’s important to just revise all of this one more time even if you know right so this will give you then which if the promise is getting resolv so it will come inside this then block or on full field”
    • .catch(): Handles the rejected state of a Promise. ” I’m going to catch here so this will be my error block and here I’m going to just log my error and let’s do a console do log and I’m going to log my error here”
    • Async/Await: Syntactic sugar over Promises, making asynchronous code easier to read and write. “asnc function that whatever each and every asnc function that you’ll be creating it will always always return a promise very very important every time it will return a promise”
    • async keyword: Marks a function as asynchronous; it implicitly returns a Promise. “I’m going to do as sync function right because we need to give the ASN keyword”
    • await keyword: Pauses the execution of an async function until a Promise is resolved. “the a keyword is is only be used inside your Hing function you can’t use outside of it right and what that a keyword does so it pauses the execution of the function until unless your promise is getting resolved”
    • Example of creating a delay function using setTimeout and Promises, and then using async/await to call it.
    1. Basic HTTP Server:
    • Using the http module to create a basic HTTP server.
    • Handling requests and sending responses.
    • Setting response headers.
    • Example of creating a simple server that responds with “Hello Node!” based on different routes.
    1. MongoDB and Mongoose:
    • Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
    • It provides a higher-level abstraction for interacting with MongoDB.
    • Connecting to MongoDB:Using mongoose.connect() to establish a connection to the database. Requires a connection string (MongoDB URI).
    • Error handling for connection failures.
    • Defining Schemas:Using mongoose.Schema to define the structure of documents in a MongoDB collection. “if you go here first you need to create a schema right so this mongos will give you this schema property and using this you’ll be able to create a new schema so you can see that new schema and then all the properties”
    • Defining data types for each field in the schema (e.g., String, Number, Boolean, Date, Array).
    • Setting validation rules (e.g., required, unique). “I want to tell mongos that okay this user the whatever public will come to register in your website the enam can be only a user so it can be only a normal user or it can be a admin user”
    • Setting default values for fields.
    • Creating Models:Using mongoose.model() to create a model based on a schema. “this will be mongus now to create a model you need to give a model and this will take a name okay this will take a name which will be this in your database it will be stored in that particular name whatever name you give let’s say you give this one as user so this will be the collection name in your database that I I’m storing all my user in this user collection”
    • Performing CRUD Operations (Create, Read, Update, Delete):create(): Creates a new document in the database.
    • find(): Retrieves documents from the database.
    • findById(): Retrieves a document by its ID.
    • updateOne(): Updates a document in the database.
    • deleteOne(): Deletes a document from the database.
    • Querying Data:Using query operators (e.g., $gt for greater than, $lt for less than, $in for inclusion in an array) to filter data.
    • Using logical operators (e.g., $and, $or) to combine multiple conditions.
    • Sorting data using sort().
    • Limiting the number of results using limit().
    • Pagination using skip() and limit().
    • Aggregation:Using the aggregation pipeline to perform complex data transformations. “this will be aggregation right and this aggregations pipeline actually is a concept from mangos where we can do a different set of things”
    • $match: Filters documents based on specified criteria.
    • $group: Groups documents based on a specified field and performs calculations (e.g., average, sum, count) on the grouped data.
    • $project: Selects specific fields to include in the output documents.
    1. Project Structuring:
    • Importance of organizing code into a well-defined folder structure. “till this part we haven’t worked on proper folder structure right each and everything like we have created inside server.js but that is not the way so how we are going to manage our project”
    • Common folder structure:
    • database: Contains database connection logic (db.js).
    • models: Contains Mongoose models (schemas).
    • routes: Defines API routes. “each and so for example let’s say you’re having a very complex application uh where you’re having multiple you need to work with multiple collection let’s say some e-commerce project so you’ll be having products you’ll be having card you’ll be having checkout you’ll be product details so for each and everything you’ll be having different different routes so that you’re not going to write each and everything on one single file and it will become messy so that is the reason we’ll be having a routes folder right”
    • controllers: Handles the main code logic for each route, interacting with the database. “controllers basically handle our main code logic that corate or basically connect with sorry not connect that uh work with your mongod database and then that controller we are going to use inside our outs”
    • middleware: Contains middleware functions. “whatever middleware related Logics that we’ll be writing we are going to write inside that folder”
    • helper: Contains helper/utility functions.
    • .env: Stores environment variables (e.g., database URI, API keys). “why we need the NV file let’s say the mongod the mongodb URL or let’s say some sensitive information some token and everything whatever we’ll be using in our project we are not going to push those changes in our GitHub right”
    • Using .gitignore to exclude sensitive files (e.g., .env, node_modules) from version control.
    1. Authentication and Authorization:
    • JWT (JSON Web Token):Using JWT for user authentication. “we need to authenticate every request by by passing a JWT token and then check if it’s a authenticated or not”
    • Generating a JWT upon successful login. “if those condition meets then we create our GWT token so that can access their route that’s it now this is like a very simple but the whole entire work how the authentication and authorization work behind the scene it”
    • Verifying the JWT in middleware to protect routes. “it that okay this will be a our security so we’ll be passing something and based on that we be able to check the data”
    • jsonwebtoken library for creating and verifying JWTs.
    • bcrypt.js:Hashing passwords before storing them in the database. “we need to has it or we need to store in encrypted form so that is the reason we’re going to use this most used package and that is called the bcrypt JS what this does you can see that it will create a Sol to protect against your Rainbow table attacks”
    • Comparing hashed passwords during login.
    • Using bcrypt.hash() to hash a password.
    • Using bcrypt.compare() to compare a password with its hash.
    • Role-Based Access Control (RBAC):Implementing RBAC to restrict access to certain routes based on user roles (e.g., admin, user). “So role based authentication or access control actually means what let’s say if there is a admin panel so you can only able to see if you are an admin user okay if you are a normal user it might be you’re not able to see”
    • Adding a role field to the user schema.
    • Creating middleware to check user roles before granting access to routes.
    1. File Uploads with Multer:
    • Using Multer middleware to handle file uploads.
    • Configuring Multer to specify the storage location for uploaded files.
    • Handling single and multiple file uploads.
    • Storing file information in the database.
    • Cloudinary is an option for file storage
    1. Testing with Jest:
    • Using Jest for writing unit tests. “let’s see that we’re going to how we are going to write some test okay so we’re going to use J and also the super test right and using these two package we we are going to write API test now as I already told you that what the unit test unit tests actually helps you to create the test for each and individual method not method each and individual modules it will not trigger any other modules it just want to test a single unit that’s what it”
    • Writing test cases to verify API endpoints.
    • supertest for sending HTTP requests to the API during testing.
    • Using expect() to make assertions about the response.
    1. Deployment (Render and Vercel):
    • Deploying Node.js applications to cloud platforms like Render and Vercel.
    • Render:Creating a render.yaml file to configure the deployment.
    • Specifying the build command and start command in the render.yaml file.
    • Setting environment variables in the Render dashboard.
    • Vercel:Configuring the build and output options in the Vercel dashboard.
    • Setting environment variables in the Vercel dashboard.
    • Importance of modifying package.json to ensure correct deployment.
    1. GraphQL:
    • GraphQL is a query language for APIs (developed by Facebook). “graph kill is developed by Facebook and uh this is nothing just a query language for apis”
    • Advantages over REST:
    • Precise data fetching: Clients can request only the data they need.
    • Single endpoint for all data operations.
    • Improved performance due to reduced over-fetching and under-fetching.
    • Key GraphQL concepts:
    • Schema: Defines the structure of the data and the operations that can be performed. “the schema file will Define your schema for your project that you are creating now what actually that schema is that is nothing but the structure of your data or the operation that you will perform”
    • Types: Define the data types of the fields in the schema (e.g., String, Int, Float, Boolean, ID). “this type keyword you need to give and then the name so let’s give this one as product so this is your type now inside this you need to specify that what kind of fields this product will have”
    • Queries: Used to fetch data.
    • Mutations: Used to modify data (create, update, delete). “mutation is where we’ll be able to create create a new product”
    • Resolvers: Functions that provide the data for the fields in the schema. “resolvers simply resolve what you are going to do so how you’re going to face the data”
    • Using graphql-tag to write GraphQL schemas and queries.
    1. TypeScript with Node.js:
    • Using TypeScript to add static typing to Node.js applications. “TypeScript is what it’s a superet of Javascript and that is actually what it has a static typing so whenever you’ll be creating projects you might uh or you usually wanted to write your function or the properties with a specific types”
    • Benefits of using TypeScript:
    • Improved code readability and maintainability.
    • Early detection of errors during development.
    • Better code completion and refactoring support in IDEs.
    • Defining interfaces to specify the types of objects. “you can create custom types remember I created this custom request and then I extend the request object from Express similarly for this one also you can extend the main document and then you can add your own Uh custom uh schemas or user structure whatever you you will be creating here”
    • Typing Mongoose schemas and models.

    Overall Impression:

    The text provides a broad overview of essential Node.js development concepts, ranging from basic syntax and module management to advanced topics like asynchronous programming, database interaction, testing, deployment, and GraphQL. The excerpts emphasize the importance of code organization, proper error handling, and understanding the underlying principles of each technology.

    Node.js Development: Frequently Asked Questions

    Frequently Asked Questions about Node.js Development

    Here are some frequently asked questions, based on the provided documentation.

    1. What is the Node.js module system, and why is it important?

    The Node.js module system allows you to organize your code into reusable pieces. Instead of writing all code into one large file, you can break it down into separate modules (files). This modularity makes code more manageable, readable, and reusable, particularly in large applications. Each file in Node.js is treated as a separate module. The module system relies on module.exports (to expose functionality from a module) and require (to import functionality from other modules).

    2. How do module.exports and require work in Node.js?

    module.exports is used to expose functions, objects, or values from a Node.js module, making them available for use in other modules. Think of it like ‘export’ in ES modules. require is used to import the functionality that has been exposed by other modules via module.exports. It’s similar to ‘import’ in ES modules, but follows the CommonJS syntax used by Node.js. When you require a module, you get whatever was assigned to module.exports in that module.

    3. What is the module wrapper in Node.js?

    In Node.js, every module’s code is wrapped inside a function before execution. This wrapper function provides several arguments: exports, require, module, __filename (the current file’s name), and __dirname (the current directory’s name). This wrapper provides a level of privacy and encapsulation for the module’s code, preventing variables and functions from polluting the global scope.

    4. What is npm (Node Package Manager), and what are some essential commands?

    npm is the default package manager for Node.js. It allows you to install, manage, and publish Node.js packages (libraries and tools). Key npm commands include:

    • npm init: Initializes a new Node.js project and creates a package.json file. Using npm init -y automatically accepts the defaults and creates a package.json file without prompting for input.
    • npm install <package_name>: Installs a specific package as a dependency for your project.
    • npm uninstall <package_name>: Uninstalls a package from your project.
    • npm update <package_name>: Updates a package to the latest version.
    • npm run <script_name>: Runs a script defined in the package.json file.

    5. What is the purpose of package.json?

    The package.json file is a JSON file that contains metadata about your Node.js project. It lists project dependencies (packages required for the application to run), development dependencies (packages needed only for development, like testing tools), scripts (commands to automate tasks), and other project-related information.

    6. How does the path module in Node.js help with file paths?

    The path module provides utilities for working with file and directory paths. It offers functions to:

    • Get the directory name of a file (path.dirname()).
    • Extract the base name (file name) from a path (path.basename()).
    • Get the file extension (path.extname()).
    • Join multiple path segments into a single path (path.join()).
    • Resolve a path to an absolute path (path.resolve()).
    • Normalize a path to remove redundant separators (path.normalize()).

    7. How do you handle asynchronous operations in Node.js using Promises, async, and await?

    • Promises: Promises represent the eventual result of an asynchronous operation. They can be in one of three states: pending, fulfilled (resolved), or rejected. Promises provide a structured way to handle asynchronous code, avoiding callback hell. You can use .then() to handle successful resolutions and .catch() to handle rejections.
    • Async/Await: async and await are syntactic sugar over Promises, making asynchronous code look and behave more like synchronous code. An async function always returns a Promise. The await keyword can only be used inside an async function and pauses the execution of the function until a Promise is resolved or rejected. This makes asynchronous code easier to read and write.

    8. How can you connect to a MongoDB database using Mongoose and define a schema?

    First, install the Mongoose package (npm install mongoose). Then, use mongoose.connect() to connect to your MongoDB database, providing the connection URL. After the connection is successful, define a schema using new mongoose.Schema(), specifying the data types and properties for each field in your documents. Then use mongoose.model() to create a model. This model allows you to interact with your MongoDB database collection using Mongoose’s methods (e.g., find(), create(), save(), delete(), aggregate())

    Node.js Custom Event Emitter Guide

    A custom event emitter can be created in Node.js using the events module. Here’s how it works:

    1. Import the events module.
    • This module is required to create event emitters.
    • const eventEmitter = require(‘events’).
    1. Create a class that extends EventEmitter.
    • This class will serve as the custom event emitter.
    • It inherits the emit and on methods from the EventEmitter class.
    • class MyCustomEmitter extends eventEmitter {
    • constructor() {
    • super();
    • this.greeting = ‘Hello’;
    • }
    • greet(name) {
    • this.emit(‘greeting’, this.greeting, name);
    • }
    • }
    1. Define a constructor.
    • The constructor can be used to set up initial properties for the emitter.
    • It calls super() to invoke the constructor of the parent class (EventEmitter).
    • In the example, the greeting property is initialized.
    1. Create a method to emit events.
    • This method uses the emit method to trigger an event with a specific name.
    • It can also pass arguments to the listeners.
    • In the example, the greet method emits a greeting event with the greeting and a name.
    1. Create an instance of the custom emitter.
    • This creates an object that can emit and listen for events.
    • const myCustomEmitter = new MyCustomEmitter();
    1. Register a listener for the event.
    • The on method is used to register a listener function that will be executed when the event is emitted.
    • The listener function receives the arguments passed by the emit method.
    • myCustomEmitter.on(‘greeting’, (greeting, name) => {
    • console.log(‘Greeting event:’, greeting, name);
    • });
    1. Emit the event.
    • Call the method that emits the event to trigger the listener function.
    • myCustomEmitter.greet(‘Sumit’);

    When the code is executed, the greet method emits the greeting event. This triggers the listener function, which logs “Greeting event: Hello Sumit” to the console.

    Creating an Express Server in Node.js

    An Express server in Node.js can be created as follows.

    Key Features of Express.js

    • Routing: Express.js is known for its routing capabilities.
    • Middleware: It uses middleware.
    • Template Engines: It supports template engines like EJS and Pug for dynamic HTML generation.
    • Static File Serving: It can serve static files.
    • Error Handling: It offers error handling.
    • RESTful API Development: It is useful for creating RESTful APIs.

    Steps to Create an Express Server

    1. Import the Express module: This is done using the require function.
    2. const express = require(‘express’);
    3. Create an Express application: Invoke the express module which returns an express application.
    4. const app = express();
    5. Define a port to listen for client requests.
    6. const port = 3000;
    7. Create routes: Define routes for different HTTP methods (GET, POST, etc.) and URL paths.
    8. app.get(‘/’, (req, res) => {
    9. res.send(‘Hello World!’);
    10. });
    • The app.get() method specifies a route for handling GET requests to the root URL (“/”).
    • The callback function receives a request object (req) and a response object (res).
    • The res.send() method sends the response “Hello World!” back to the client.
    1. Start the server: Use the app.listen() method to start the server and listen for incoming connections on a specific port.
    2. app.listen(port, () => {
    3. console.log(`Server is running at port ${port}`);
    4. });
    • This makes the server accessible at localhost:3000.

    Middleware

    • To use middleware, the app.use() method is employed.
    • Middleware functions have access to the request and response objects, and the next middleware function in the stack.
    • express.json() is a built-in middleware used to parse JSON data in request bodies.

    Application Settings

    • app.set() is used to set application-level settings, such as the view engine.
    • For example, to set the view engine to EJS:
    • app.set(‘view engine’, ‘ejs’);

    Example

    const express = require(‘express’);

    const app = express();

    const port = 3000;

    app.get(‘/’, (req, res) => {

    res.send(‘Hello World!’);

    });

    app.listen(port, () => {

    console.log(`Server is running at port ${port}`);

    });

    Express.js Dynamic Routing

    Dynamic routing in Express.js involves creating routes where a portion of the URL can vary. This allows a single route to handle requests for multiple resources based on a parameter passed in the URL.

    Key Concepts and Implementation

    • Defining Dynamic Routes: To create a dynamic route, a colon (:) is used before the parameter name in the route path. For example, /products/:id defines a route where :id is a dynamic parameter.
    • Accessing Route Parameters: The req.params object is used to access the values of the dynamic parameters. For example, in the route /products/:id, the value of id can be accessed using req.params.id.
    • Example:
    • app.get(‘/products/:id’, (req, res) => {
    • const productID = parseInt(req.params.id); // Parse the ID
    • // Logic to retrieve product from a database or array
    • // Send the product as a JSON response
    • });

    Note: Information regarding retrieving a product from a database or array was not found in the source.

    Use Cases

    • E-commerce Applications: Dynamic routes are commonly used in e-commerce to display details for specific products. For example, clicking on a product with id2 would navigate to /products/2.
    • API Endpoints: They are useful for creating API endpoints where a specific resource needs to be accessed based on its ID or another identifier.

    Important Notes

    • Parameter Naming: When defining dynamic routes, the name given to the parameter after the colon (e.g., :id) must be used to access its value in req.params (e.g., req.params.id).
    • Data Retrieval: In real-world scenarios, the dynamic value captured from the URL is often used to query a database and retrieve the corresponding data.
    • Middleware: Dynamic routes can also be used with middleware to perform actions based on the parameters.

    By using dynamic routing, Express.js applications can create more flexible and efficient routes that adapt to different request parameters.

    Express.js Template Engines for Dynamic HTML Generation

    Template engines in Express.js are used to generate dynamic HTML pages with plain JavaScript. Template engines can help to generate dynamic HTML pages in Express applications.

    Key Aspects

    • Definition: A template engine is HTML markup with plain JavaScript.
    • Purpose: Template engines help in generating dynamic HTML pages in Express applications.

    Example with EJS

    • Set the View Engine: Tell Express to use EJS as the view engine.
    • app.set(‘view engine’, ‘ejs’);
    • Set the Views Directory: Specify the directory where the view files are located.
    • app.set(‘views’, path.join(__dirname, ‘views’));
    • Create Views: Create a views folder where the HTML files will reside. Each file in this folder will be treated as a separate module.
    • Render Views: Use res.render() to render the template and pass data to it.
    • app.get(‘/’, (req, res) => {
    • res.render(‘home’, { title: ‘Home’, products: products });
    • });
    • In this example, home.ejs is rendered, and data such as title and products are passed to the template.
    • Access Data in Templates: Use special tags to output dynamic values in the template.
    • <h1><%= title %></h1>
    • <ul>
    • <% products.forEach(product => { %>
    • <li><%= product.title %></li>
    • <% }); %>
    • </ul>
    • The <%= … %> tag is used to output the value of a variable.
    • The <% … %> tag is used for control flow, such as loops.

    Benefits of Using Template Engines

    • Dynamic HTML: Template engines allow generating HTML pages dynamically based on data from the server.
    • Code Reusability: Common components, like headers and footers, can be created as partials and included in multiple views.

    By using template engines like EJS, developers can create dynamic and maintainable web applications with Express.js.

    RESTful API Development with Express.js: A Practical Guide

    RESTful API development involves creating APIs that adhere to the principles of REST (Representational State Transfer) architecture. Express.js is a framework that provides features for building such APIs in Node.js.

    Key Features of Express.js for API Development

    • Routing: Manages routes.
    • Middleware: Uses middleware.
    • RESTful API Development: Facilitates RESTful API creation.

    Project Structure

    To organize an API project, a typical structure includes:

    • Models: Data models for interacting with the database.
    • Controllers: Logic for handling requests and responses.
    • Routes: Defines the API endpoints.

    Steps to Build a RESTful API

    1. Set up the project: Create a new Node.js project and initialize package.json.
    2. npm init -y
    3. Install Express.js: Install Express.js and any other required packages such as body-parser.
    4. npm install express
    5. Create the main application file: Create app.js (or a similar name) to set up the Express server.
    6. Require Express: Import the Express module.
    7. const express = require(‘express’);
    8. Create an Express application: Invoke express to create an application.
    9. const app = express();
    10. Define middleware: Use middleware to parse JSON data.
    11. app.use(express.json());
    12. Define routes: Create routes for different API endpoints.
    • GET: Retrieve data.
    • app.get(‘/api/books’, (req, res) => {
    • // Logic to get all books
    • });
    • app.get(‘/api/books/:id’, (req, res) => {
    • // Logic to get a single book by ID
    • });
    • POST: Create new data.
    • app.post(‘/api/books’, (req, res) => {
    • // Logic to add a new book
    • });
    • PUT: Update existing data.
    • app.put(‘/api/books/:id’, (req, res) => {
    • // Logic to update a book
    • });
    • DELETE: Delete data.
    • app.delete(‘/api/books/:id’, (req, res) => {
    • // Logic to delete a book
    • });
    • Dynamic routes can be created using colons to define parameters.
    1. Start the server: Specify the port and start listening.
    2. const port = 3000;
    3. app.listen(port, () => {
    4. console.log(`Server is running on port ${port}`);
    5. });

    Testing APIs with Postman

    • Install Postman: Download and install Postman for testing API endpoints.
    • Create requests: Set up requests in Postman to test each route.
    • Specify the type (GET, POST, PUT, DELETE).
    • Enter the URL.
    • Include any required headers or body data.
    • Send requests and verify responses: Send the requests and verify that the responses are as expected.

    By following these steps, you can create a RESTful API using Express.js, organize the project structure, and test the API endpoints with Postman.

    Node JS Full Course 2024 | Complete Backend Development Course | Part 1

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • Laravel Project: Building a Car Management System

    Laravel Project: Building a Car Management System

    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

    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    1. 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.
    2. 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’)).
    3. 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.
    4. 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

    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    1. 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.
    2. 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’)).
    3. 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.
    4. 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

    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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:

    1. Request Entry: The request hits the public/index.php file.
    2. Bootstrapping: index.php includes vendor/autoload.php and bootstraps the Laravel application.
    3. 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.
    4. Routing: The router takes the request and matches it to a defined route.
    5. 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.
    6. Controller Action: The matched route’s controller action is executed.
    7. Response Generation: The controller action may render a view or return data.
    8. Middleware (Post-Response): If middleware is registered, the response is passed through it before being sent to the user.
    9. 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.
    Laravel 11 in 11 hours – Laravel for Beginners Full Course

    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

  • PHP Syntax, Variables, Database Insertion, and Login System Tutorial

    PHP Syntax, Variables, Database Insertion, and Login System Tutorial

    The source material offers a tutorial on PHP programming, starting with basic syntax, variables, and data types. It progresses to more advanced topics like superglobals, form handling, and database interaction using prepared statements to prevent SQL injection. The tutorial includes building a calculator and a search system as practical exercises. Arrays, constants, loops, sessions, and error handling are discussed, along with implementing an MVC pattern for better code organization. The material also teaches security practices like sanitizing data and regenerating session IDs. The focus is on creating a login and signup system with error handling and form persistence.

    PHP Study Guide

    Quiz

    1. What is a superglobal in PHP, and why are they useful?

    Superglobals are built-in variables that are always available in all scopes. They provide access to information from various sources like forms, cookies, sessions, and the server environment. They are useful because they allow developers to easily access and manipulate data throughout their PHP applications without explicitly passing them as arguments.

    2. Explain the purpose of the $_FILES superglobal.

    The $_FILES superglobal is used to retrieve information about files uploaded through an HTML form. It provides details like the file size, name, temporary location, and file type, enabling PHP to validate and handle uploaded files effectively. This allows developers to manage file uploads, check file sizes, and verify file extensions.

    3. Describe how cookies work and how the $_COOKIE superglobal is used.

    Cookies are small text files that a server embeds on a user’s computer to store information. The $_COOKIE superglobal is used in PHP to access the values stored in these cookies. Developers can retrieve information about user preferences or track user activity using cookies and the $_COOKIE superglobal.

    4. What are sessions, and how is the $_SESSION superglobal used to manage them?

    Sessions are a way to store information about a user on the server-side across multiple requests. The $_SESSION superglobal is used in PHP to store and retrieve session variables, allowing developers to maintain user-specific data and state during a browsing session. This is important for login and other user management features.

    5. What is the purpose of the concatenation operator (.) in PHP?

    The concatenation operator (.) is used to join two or more strings together in PHP. It combines variables and literal strings to create a single, unified string. Concatenation allows developers to dynamically build strings by combining different pieces of data.

    6. Explain the difference between = (assignment), == (comparison), and === (identical) operators in PHP.

    The = operator is used to assign a value to a variable. The == operator is used to compare two values for equality, without considering their data types. The === operator is used to compare two values for identity, meaning they must be equal in both value and data type.

    7. Describe what operator precedence is and how it affects the evaluation of expressions in PHP.

    Operator precedence determines the order in which operators are evaluated in a PHP expression. Operators with higher precedence are evaluated before those with lower precedence. Parentheses can be used to override the default precedence and control the order of evaluation.

    8. How do you create an if statement in PHP, and what is its purpose?

    An if statement in PHP is created using the if keyword, followed by a condition in parentheses. The code within the if statement’s curly brackets is executed only if the condition is true. if statements allow developers to execute different code blocks based on certain conditions.

    9. Explain the purpose of a for loop and how it is structured in PHP.

    A for loop in PHP is used to execute a block of code repeatedly for a specified number of times. It is structured with three parts inside the parentheses: initialization, condition, and increment/decrement. The initialization sets a starting value, the condition determines when the loop stops, and the increment/decrement changes the loop counter with each iteration.

    10. How do you start a session in PHP, and why is it important to do so?

    A session is started in PHP using the session_start() function. It’s important to start a session at the beginning of any PHP script where you intend to use session variables to store user-specific data and maintain state. By starting the session the server is able to connect all the activity of the client to a specific user ID.

    Essay Questions

    1. Discuss the importance of data validation and sanitization in PHP web applications. Explain how superglobals like $_POST and $_GET are used to retrieve user input, and describe common techniques to protect against security vulnerabilities such as SQL injection and cross-site scripting (XSS).
    2. Explain the different types of operators available in PHP, including arithmetic, assignment, comparison, logical, and string operators. Provide examples of how each type of operator is used in practical PHP code.
    3. Describe the different control structures available in PHP, such as if, else if, else, switch, for, while, and foreach. Explain how each control structure is used to control the flow of execution in a PHP script, and provide examples of real-world scenarios where each control structure would be useful.
    4. Explain the concepts of local, global, and static scope in PHP. Describe how variables are accessed within different scopes, and discuss the implications of using the global keyword.
    5. Describe the process of connecting to a database using PHP Data Objects (PDO). Explain how to prepare and execute SQL statements, bind parameters, and retrieve data from the database. Discuss the importance of using prepared statements to prevent SQL injection attacks.

    Glossary of Key Terms

    • Superglobal: Predefined variables in PHP that are always accessible, regardless of scope.
    • Cookie: A small text file that a web server stores on a user’s computer.
    • Session: A way to store information about a user on the server-side and remember it across multiple pages of a website.
    • Concatenation: The process of joining two or more strings together.
    • Operator Precedence: The order in which operators are evaluated in an expression.
    • Assignment Operator: Used to assign a value to a variable (e.g., =).
    • Comparison Operator: Used to compare two values (e.g., ==, !=, >, <).
    • Identical Operator: Used to compare two values to see if they are the same and are of the same type (e.g., ===, !==).
    • If Statement: A conditional statement that executes a block of code if a specified condition is true.
    • Else If Statement: A conditional statement that extends an if statement to execute a different block of code if the initial condition is false and a new condition is true.
    • Else Statement: A conditional statement that executes a block of code if the if condition is false.
    • For Loop: A control structure that executes a block of code a specific number of times.
    • While Loop: A control structure that repeatedly executes a block of code as long as a specified condition is true.
    • Incrementing: Increasing the value of a variable, often by one (e.g., ++).
    • Decrementing: Decreasing the value of a variable, often by one (e.g., –).
    • Control Structure: A statement that controls the flow of execution in a program.
    • Variable Scope: The region of a program where a variable can be accessed.
    • Local Scope: Variables declared within a function or block of code that are only accessible within that function or block.
    • Global Scope: Variables declared outside of any function or block, accessible throughout the script.
    • Static Scope: A static variable retains its value between function calls.
    • Constant: A value that cannot be changed during the execution of a script.
    • Database: A structured collection of data stored in a computer system.
    • SQL: Structured Query Language, a standard language for managing and manipulating databases.
    • Data Type: The type of data that can be stored in a variable or database column (e.g., integer, string, date).
    • Varchar: A variable-length string data type in databases.
    • Integer: A whole number without any fractional part.
    • Float: A number that contains a decimal point
    • Signed/Unsigned: Specifies whether an integer data type can store negative values (signed) or only positive values (unsigned).
    • Auto-Increment: A feature in databases that automatically assigns a unique, incrementing value to a column, typically used for primary keys.
    • Primary Key: A column in a database table that uniquely identifies each row.
    • Foreign Key: A column in a database table that refers to the primary key of another table, establishing a relationship between the two tables.
    • SQL Injection: A security vulnerability where malicious SQL code is inserted into a database query.
    • Hash: A one-way function that converts data into a fixed-size string of characters, used for security purposes.
    • Salt: A random string added to a password before hashing to increase security.
    • PDO (PHP Data Objects): A PHP extension that provides a consistent interface for accessing different databases.
    • DSN (Data Source Name): A string that contains the information required to connect to a database.
    • CRUD: An acronym referring to the basic database operations: Create, Read, Update, and Delete.
    • Model: A class or component responsible for interacting with the data storage, such as a database.
    • View: The part of an application that is responsible for presenting data to the user.
    • Controller: A class or component that handles user requests and interacts with the model and view to generate a response.

    PHP Fundamentals and Database Interaction Overview

    Okay, I have reviewed the provided text and created a briefing document summarizing the key themes and ideas.

    Briefing Document: PHP Fundamentals and Database Interaction

    Document Purpose: To provide a consolidated overview of PHP concepts covered in the provided source material, focusing on superglobals, operators, control structures, functions, data types for databases, SQL operations, sessions, hashing, and basic MVC principles with error handling.

    I. Superglobals:

    • Definition: Superglobals are built-in variables that are always available in all scopes.
    • Examples:$_FILES: Used to grab information about files uploaded through an HTML form. “Using this super Global here just kind of like allow for us to grab information about files that the User submitted using a HTML form” This is useful for file size checks and extension validation for security.
    • $_COOKIE: Used to store or retrieve information from cookies stored on the user’s computer.
    • $_SESSION: Used to store or retrieve information from session variables, which are stored on the server. Example: “I could for example create a dollar signore session and inside the bracket I’m going to make sure to include a name for this session variable here so I could call this one username”. Sessions are useful for storing user-specific data like usernames.
    • $_ENV: Contains environment variables, which are sensitive data not meant to be accessible to users or other environments. “Environment variables are essentially very sensitive data that you want to have inside the particular environment that the user is working in so you know data that should not be accessible to either the user or other environments”
    • $_SERVER and $_GET are to be discussed in later videos.

    II. Operators:

    • String Operators: Used to concatenate strings. The . operator is used for concatenation: variable C = variable a . ” ” . variable b;.
    • Arithmetic Operators: Basic mathematical operators like +, -, *, /, % (modulo), and ** (exponentiation).
    • Operator precedence can be controlled using parentheses. Example: (1 + 2) * 4.
    • Assignment Operators: Assign values to variables. = assigns a value. +=, -=, *=, /=, etc., are shorthand for performing an operation and assigning the result back to the variable. Example: variable a += 4 is equivalent to variable a = variable a + 4.
    • Comparison Operators: Used to compare values.
    • ==: Checks if two values are equal (without considering data type).
    • ===: Checks if two values are equal and of the same data type.
    • !=: Checks if two values are not equal.
    • !==: Checks if two values are not equal or not of the same data type.
    • <, >, <=, >=: Less than, greater than, less than or equal to, greater than or equal to.
    • Logical Operators: Used to combine multiple conditions.
    • && (AND): Both conditions must be true.
    • || (OR): At least one condition must be true.
    • Alternative symbols for AND and OR: and , or (less common).
    • Incrementing/Decrementing Operators: Increment (++) or decrement (–) a variable’s value. variable a++ increments after the current expression is evaluated, while ++variable a increments before.

    III. Control Structures:

    • Conditional Statements: Used to execute different blocks of code based on conditions.
    • if: Executes a block of code if a condition is true.
    • else if: Checks another condition if the previous if condition is false. “the else if statement basically is just a chain that we chain behind our if statement and says okay so if the first if condition is not met then jump down and check for the next one in the chain list”
    • else: Executes a block of code if none of the previous if or else if conditions are true.
    • Switch Statements: Provides an alternative to multiple if/else if statements, especially when comparing a single variable against multiple possible values.
    • Match (PHP 8): A newer feature similar to switch, providing a more concise syntax for value matching.
    • Loops: Used to repeat a block of code multiple times. “a loop is a way for us to spin out a blocker code multiple times by just writing one block of code”
    • for: Repeats a block of code a specific number of times. Requires initialization, condition, and increment/decrement expressions. “a for Loop is a very basic way for us to spit something out depending on numbers”
    • while: Repeats a block of code as long as a condition is true. “as long as this variable here is equal to true then I want to Loop something out”

    IV. Functions:

    • Definition: Reusable blocks of code. “A function is essentially just a blocker code that performs a specific task and then if you want to perform the same task that function that perform then you simply go and reuse the code”
    • Scope:Local Scope: Variables declared inside a function are only accessible within that function. “as soon as we declare a variable inside a function it is locally scoped within that function so we can only access it within my function”
    • Global Scope: Variables declared outside functions are accessible globally, but require special handling to be used inside functions (e.g., using the global keyword or passing as parameters).
    • Static Variables: Static variables inside functions retain their value between function calls.
    • Parameters and Arguments: Data can be passed into functions as parameters, allowing functions to operate on different data.
    • Return Values: Functions can return values, which can then be used elsewhere in the code.

    V. Constants:

    • Definition: Named values that cannot be changed after they are defined. Defined using the define() function. “When you create a constant that you use capitalized lettering because it shows other programmers that this is a constant so it’s just kind of a visual indicator for other programs to know that this is a constant”
    • Constants are in the global scope.
    • Good practice to define all constants at the top of the script.

    VI. Database Interaction (MySQL):

    • Data Types: Used to define the type of data that can be stored in a database column. “each column inside a table needs to be defined with a data type in order to tell our database what kind of data do we expect to be put inside this column here”
    • INT: Integer numbers. A common device width to define is 11. “a typical thing that we do when it comes to just making websites is we just Define 11 in here as a default”
    • BIGINT: Large integer numbers.
    • FLOAT: Floating-point (decimal) numbers.
    • DOUBLE: High-precision floating-point numbers.
    • VARCHAR(size): Variable-length strings. The size parameter specifies the maximum number of characters.
    • TEXT: Large text strings. ” using text for for example comments and blog post and that kind of thing is kind of what we need to use this data type for”
    • DATE: Dates (YYYY-MM-DD).
    • DATETIME: Dates and times (YYYY-MM-DD HH:MM:SS).
    • Signed and Unsigned: For integer types, SIGNED allows negative values, while UNSIGNED only allows positive values, effectively doubling the maximum positive value that can be stored.
    • SQL Operations:CREATE TABLE: Creates a new table.
    • INSERT INTO: Inserts data into a table.
    • SELECT: Retrieves data from a table.
    • UPDATE: Modifies existing data in a table.
    • DELETE FROM: Deletes data from a table.
    • Primary Key (ID): A unique identifier for each row in a table. “basically whenever we have a table we want to make sure that we can find data inside this table very easily which means that having a ID for all the different rows we have inside the table is going to make it a lot easier to find it”
    • AUTO_INCREMENT: Automatically assigns a unique, incrementing value to the ID column for each new row. “Auto increment which is a type of column that’s going to automatically increment or increase the number one so we can easily find things using ID so that’s just for example to make it easier to find different posts inside our website”
    • Important: Do not manually change primary key IDs after they have been assigned as this will break relationships with data in other tables.
    • Database Connection (PDO): PHP Data Objects (PDO) is a consistent way to access databases. “PHP data objects is a way for us to create a database object when we want to connect to a database so basically we turn the connection into a object that we can use inside our phsp code and just refer to that object whenever we want to connect to a database”
    • Data Source Name (DSN): A string that specifies the database driver, host, and database name.
    • Try/Catch Blocks: Use try/catch blocks to handle database connection errors.
    • Prepared Statements: “prepared statement is going to go in and and just pre compile the query we have so so therefore the code is going to execute a lot faster because we’re basically telling it hey in the future we we need you to run this query but we are just not going to insert the data inside just yet we’re going to do that later which means that it’s going to pre compile everything and have it all prepared and ready when we actually finally do pass in all the bits of data” Helps prevent SQL injection attacks.

    VII. Sessions:

    • Definition: A way to store information about a user across multiple pages. “Sessions are basically information that you store on a user that has to be remembered across multiple pages”
    • session_start(): Starts a session. Must be called at the very beginning of the script. “So right now we don’t have a session going on inside ex example so we could actually go in and copy paste this information paste it over here just to make sure we have a session started on both pages and then with this we’re now going to go back inside the website refresh it”
    • $_SESSION: A superglobal array used to store and retrieve session variables.
    • Session ID Cookie: Stored on the user’s browser to identify the session.

    VIII. Hashing:

    • Definition: One-way algorithm that converts data into a fixed-length string. Used to securely store passwords. “hashing is whenever we perform a oneway hashing algorithm on a plain piece of text for example a password and then we basically convert it into a fixed length string that you can’t really look at and tell what exactly is this supposed to be”
    • Hashing algorithms are designed to be irreversible and computationally expensive.
    • Salt: A random string added to the data before hashing to increase security. “Essentially a salt is a random string of text that is going to be included inside the data that you provide the hashing algorithm so it’s going to mix the salt together with the text that you provided it and then it’s going to Hash it afterward to create a more unique and even harder to crack hashing algorithm to make it even stronger”
    • Pepper: A secret string added to the data before hashing (similar to a salt, but not randomly generated). “And essentially we’re just going in and we’ll combine in these three pieces of data up here so we have the sensitive data that the user gave us inside whatever input we have inside the website uh we do also have a piece of data called a salt and then we also do have our pepper”

    IX. Basic MVC (Model-View-Controller) Principles & Error Handling

    • Structure: The material references separating code into different files (e.g., including a “hash_password.in.php” file in an “includes” folder). It also hints at the idea of a Controller component handling user input and calling on Models (presumably for database interaction).
    • Error Handling: The code demonstrates basic error handling, such as validating user input and using if statements to check for errors. It also demonstrates a basic error handling setup where an empty array is used to store error messages that can then be displayed to the user.

    Key Takeaways:

    • PHP provides a variety of superglobals for accessing different types of data.
    • Understanding operators is essential for manipulating data and creating complex logic.
    • Control structures are critical for controlling the flow of execution in PHP scripts.
    • Functions are essential for code reusability and organization.
    • Securely storing passwords using hashing with salts is a must.
    • Basic MVC ideas such as utilizing controller functions can help to break code up and make it more maintainable.
    • Proper database interaction requires understanding data types and SQL operations.

    This document provides a high-level summary. Deeper dives into each of these topics can be found in the original source material.

    PHP Superglobals, Operators, Control Structures, and Variable Scope

    Superglobals, Forms, and Data Handling

    • What are superglobals in PHP, and why are they important to understand?
    • Superglobals are built-in variables that are always available in all scopes of a PHP script. They provide access to information about the server, the environment, and the user. Understanding them is important because they are essential for handling data submitted through forms ($_POST, $_GET, $_FILES), managing sessions and cookies ($_SESSION, $_COOKIE), accessing server information ($_SERVER), and more. They act as the primary interface between the PHP script and the external world.
    • How can I prevent users from crashing my website by uploading very large files?
    • PHP provides the $_FILES superglobal, which contains information about uploaded files, including their size. You can use this information to validate the file size before saving the file to the server. By checking if the file size exceeds a certain limit, you can prevent excessively large files from being uploaded, thus protecting your website from crashes or performance issues.
    • What are cookies and sessions, and how are they managed in PHP?
    • Cookies are small files that a server embeds on a user’s computer to store information. PHP provides the $_COOKIE superglobal to access and manage cookies. Sessions are a server-side way to store information about a user across multiple requests. PHP uses the $_SESSION superglobal to access and modify session variables. You must call session_start() at the beginning of each script where you want to use sessions. Closing the browser typically ends the session, though this can be configured.
    • How can I use PHP to retrieve data submitted through an HTML form?
    • When a user submits an HTML form, the data is sent to the server using either the GET or POST method. In PHP, you can access this data using the $_GET and $_POST superglobals, respectively. For example, if a form has a field named “username,” you can access the submitted value using $_POST[‘username’]. Always sanitize and validate user input to prevent security vulnerabilities.
    • What are operators in PHP, and what are some common types?
    • Operators are symbols or keywords that perform operations on one or more values. Common types include:
    • String Operators: Used to concatenate strings (e.g., .).
    • Arithmetic Operators: Used for mathematical calculations (e.g., +, -, *, /, %, **).
    • Assignment Operators: Used to assign values to variables (e.g., =, +=, -=, *=, /=).
    • Comparison Operators: Used to compare values (e.g., ==, ===, !=, !==, <, >, <=, >=).
    • Logical Operators: Used to combine or modify boolean expressions (e.g., && (and), || (or), ! (not)).
    • Incrementing/Decrementing Operators: Used to increase or decrease a number (++, –).
    • What are control structures in PHP, and why are they important?
    • Control structures are language constructs that control the flow of execution in a PHP script. They allow you to make decisions, repeat code blocks, and execute different code paths based on conditions. They are fundamental for creating dynamic and interactive websites. Key examples are:
    • If/Else/Elseif statements: Conditional execution of code blocks.
    • Switch statement: Multi-way branching based on a value.
    • Loops: Repeated execution of code blocks (e.g., for, while, foreach).
    • What are the key differences between the local, global, and static variable scopes in PHP?
    • Local Scope: Variables declared within a function have local scope and are only accessible inside that function.
    • Global Scope: Variables declared outside functions have global scope and are accessible throughout the script, except inside functions, unless explicitly accessed using the global keyword or the $GLOBALS superglobal.
    • Static Scope: Static variables declared within a function retain their value between function calls. They are initialized only once and persist across multiple invocations of the function.
    • What are constants in PHP, and how do they differ from variables?
    • Constants are named values that cannot be changed after they are defined. They are defined using the define() function or the const keyword (in PHP 5.6+). Constants are always in the global scope and can be accessed from anywhere in the script, including inside functions. Unlike variables, constants do not require a dollar sign ($) prefix. It is convention to name constants using capitalized letters to distinguish them from variables. Constants are useful for storing values that should not be modified, such as configuration settings or mathematical constants (e.g., PI).

    PHP Syntax Fundamentals

    PHP syntax dictates how to write PHP code without generating errors. Here’s an overview of key aspects:

    • Opening and Closing Tags: PHP code must be enclosed within opening and closing tags, such as <?php and ?>. The PHP parser searches for these tags to identify PHP code within a page. You can embed PHP code directly within HTML using these tags.
    • Semicolons: Each PHP statement should end with a semicolon (;), which signals the end of the statement to the PHP parser. However, the closing PHP tag ?> automatically implies a semicolon, so the last statement before the closing tag doesn’t strictly need one. It is recommended to include semicolons after every statement for consistency and to prevent errors.
    • Pure PHP Files: When a file contains only PHP code, the closing tag can be omitted. This is the recommended practice to avoid potential issues caused by accidental whitespace or new lines after the closing tag.
    • Embedding PHP in HTML: There are two ways to embed PHP inside HTML:
    • You can directly embed PHP code within HTML tags, echoing HTML elements from within PHP code.
    • Alternatively, you can split up a condition using opening and closing PHP tags around the beginning and closing of the statement to allow HTML to be written as HTML.
    • Comments: It is good practice to use comments in PHP code to explain what the code does. Comments are not outputted in the browser.
    • Single-line comments can be created using two forward slashes (//).
    • Multi-line comments can be created by enclosing the comment between /* and */.

    PHP Variables: Declaration, Data Types, and Superglobals

    Variables in PHP are named memory locations that store data. They are essentially labeled boxes that hold data, making it easier to refer to and handle data within code. In PHP, a variable is declared by using a dollar sign ($) followed by the variable name.

    Here’s a detailed overview:

    • Declaring Variables: To declare a variable, a dollar sign ($) is used, followed by the chosen name for the variable. For example, $name declares a variable named “name”.
    • Variable Names:
    • Variable names must start with a letter or an underscore.
    • After the first character, variable names can contain letters, numbers, or underscores.
    • It’s customary to begin variable names with a non-capitalized letter, and subsequent words in the name should start with a capitalized letter (e.g., $fullName).
    • Assigning Data: Variables are assigned data using the assignment operator (=). For example, $name = “Danny Crossing”; assigns the string “Danny Crossing” to the variable $name.
    • Referring to Variables: To access the data stored in a variable, refer to the variable by its name, including the dollar sign. For example, echo $name; would output the value of the $name variable.
    • Variable assignment: It is possible to assign the value of one variable to another. For example, $test = $name; will assign the value of the variable $name to the variable $test.

    Data types that can be stored in variables:

    • Scalar Types: These variables contain only one value.
    • String: Represents a piece of text. For example, $string = “Daniel”;.
    • Integer (int): Represents a whole number. For example, $number = 123;. Note that integers should not be enclosed in double quotes; otherwise, they will be interpreted as strings.
    • Float: Represents a number with decimal points. For example, $float = 256.78;.
    • Boolean (bool): Represents a true or false value. The values can be true or false. In certain contexts, 1 is evaluated as true and 0 as false.
    • Array Type: Arrays store multiple pieces of data within a single variable. For example, $names = array(“Daniel”, “Bella”, “Feta”);.
    • Arrays can be created using the array() construct or with square brackets []. The square bracket syntax requires PHP version 5.4 or higher.
    • Object Type: An object is a data type.
    • Superglobals: Superglobals are built-in variables that are always accessible, regardless of scope. Superglobals are accessed using a dollar sign $ followed by an underscore _ and a capitalized word. Examples include:
    • $_SERVER: Contains information about the server environment.
    • $_GET: Used to collect data from the URL.
    • $_POST: Used to submit data.
    • $_REQUEST: Used to collect data after form submission.
    • $_FILES: Used to retrieve data about files uploaded to the server.
    • $_COOKIE: Used to retrieve values from cookies.
    • $_SESSION: Used to manage user session data.
    • $_ENV: Used to access environment variables.

    PHP Superglobals: Understanding and Usage

    Superglobals are built-in variables in PHP that are always accessible regardless of the scope. Unlike regular variables, which may have limited accessibility based on their scope (e.g., local variables within a function), superglobals can be accessed from anywhere in the code.

    Key aspects of superglobals include:

    • They are predefined variables within the PHP language.
    • They are automatically available without needing to be explicitly declared or defined.
    • They can be accessed from any part of a script, including within functions and classes.
    • Superglobals are referenced by creating the dollar sign $ but then creating a underscore _ followed by a capitalized word.

    Here’s a list of common superglobals in PHP:

    • $_SERVER: This superglobal holds information about the server environment, such as server names, document roots, and request methods. For instance, $_SERVER[‘DOCUMENT_ROOT’] can provide the root directory of the current script.
    • $_GET: Used for collecting data submitted via the URL. Data is appended to the URL as name-value pairs.
    • $_POST: Used for collecting data submitted through HTML forms using the POST method. This method is commonly used for submitting sensitive or large amounts of data.
    • $_FILES: Used for accessing data related to files uploaded to the server. It allows you to retrieve information such as file size, name, and extension.
    • $_COOKIE: Used for retrieving values stored in cookies. Cookies are small files that the server embeds on the user’s computer to store information about their activities.
    • $_SESSION: Used for managing user session data. Sessions allow you to store information about a user that persists across multiple pages of a website.
    • $_ENV: Used to access environment variables. Environment variables are often used to store sensitive data that should not be directly accessible to users.
    • $_REQUEST: Used to collect data after HTML form submission.

    HTML Forms: Data Collection, Submission, and Security

    Here’s information about HTML forms, based on the provided sources:

    • HTML forms are used to collect data from users.
    • Forms can include various input elements like text fields, drop-downs, and buttons.
    • Key attributes of the <form> tag:
    • action: Specifies where the form data should be sent for processing. This is typically a URL or a PHP file.
    • method: Defines the HTTP method used to submit the form data. Common methods are GET and POST.
    • Form Input Attributes:
    • name: A reference name is needed so the data can be grabbed once the data is sent to the next page. When grabbing data using the name attribute, you grab whatever the user input.
    • value: With drop-down menus, the data selected when referencing the name will be the data inside the value attribute.
    • Labels: Use labels to improve form accessibility, especially for users with disabilities.
    • Submitting Data:
    • GET Method: Submits data via the URL, making it visible in the address bar. It is typically used to get data from a database.
    • POST Method: Submits data in the body of the HTTP request, so it is not visible in the URL. It is typically used to submit data to a website or database. It’s also useful for submitting more sensitive data.
    • Superglobals: $_POST is a PHP superglobal used to collect data from forms submitted with the POST method.
    • HTML Special Characters: When having anything shown inside the browser using PHP, escaping it using HTML special characters is important to prevent users from injecting code inside the browser. There are a couple of different ways to sanitize data, depending on the purpose.
    • HTML Entities: HTML entities can be used to sanitize data.
    • Form Validation:
    • Required Attribute: Though it can be added to form inputs, it is not secure to rely on HTML, CSS, or JavaScript for security.
    • PHP for Security: Server-side security (using PHP) is essential for validating and sanitizing user inputs to prevent malicious attacks.
    • Error Handling: When creating any sort of error handlers inside a script, it can be checked if any of the inputs have been left empty when the user submitted the form. You don’t want the user to be able to submit the form if there is no data to submit. It needs to require that they submit all the data.
    • Action Attribute: When submitting a form and sending the data to the same page that the user is on, one way to do it is to open PHP tags inside the action, then include the server super global and target PHP self. It is important to note that this is prone to hacking.
    • File Uploads: The $_FILES superglobal is used when a HTML form allows users to submit files.

    Databases and Queries: A Quick Reference

    Here’s an overview of databases and queries, based on the provided sources:

    • Databases:
    • A database is used to save user information, and is used whenever a website has to remember something.
    • A database is made up of tables where similar information is gathered. Tables give the data structure.
    • Each piece of data corresponds to a column. Each entry (or data) corresponds to a row.
    • Relational Database Management System (RDBMS):
    • There are many different types of database systems, called RDBMS.
    • MySQL is a commonly used database system, especially with PHP. MySQL servers are not the same as MySQL PHP functions.
    • Setting up a Database
    • XAMPP includes both Apache and MySQL servers. The Apache server is the web server where PHP runs. The MySQL server is the actual database server.
    • To manage a database, use a dashboard like PHPMyAdmin.
    • To create a database, select ‘databases’ and type in a name.
    • SQL:
    • SQL (Structured Query Language) is used to manipulate databases. With SQL, you can create tables, insert data, select data, or delete data.
    • To use SQL, make sure the correct database is selected. Then, click the SQL tab.
    • There are typical SQL lines of code that are used repeatedly.
    • It is useful to practice SQL directly inside a database.
    • Data Types:
    • When inserting data, each column inside a table must be defined with a data type. This tells the database what kind of data to expect.
    • Common data types include INT for integers, VARCHAR for character strings, DATE, and DATETIME.
    • INT stores numbers. BIGINT stores larger numbers.
    • VARCHAR stores strings. You need to define a parameter for the length of the string.
    • TEXT stores long text.
    • DATE stores year, month, and day. DATETIME stores date and time.
    • Queries:
    • A query is a request for data from a database.
    • CREATE TABLE: Used to create a new table in the database.
    • INSERT INTO: Used to insert data into a table.
    • SELECT: Used to select data from a table.
    • UPDATE: Used to modify existing data in a table.
    • DELETE FROM: Used to delete data from a table.
    • Prepared Statements:
    • Prepared statements prevent users from writing SQL code directly inside an input.
    • The query (SQL code) is sent to the database first. Then, data submitted by the user is bound and sent to the database afterward. Because the query is separate from the data, SQL code will not impact the query.
    • Prepared statements can use either named parameters or non-named parameters.
    • With non-named parameters, user data is replaced with question marks.
    • With named parameters, each piece of user data is replaced with a name. With name parameters, the order does not matter.
    • Joins:
    • A join is used to select data from two or more tables at the same time.
    • Types of joins include INNER JOIN, LEFT JOIN, and RIGHT JOIN.
    • With INNER JOIN, data is selected from two tables that have matching data.
    • With LEFT JOIN, the table on the left is the primary table. Even if a user does not have a comment, all the users will still be shown.
    • With RIGHT JOIN, the comments on the right side are the focus.
    🔥 PHP Full Course 2025 – Learn PHP from Scratch! 🚀
    PHP Mastery Course: From Basics to Advanced with Practical Projects & Exercises in One Video.

    The Original Text

    so welcome to a new version of my PHP course now in this video we’re going to talk a bit about what exactly PHP is and what you’re going to learn in this course here and why it’s going to be a little bit better structured than the previous one I have on the channel so let’s go and talk a bit about what exactly this course is and who it is made for now here at the beginning it is going to be a beginner friendly course so to speak my main goal is to make sure that people has never done PHP before and might find a little bit intimidating because they’ve never done a programming language before will be able to get into this course here and don’t find it overwhelming so that is going to be my main priority as we going on with these lessons here it is quite normal to find PHP intimidating if this is your first programming language so don’t be scared that this is going to be overwhelming cuz I will try to make it as understandable as possible for people who has never done any sort of programming before with that said of course this course is going to get more and more complicated and more and more advanced as we go on but here in the beginning it is going to be very beginner friendly so with that said let’s go and talk a bit about what exactly PHP is and what you can use it for now PHP stands for hypertex preprocessor actually it stands for PHP hypotext pre-processor it is what you call a recursive acronym when you have the word itself inside its own spelling now PHP is a language that are used mainly for making websites but it can be used for other things as well like for example creating a desktop application if you know how to do it but it is something that is more commonly used for web developments one of the reasons it’s so easy to use for web development is because you can very easily embed it into the HTML when you start creating a website using HTML and CSS and it is also a very easy language to learn compared to many other programming languages out there and one of the things about PHP you may not know is that is actually considered a serers side language meaning that the phsp you’re going to program is going to run on the server of your website but not actually inside the client which is inside the browser so languages such as HTML CSS and JavaScript which actually runs inside the browser these languages run differently than PHP which is actually running on the server instead this means that when you’re writing PHP inside your website you can’t actually see the code inside the browser which you can when it comes to for example HTML CSS and JavaScript so PHP is completely hidden since it runs in the server instead so with all that said let’s go and talk about the elephant in the room is PHP dead because when it comes to websites on the internet right now currently in 2023 we have more than 78% of websites out there that we know of that are using PHP as their backend language this means that PHP is currently massively dominating when it comes to the backend languages that we use for websites out there today but one of the reasons I do often hear that PHP is a dead language and you shouldn’t use it anymore has a lot to do with the fact that PHP is only used mainly for web development whereas other languages such as python is used for all sorts of things including you can also use Python for web development so if you were to take the Python programming language and say okay how many people are using python nowadays versus people who are using phsp then python is going to have much higher numbers however these are actually not the numbers you should look at since we need to look at how many people are using python 4 when it comes to web development versus people who use PHP for web development and when it comes to this PHP is much much much higher numbers than when it comes to python it pretty much BS down to the fact that some people on the internet don’t like PHP because it’s more specifically suited towards web development whereas a language like python can be used for many other things besides web developments so if you’re sitting there you want to learn specifically web development then PHP is by far the language that I would recommend using when it comes to web development of course python is also an amazing language to use for web development if you want to use D Jango as a framework but PHP is just more the more popularly used language when it comes to specifically web development so just to mention a couple of websites that do actually use PHP we do have Facebook which uses a version of phsp we do also have Wikipedia canvas is also a very popular website that uses PHP and then we do also have WordPress which is not really a website but more of a Content management system which is also the most popular content management system out there today so if you plan on using WordPress at some point in the future I do recommend that you learn PHP since it is what they use when it comes to plugins and just the the WordPress CMS system in itself learning PHP is definitely something that I highly recommend if you’re just planning on going into web development as a web developer but now let’s go and talk a bit about Theory versus practice when it comes to implementing PHP inside your website because when it comes to learning any sort of programming language like for example PHP then things will be a little bit slow in the beginning it is just a very typical thing when you learn a new programming language that you have to learn all the theory first and then later on you start getting into some more practical examples so you can actually see oh okay so that’s how we use it inside for example our website I will try to include as many examples as I can as we go throughout this series but it is important to know that there will be a lot of theory here in the beginning so you don’t need to worry too much about it if you’re looking at these lessons at the beginning and thinking to yourself okay so I can’t really see how this code that we’re learning has to be used inside a real website just keep following the lessons at at some point you will get to a point where you get a realization of oh so this is how we need to use everything everything that we learned inside a real website but now let’s go and talk a bit about how I am going to approach this course here it is my experience that people become very easily overwhelmed when it comes to teaching a backend programming language like PHP so it’s important to split things up into multiple lessons to make sure that people can digest it a lot easier that being said when it comes to teaching PHP you can roughly divide PHP into three different categories when it comes to learning PHP as a language you have the actual PHP language which is just learning PHP and how to write it and how to Output things inside your website you know just plain PHP programming and how to actually write things that do something inside your website then after learning PHP you’re going to start learning about databases and how to actually manipulate databases by pulling out data or inserting data inside the database a database is a place where we store information for example if you want your website to remember things about your users and then the last thing you need to learn about is security Now security is a huge when it comes to PHP since you are essentially manipulating data from the user and a lot of that data is going to be sensitive data so it is important to take security very serious when it comes to PHP because it is something that is crucial to learning PHP and you can’t learn PHP and just go into it with the mindset of okay so security is just kind of like like an offside thing security is something you need to do and it is something you need to look into at some point and it is something that we will start looking into a little bit further into the course later near the end I do want to point out here that I do know a lot of people think it’s very important that you teach all security at the beginning when a person starts learning PHP but in my experience a lot of people will get overwhelmed if you teach everything when it comes to security at the same time as you also try to teach a complete beginner the basics of PHP so in order to digest things a lot easier we’re just going to focus on phsp then later on we’re going to start learning how you need to implement security into the PHP you already learned of course there is going to be moments where we can’t avoid talking about security and when those moments come we will of course talk about some security but any security that isn’t directly related to any sort of lesson that we’re learning about is not something we’re going to talk about until later on so with that said let’s talk about some frequently asked questions since I do want to answer some of the questions I have received in the past in my comment section will I include documentation for each lesson yes there will be documentation for each of the lessons that I teach inside the description of the video so if you want to Deep dive a little bit further into the lesson that we’re learning about then you can of course look into that documentation and learn a little bit further about what we’re learning will we do procedural or objectoriented PHP programming now here at the beginning we will focus on doing procedural PHP programming since I do know that it’s easier to get people into PHP when it comes to procedural programming later on in the course we will of course Deep dive a little bit further into objectoriented PHP programming but when it comes to just PHP here at the beginning like I said it’s going to be procedural and just to mention it for any beginners watching this you don’t need to look up object oriented PHP just focus on procedural PHP and learning that and then later on we will get to do objectoriented PHP and talk a bit about what exactly it is will I cover a framework like larell now something people may not know about especially if you are a beginner when it comes to learning any sort of language like HTML CSS JavaScript PHP python whatever you’re trying to learn there will always B Frameworks now Frameworks is a way for us to follow a well framework in order to build things much easier much faster and just kind of like to automate some things for us and a lot of things when it comes to especially PHP and Security will actually be automated when it comes to doing something using larell for building PHP applications however since this is going to be a phsp beginner course and I do think it’s important that people shouldn’t even look at a framework until they learned the basics of PHP we will not cover any sort of Frameworks in this course here at most it is going to be a separate course at some point in the future but for now it is not going to be part of this course here so with that said I hope you enjoyed this little introduction here in the next episode we’ll talk about how to set up PHP and how to install a local server on your computer since we did talk about PHP being a serers side language so we do need to have a server in order to actually write PHP inside a website and again just to mention this for the beginners here you don’t need to freak out when I say you need to install a local server on computer it is something that takes literally a minute to do and it’s not something that’s going to break your computer anything it is something that everyone that does web development at some point will have to do when they start learning how to make websites so with that said I hope you enjoyed this little video and I’ll see you guys in the next [Music] [Music] one so in order to set up a website using PHP we have to install what is called a local server and there’s a lot of different software out there in the internet that you can get in order to install a local server on your computer I do know that some people are a little bit scared when it comes to installing a server on your computer and I just want to point out that there’s nothing to be scared of everything is going to be fine and you’re not going to install any sort of viruses anything setting up a server is something that is actually quite easy to do and anyone that does websites do it quite frequently so it’s not something that new people should be scared of doing it’s something that takes a couple of minutes to do and then you have something running on your computer so when it comes to installing a server there’s many different servers you can choose from you have lamp Vamp examp limp there’s many different kinds of servers I did also hear about something called Ducker from one of my subscribers in the last video so it’s just interesting to see that there’s so many different ways to do it what we’re going to use however is a server called exam and the argument I have for using exam is that it’s easy to set up and it’s the one I’ve been using for many years I’m just really comfortable using xam so going inside your computer you can see that we have this website here that I just found called Apache friends.org I’ll go ahe and leave a link to it so you can actually see it on screen here basically this is just going to be a piece of software that you’re going to download that we’re going to start and then it’s going to run our server on our computer this means that we can actually run a website that is using PHP on our computer without having to upload our website to the Internet so this makes it very easy to just work on our website offline on our computer just like if you were to just make make a HTML website as you can see we have a couple of different versions We can install in here we have for Windows Linux and mac and you can also see what version we’re going to install in this case here this is going to be release 8.2.0 which is the PHP version that we’re going to run on This Server here so once you figured out what operating system you’re sitting on I I bet you probably know already you’re going to go and click the button for that one so I’m going to click windows then it’s going to install the program for you and if it doesn’t you’re just going to go and click up here where it says click here then we’re going to accept the privacy up and then we’re just going to go and download the latest version which is 8.2.0 so we have the latest version of PHP here so I’m going to go and download it now once you have it downloaded you’re just going to go and double click it so we can make sure to install it on our computer and it is important that you take note of where exactly you are installing it since we will have to go in and do a couple of changes to it now if you do get a popup like this don’t worry too much about it since this is only going to be relevant if we were to install this inside our program files inside our main drive so with that I’m just going to click okay and then we’re going to choose where we want to install this program so we’re going to make sure all these are ticked on and then I’m going to click next then I’m going to select where I want to install this now as you can see I have it inside my C drive but not inside my program file so I can just go and install it directly on the C drive so I’m just going to go and do that click next then I’m going to choose a language in this case it’s going to be English and then we can just go ahead and make it set up our program on our computer so it’s just going to unpack and install now if you do insist that you want to install this inside your program files then I do have a Link in the description where you can go in and actually make sure there’s no warnings popping up when you try to run this program inside the program files but like I said if you just install it directly inside the C drive like I did here we’re not going to have any sort of issues now once you have it installed it’s going to ask if you want to start the control panel now if you want to wait with later for now let’s just go ahead and not do that because I do want to show where exactly this is installed so you can just open it up from inside your computer so with that I’m going to click finish and then you’re going to go into a installed xamp which is inside in my case the C drive so I’m going to go into this PC inside my C drive then I’m going to go down to the bottom here and then you can see I have xamp inside the XM folder we’re going to have the actual server files which means that we can scroll down to the bottom and actually run this control panel that we were just asked about so we can just go and click the xamp dash contr control.exe open it up and then you can see we have a little software in here now the important thing for you to know about in here is that we have two services that we need in order to actually get PHP working one is going to be the Apache server which is the one that we need in order to actually run PHP and the second one is the MySQL server which is used in order to get access to our database so what I can do is I can start these two and then you can see we have them running another tip that I have for you is to make sure that you go down and actually dock this at the bottom since this is the program you’re going to have to start every single time you need to start working on your website this means that we need to go down and actually dock it or pin it to your taskbar so you have easy access to it next time with this running we now need to set up our website inside This Server here which is very easy to do so we’re going to go back inside our folder where we have XM installed and then you’re going to go up to the top here and then you’re going to go inside the folder called HT docs now in here you’re going to find a bunch of files and these are just mainly to welcome you into the XM software so if I were to go inside my browser here and inside the URL I’m going to type Local Host and then you can see we get this little website here and this is basically what we see with these files inside the HT docs folder this is basically what this is so we don’t really need to have this so what I can do is I can go back inside our folder and then I just go and delete all the files that we have in here now the important thing for you to know about this folder here is that this is going to be the place where you start creating your websites every time you want to create a new website inside This Server here so what we can do is we can go and create a new root folder so I’m going to right click and say I want to create a new folder I can call this one my website just to give it some kind of name of course you’re more than welcome to call whatever you want it to be but in my case I’m just going to call it my website and now what you’re going to notice is that inside the browser I can go back inside and type Local Host and then you can see we get a list of all the different websites that I have inside this folder here this means that if I were to create a second website go in here create a second one my second website then you can see if I were to refresh in here we now have a new website that we can open up using this server here so if you were to click my website you can now see that we have this website open so going inside your preferred editor my case this is going to be Visual Studio code I’m going to go ahead and create my first file which means that I’m going to save this file inside this folder that I just created a very good advice for you is to go inside and actually dock the HD docs folder on the side over here so have quick access to it so what I can do is I can go ahead and go inside find xamp take my HT docs folder and dock it over here on the side so in this sort of way I have quick access to it whenever I have to open my folders here so I can click it go in here let’s just go and delete that second website since we don’t actually need it I’m going to go inside my root folder and create a index.php now this is the moment where some people are going to get confused if it came directly from my HTML course because when it comes to phsp we want to make sure that instead of creating HTML files we create a PHP file the main difference here is that we actually allow for PHP to be run inside these files here you can still write HTML just like you can before so you don’t need to freak out about your website breaking or anything like that or not being able to write HTML inside these files just because it’s called PHP and the same thing goes if you have an existing website that you want to convert into a PHP website you can just take all the different HTML files that you have and just change the extension from HTML to PHP on those and it’s going to work inside your server and it’s not going to break anything by the way I should say that because some people do worry that it is going to break something so I have to say it with this file here I’m going to save it and then you can see we have this front page here so if I were to go back inside my website I can refresh my website and then you can see we get a completely blank page and that’s because right now we have the index file running inside our server now depending on the editor you’re using because in some cases the editor is just going to work straight away but if you are using visual studio code it may ask you something down here at the bottom it says cannot validate since a PHP installation could not be found this is a very typical thing when you have a new version of Visual Studio code so if you have not set up phsp already inside this software you are going to have to set it up manually inside this text editor here so what you can do if you were quick enough is to make sure you opened up the little link it gave you if not then we’re going to go up into file go down to preferences go inside your settings then you’re going to click on extensions and then you’re going to go down to PHP and from in here you can actually set it to where you want to have the executable path set up inside a Json file so where to click this you can now see that we have this one line called phsp Dov validate do executable path and this is where we need to set in the link for our PHP installation which is again inside the exent folder so if I were to go back inside the XM folder go back you can see we have a folder in here called PHP so I’m going to click it and then you can see we have a php.exe file down here at the bottom this is the one we need to link to inside this executable path inside Visual Studio code so what I can do is I can copy my path here go back inside paste it inside the double quote and then we’re going to write back slash php.exe now if you covered the path directly like I did here you want to make sure these are not back slashes but instead forward slashes otherwise you’re going to get an error message and once you did this you’re just going to go and save the file and then you can close it down and now we have it set up so that we can actually find the PHP version that we’re using once we start creating a PHP website so just to kind of test this out let’s go and start up a regular HTML website now I’m just going to go and zoom in for you so you can actually see what is going on here and what I’m going to do is I’m going to go inside the body tags and create a pair of PHP tags which we use in order to write PHP inside a website so what I can do is I can write angle bracket question mark PHP question mark angle bracket and then anything that goes in between here is going to be considered as PHP so just to follow a very popular tradition here let’s go ahead and go inside and write Echo double quotes Hello World close it off with a semic on save it go inside our website refresh it and then you can see we get hello world so with that we now know that we have a server running so we can actually write PHP code inside our website and have it display inside the browser and with that in the next video we’re going to talk a bit about PHP syntax so we can actually write PHP properly inside our website so hope you enjoyed and I’ll see you in the next video [Music] now before we get started we need to talk a bit about the syntax of writing PP code since syntax is what is going to allow for you to write PHP code without having to create too many errors so in the last episode we talked a bit about opening and closing TX when it came to writing PHP inside a document like for example your index. PHP file and the important thing to know about here is that whenever you create these opening and closing tags your PHP is going to be parsing this page and search for these open open and closing tags until it finds one and then it’s going to see that phsp code inside those tags we can now very easily just take our phsp code and embedded directly inside our HTML like I did on screen here so you can just have the body tags you can have for example a paragraph tag and then right on theath you can just include some PHP code so it is very important that anytime you want to create PHP code you need to have these tags so you need to memorize these tags since we have to use them constantly whenever we want to create any sort of PHP code so when it comes to writing PHP code we do also need to talk about ending of each statement with a semicolon since semicolons is what is going to tell our code that this is a finished statement so as you can see inside my code here I have a very basic pair of PHP text and a echo which we haven’t talked about yet but essentially a echo is something we use in order to Output things inside our browser so if I want to Output some text or a string as we call it then I can Echo a string which is wrapped in double quotes and then end it off with a semicolon to tell it that okay so this is the end of the statement go ahead and Echo this out inside our browser but something you may not know is that the closing PHP tag actually automatically implies a semicolon which means that if I were to take an example like this one where we have two Echoes that Echoes out some code then the last statement doesn’t actually have a semicolon because that is actually implied by the closing PHP tag at the very bottom and I just want to point something out here because even though technically we don’t need to have a semicolon inside the last statement it is something that I do recommend that you do every single time it is also something most people do and it’s just for the simple reason that it doesn’t hurt anything to put that last semicolon and it also teaches you that every single time you create a statement you have to put a semicolon because a lot of times one of the errors that people they type in my comments is when they forgot to put a semicolon or they forgot to close off a parentheses or a curly bracket or something so teaching you the mindset of putting semicolons after each statement is something I highly recommend you do because you have to get into that mindset but now let’s talk about when we have a file that only has PHP inside of it because up until now we talked about this page for example the index a PHP file but in some cases we do also have files that are purely phsp the way we do it when we have this pure phsp file is you want to make sure you have the opening tag at the very top of the page every single time because otherwise your PHP is not going to be working but when it comes to the closing tag we actually want to omit it we don’t want to have a closing tag at the end this is actually the recommended thing to do so just like with the example you see here we have this file that only has a PHP tag at the very top but there’s no closing tag at the bottom it is for the simple reason that in some cases if you were to close off the PHP tag at the very bottom but then accidentally leave a empty line or a space or something then things can go a little bit wrong having talked about that let’s talk about a more advanced example of embedding PHP inside HTML in this example here you can see that I have a pair of body tags so we have some HTML and inside these body tags I have a PHP statement this is called a condition and conditions is something we will talk more about in the future so you don’t really need to know what a condition is right now but essentially I have a condition here where if something is true then run the blocker code inside the curly brackets and in between these curly brackets I did just like before I Echo out or output some text inside the browser or a string as we call it and as you can see I actually included some HTML tags inside that string so we have some html text but with a paragraph tag wrapped around it and this is something you can do whenever you want to create HTML inside a web page you can actually Echo it out using PHP so you can write HTML and content using phsp in this sort of way um but this is not really the most optimal way to do things because you may notice a couple of things here first of all the text is completely orange and that’s the typical color when it comes to writing a string inside phsp and because of that we run into some issues with the HTML not actually having any sort of syntax checking we don’t have any coloring of the HML just like the body tag up and below so writing HML like this inside H string is something that is going to get quite messy and it’s going to get confusing and you don’t really have any automated syntax checking cuz it’s not seen as HTML by your editor is seen as a PHP string so what you can do instead is you can split up your condition using the opening and closing PHP tags around the beginning of the statement and the closing of the statement so on the next slide here you’re going to notice that the if statement is going to get moved up next to the opening PHP tag and then I’m going to close it right after that line and then the curly bracket at the bottom there is going to have a opening and a closing PHP tag as well because by doing that we now allow for HML to be written in between those curly brackets but we can actually write it as HTML and the editor is also going to see it as HTML and actually check it for syntax and that kind of thing and color it so it looks really pretty so doing it that way is really the optimal way to do it I think when it comes to writing HTML the last thing I want to talk a bit about here is writing comments inside your PHP you have seen some of it already but I just want to just sort of like go through it since there’s a little bit more to it whenever you create phsp code write comments because at some point you’re going to forget what the code does and you have to return to it and you have to go through the code and see what it does when you could just have created a comment early on to tell future you what exactly the code does so creating comment is a very important thing a a comment is not going to get outputed inside the browser it is just there for you as the developer to see so we have talked about creating a single line comment here using two forward slashes and because this is a oneline comment we can’t go down to the next line and continue writing then it’s going to see it as not a comment uh but we can create multiple line comments by instead of using two forward slashes we can use a forward slash and a multiplication symbol and then close it off again using multiplication forward slash because in this sort of way we can now create multiple lines in between these two opening and closing tags when it comes to writing a comment and just like that you now know the basics of syntax when it comes to writing PHP there is of course you know more advanced things we could go into but I think this is a good beginning to understanding how to write phsp and not get any sort of basic errors inside your browser whenever you try to create any sort of basic phsp code so with that said I hope you enjoyed this little video and I’ll see you in the next one [Music] so in the last video we talked a bit about PHP syntax and today we’re going to talk a bit about how to create variables and data types now I do think it’s a really good idea that we go inside our edit on this video and just talk a bit about this so we have some practical experience writing PHP code and with that we do need to actually start up our website and I thought why not do that together since that is something we haven’t done yet so what you need to make sure you do every single time time you want to see your website inside the browser is first of all you need to have your editor open which is step one then you need to make sure you’re opening up examp so you want to open up the software make sure you actually start the Apache and MySQL server then you want to go inside your browser and then you want to go into the URL and type Local Host and when you do that you can see all the websites that you have inside your HD docs folder in my case here I do have two websites you should not have two you should only have one so go and pick the one that we created together in the first episode and then you can see we have our website in front of us here and that’s the basic step in order to open up your website when you’re running it inside a server like examp so now we can go back inside our index.php and just to kind of talk briefly about the last episode because I know some people were little bit confused when it came to embedding HTML and PHP together so if I were to go inside I can create a regular HTML paragraph and I can go and create this is a paragraph and just write some text inside this paragraph here now what you can do is you can create the PHP tag so the opening and closing tag so angle brackets question mark PHP and then you can say question mark angle bracket so what I could do is echo which we talked about is how to Output things inside the browser I can say this is also a paragraph and we do need to make sure we remember that semicolon even though because this is the last statement inside this particular PHP tag here we don’t technically need to have this last semicolon but like I said it is best practice to remember to do it every single time because it doesn’t hurt anything to do it so let’s just go and do it every single time and when you do this you can go back inside your website refresh it and then we can see we have two pieces of text we have this is a paragraph and this is also a paragraph So we have two paragraphs inside our website and just to show something a little bit more complicated you can also go inside existing HTML elements and create PHP so I can go in between here and I can open up my PHP tags and then I can write something additionally in here so we would have to again because we need to make sure to Output whatever we’re doing using PHP and I can go ahead and Echo awesome paragraph semicolon save this one go back inside my website and then you can see we included this awesome paragraph in here and this is just to kind of show that we can mix and match PHP and HTML together in any sort of way that we want by embedding it directly inside the HTML but now this is not what I wanted to talk about in this video here I do actually want to talk about variables and data types because we do have variables and data types which we use constantly when it comes to writing phsp code so this is something we have to memorize so let’s go and talk a bit about what exactly a variable is now a variable is when we have a memory location inside our application that stores some sort of data which is a very confusing way for beginners to understand what exactly a variable is because a lot of people don’t understand what is memory location and that kind of thing so instead just for practice here let’s pretend that a variable is a box and that box box has a label so you know when you’re moving into a new house you put you know some writing on the box whether it’s kitchen utensils or uh for the the kids room or something so you know what’s inside the box but then you do also have something inside the Box some actual data so whenever you grab this box by referring to the name of the box then you grab whatever is inside the box as well and that is technically what a variable does so when you reference to a variable you grab the data and it’s just a very easy way for us to refer to data and label it so we know exactly what what the data is now when it comes to PHP uh the way you refer to a variable or the way you declare a variable is by creating a dollar sign so if I were to go inside my PHP tags here I can create a dollar sign which means that now we are declaring a variable and then we can call it something so we can come up with a name for this variable that we think makes sense to the data that is inside the variable so in this case here I could say that this is a name so I could say that this is a name and it’s going to be equal to some kind of data so now we’re initializing this variable by assigning a piece of data to it so in this case here I could say that it is a string which we talked about before called Danny Crossing so now every time I refer to this variable called name I’m going to get a value called Danny Crossing so if I were to go below here and just echo which means that we’re outputting something inside the browser and I can go ahead and Echo out name or the variable called name so we need to remember the dollar sign here if I were to do this go back inside my website you can see that we’re echoing out Denny cing so in this sort of way we can create boxes or labels for pieces of data that we can refer to in order to better handle data inside our code so in this case here we created a variable called name and you can call whatever you want but now we do also have naming conventions when it comes to naming these variables here so in this case you can see we call this one variable name but we can also go in and either start it with a letter or a underscore in order to name this variable now the customary thing is to start with a non-capital Iz letter and then make sure that any other new words inside this variable name starts with a capitalized letter so if I were to write full name instead then we start with a non-c capitalized F and then a capitalized n for name so whenever you have multiple words inside the variable name then you just make sure the first letter of that second word or third word or fourth word is going to be capitalized and again it’s not really a customary thing you have to follow but it’s it’s the way that people do it so I would recommend doing it the same way so people don’t misunderstand what your code does or why you named your variables in this way that other people don’t usually do it and just to mention it when it comes to any other letters that isn’t the first letter inside the variable name then you can also go ahead and create either underscores or you can create numbers so we can say one but make sure you stick within letters underscores or numbers when it comes to the variable name after the first letter inside the variable name so now let’s go and delete what we have here and talk a bit about data types because when it comes to data types inside PHP we have many different data types we’re not going to talk about all of them in this video here since some of them are a little bit more complex than others uh but we will talk about some of the base types that we have inside phsp the first one is going to be what is called Scala types and Scala basically just means that the variable contains one value to it and the first example of that would be we could create a variable that is called something like string and a string we did already talk about what kind of data that is so in this case here we could say uh Daniel so as we know already a string is a piece of text now we do also have numbers so I can go below here and I can create a integer or a int and I’m going to go and name this one a number so we can just write some sort of random number here and this is going to be a value for a integer notice that we’re not using double quotes around the number because if I were to do that then all of a sudden this is going to be a string so it’s not considered a number inside the PHP language anymore it is actually considered to be a piece of text just like a string up here and you can actually tell by the color that it actually changed it to text now we do also have something called a float which is something that we see happen a lot in many other programming languages which is essentially when you have a number that has decimal points so if we to write something like 25678 then this is going to be considered a float because it has decimal points and then we do also have one more scaler type which is called a Boolean now I’m just going to go and write bull even though it is spelled buoen we’re just going to write bull for short and this one is going to be a true or false statement so essentially is something true or is it false and the values for that is going to be false or it is going to be true now it is also important to mention here that if you were to have numbers in here and you were to run this as a Boolean then one is also going to return as true and zero is going to return as false but in most cases we do just use true or false when it comes to this type of data here and just because I talked about it in the last video let’s go and create a comment for this section here so you know exactly what this is so we’re going to create a oneline commment and I’m going to call this one scaler types now the next one we have is actually one that we’re not going to do too much with here in the beginning but we do also have a array type so we can actually go and create a common and call this one array type and essentially a array is when we have a variable that has multiple piece of data inside of it so just like Scala types which means contains one value in the case of an array we have multiple values inside one variable so so could for example create a variable called array and I can name this one equal to multiple pieces of data now we do have two different ways you can create an array one is by writing array parentheses semicolon and then you can add multiple pieces of data in here which could for example be a bunch of string so I can go in here and say we have one string which is called Daniel and then I can create a comma and then add a second string which could be Bella then I can add a third piece of data and I can just keep piling data on inside this array here so we can say feta which is also a string and then we could of course rename the array to something like names if that makes a little bit more sense to what exactly this piece of data has inside of it but essentially this is going to be a bunch of data inside one variable and just to mention it since I did mention there was another way to do this instead of creating array parentheses you can also do a square bracket and then close it off using a square bracket as well just like this now if you just started following this course here you should have a newer version of PHP but if you do run PHP 5.4 or lower then these square brackets are not going to work when it comes to writing a PHP code so if you run a older version of PHP then you do have to do it the way by creating this array around it but just like I said if you’re a little bit confused about why we use arrays inside our code and you may have questions about it don’t worry too much about it because we will get to talk more about arrays in the future for now like I said you’re only going to have to worry about these different scaler types here I do want to mention one more data type though even though it’s not one you should concern yourself with here at the beginning since this is something that’s a little bit further ahead in this course here but we do also have something called an object type so we can say object type and an object type is essentially just when we have a object that is equal to a variable objects is something we create based on classes which is something we again are not talking about right now but when we do instantiate a class we do actually create a variable that is equal to an object based off of that class so could for example say that we have a variable called object and then we set it equal to a new object which is going to be the name of the new object so we could for example say car parentheses and semicolon and this would instantiate a new car object which of course right now can’t find because we don’t have it but once we do have a class called card that we can instantiate then this is not going to throw an error message but like I said we’re not really going to worry too much about arrays and objects right now this early on in this course here so don’t worry if you get confused about because that is perfectly normal even though we’re not really supposed to talk about erasing objects yet I still thought it was important to just kind of like mention them because it is something that is very used inside PHP so knowing about them so you have kind of like a a little bell inside your head when we talk about objects in a future episode and you think to yourself oh wait I heard about that at some point inside this course here and then you might go back to this lesson here and think oh yeah we talked about objects in that early lesson oh now we get to talk about what exactly it is so don’t worry too much about right now it is something that you just need to have kind of like in the back of your head it’s not important right now the only thing you need to worry about right now is that we have these Scala types and when we actually create the variable we declare the variable and then we initialize it by assigning a value to it the reason I mentioned that is because it is possible to go down and create a variable and let’s just go and call it names and not assign anything to it and when you do this depending on the context of when you use this variable it is going to default to a certain value type so if you were to use this one in a string context then it will just go and say oh okay so this is supposed to be a string automatically and then it’s just going to assign a empty string to it and it will actually do something that looks like this so we just have an empty string that doesn’t have any sort of value inside of it and this is what it’s going to default too and the same thing goes for integers floats and booleans and arrays and objects they all default to something so in this case here if I were to go ahead let’s just go and use these up here so as a default a string defaults to nothing so just an empty string with double quote by the way an integer is going to default to zero and the same thing goes for floats they also default to zero and when it comes to booleans they default to faults and just to mention it here when it comes to an array so if we were to create a array because we did talk about them in this video so we do also need to just kind of mention this it is going to default to a empty pair of square brackets and when it comes to an object day default to null which means nothing null is not a concept that we’re going to talk about right now but it just basically means nothing however when it comes to declaring a variable you should always initialize it the reason I say this is because sometimes when we do create variables we don’t know what should be inside the variable just quite yet and in those cases we just declare a variable but we wait with assigning any sort of value to it and when those moments happen you should not do it this way because you do risk getting error mess messages inside your code so make sure that you always assign something to it by initializing the variable so with strings you put empty double quotes with a integer you put a zero the same thing with floats if you put a buo and always set it to false arrays are just going to have these square brackets here and objects are just going to be null so these are going to be the default values you should always put inside a variable if you don’t know what kind of data you should put inside of it just quite yet otherwise your interpreter is just going to throw you a warning in a lot of cases so so just go ahead and make that into a Happ and here at the end before we end up the episode I just want to say that it is perfectly normal to be completely overwhelmed with all this information here because this is a lot of information I’m dumping on people especially if this is your first programming language this is going to be completely new and this is going to be a lot of information I just want to say that is perfectly normal to be overwhelmed and in the future we will get to do many more practical examples where we do actually use variables for something and we use many different data types and it is something that is just going to be a bit more natural when you actually to start seeing how these are used in Practical examples and when you get that little oh okay Epiphany moment where okay so this is how we use these different things we’ve learned up until now then at that point you will remember things a lot easier okay so don’t be worried about if you can’t memorize all these things cuz no one expects you to memorize all these things in one sitting it is something that sticks with you as you start practicing PHP along the way just to give a short example here at the end just so people know exactly how we can use variables inside our code if I were to go back and sign up body tags here and at the very top I’m going to go ahead and declare a variable called name going to set this one equal to a string called Danny Crossing and what we can do here is we can go below and create a paragraph inside HTML then I can just go and say hi my name is and then we’re going to open our PHP tags close it off again comma and I’m learning PHP then what you’re going to do is you’re going to go up and grab your variable name and you’re going to go inside your PHP tags and you’re going to Echo out your variable name semicolon and when you do this and go inside the browser and refresh it you can see that now it says hi my name is Denny cing and I’m learning PHP so in this sort of way we can take data or variables and we can use them inside our code or inside our HTML if you want to do that to Output data in this sort of sense like this is a very basic example but just to kind of show that we can use variables to reference to data that we assigned to variables and just to mention one more thing because something we can also do is we can go down and say I want to create a new variable and I just go and call this one something like test just to give it some kind of name I can assign equal to name so in this case here we have a variable that is assigned equal to a variable and I were to take this name and copy it down instead of the echo you’ll now notice that we still do get hi my name is Danny Crossing and I’m learning PHP and that is because this first variable here has a piece of data assigned to it and then the second variable down here has that same variable which has data inside of it assigned to itself so we can also assign variables equal to variables in this sort of way here and with that we now know a lot about variables so I hope you enjoyed this episode here and I’ll see you in the next [Music] [Music] video so in the last video we talked talk a bit about variables and data types and in this video we’re going to talk a bit about predefined variables or what you also call built-in variables now a predefined variable is a variable that exist inside the PHP language so in comparison to a variable from the last episode where we created it ourselves by saying we have a variable by saying a dollar sign and then we give it some kind of name so we could for example say name set it equal to some kind of value like Daniel and then we have a variable but now this is a userdefined variable which means that we created it ourselves but we do also have variables inside the PHP language and these are called super globals which means that we can access these variables from anywhere inside our code no matter what the scope is inside our code now scope is something we haven’t talked about yet but it is something we’ll get a little bit more into once we start talking about functions in PHP so for now just know that super globals can be accessed from anywhere inside our code now we do have a list of super globals that we can gain access to and each of these do something different when it comes to grabbing these variables so I’m just going to go ahead and list them out here one by one and talk a bit about them and explain what exactly they do and what you can use them for inside your code and just keep in mind once we do this I don’t expect you to memorize all of these in the first go we will actually get to use more of them as we start you know continuing these lessons here so you will get more practical examples to just kind of help you understand how we use these but for now I’m just going to give a short description of what exactly they do and then we’ll talk about more of them in the future episodes now the first you need to know is that whenever we want to define a super Global or a predefined variable is that we reference them by creating the dollar sign but then we create a underscore followed by a capitalized word so for example we could access the server variable and you want to make sure you add these square brackets afterwards and then semicolon so we could for example go inside and say we want to get the documentor root which is going to give us information about the root path of this particular website here so in order to access it inside the browser would do of course need to Output it by echoing it out so if we were to go inside my website refresh it you can now see that we get the C drive xamp HT docks which funny enough is the folder that we talked about in the first episode where we installed xamp so this is the location of the website inside our computer so what I could also do is I can go underneath here and just sort of copy paste this and I could also get some information about the PHP unor self then go inside the browser refresh it and then we can see we get some more information here so now we get the my website which is the name of the root folder that we’re inside of right now and we also get the name of the file that we’re inside of right now and the reason these are written right next to each other is of course because we have them echoed right after each other we could also go down below here and say we want to Echo out a HTML break which is if you know HTML which you should know by now is how to create a new line so want to save this go inside you can now see that these are the two different pieces of information that we get using the server super Global and there’s many pieces of information you can get about the server and there’s a huge list that I will include inside the documentation inside the description of this video here but for now we just going to take a couple of examples here just to kind of show you a little bit about what I can do uh the next one I want to show you is going to be the server name so if I were to go down and copy paste the break I can also go in here and grab the server uncore name if I were to do that you can now see that we get local host and that is of course because we’re working on a local server right now so if if you had your website on a online server that would be the name of that server we can also copy paste one more time and we can do one called request method underscore method and what this will do is tell you how this page was access so in this case here you could for example say that this is using a get method but if you were to access a page using another method like a post method then you can also see that when you output what kind of request method you were using now if you come from the HML CSS course that I have on my channel you may have heard something about get and post methods and that is essentially when you have a form inside a website you know just a regular form you can fill in using HTML and inside the form we have two attributes we have a action and we have a method and inside the method you just simply state if you want to submit the data using a get or a post method and that is essentially the information we’re getting here in a couple of episodes from now we will do a exercise together where we will be using this particular method in order to graph some data so in a couple of episodes from now do take note that we have a dollar signore server request method since we will be using that particular one in a future episode now the next one we’re going to talk about is going to be dollar signore getet which is another Super Global that you may have some bells ringing in your head about because we just talked about get and post methods so essentially when it comes to handling data and submitting data from page to page inside our website we can do so using a get or post method like I said using a HTML form so when we do that we can use a get or post method in order to grab that data from inside the URL which means that I can go in and instead of all this stuff that we just wrote here I could go in and say that we want to grab a piece of data so dollar signore get square brackets semicolon and I want to grab a piece of data that might have a label labeled as name now currently we don’t actually have anything like this inside our website but what you could do is you can go inside your website go go inside the URL and say that we have our current page which is index.php and then you can add a question mark name equal to Danny and because we have this name equal to Danny inside our URL after the question mark we’re now accessing a piece of data inside the URL which could have been submitted by a get method so this is how it would actually look like if you were to submit a piece of data from a form using HTML so if I were to go inside my code and actually Echo this out because like we talked about we do need to Echo in order to output something inside the browser if I were to do this because I have this inside the URL and refresh it you can now see we get Danny and that is because right now all the data inside the URL is going to be accessed as an associative array which means that we have a bunch of data with labels that we can access using this get method here so if I were to go in here so what I could also do is I could add a ENT symbol which is the ant symbol and I could add in a second piece of data which in this case could be I color is equal to Blue so if we were to add in a second piece of data we could also go in and say we want to Echo out a piece of data which is called I color so if we wrote I color saved it refreshed it you can now see we get Denny blue using get methods is something we use quite often inside PHP since we do submit data from page to page constantly whenever we do something using phsp so knowing this is something that is very important for you to memorize however we do also have have a post method and that is going to work a little bit different because a post method will also submit data but a post method is not going to be visible inside the URL just like a get method is so essentially I could still have the same information submitted but we can’t see it inside the UR else so even though we might still have data accessible to us that we submitted to this page we can’t see it inside the browser which is very useful when it comes to submitting more sensitive data so in case someone is standing behind you and looking over your shoulder as you’re submitting data inside a website they can’t see it so it’s going to be more secretive when you submit it there’s of course many different benefits to using a post method over a get method it really depends on what kind of users you’re trying to get here the main rule of thumb is that if you’re trying to get data from a database or just get data that you want to show the user then we use a get method and if you want to submit data to the website or to a database inside the website then we use a post method a very good example of this is if you have a login system and you want to lock in the user when they’re typing in that login information and then submit the data then we don’t want that data to be seen so that has to be submitted using a post method but once they log in and they have this user profile page inside their website that they can visit then all the data inside the profile page could for example be grabed using a get method so again a couple of different ways to use these but now we do also have something called a request method so if we were to go down here and instead say request and do this and actually go back inside the URL and refresh it you can now see that we’re still getting Danny so even though I used a request method instead that still looks for the name label inside the URL we actually still get Danny and this is because a request method is going to be looking for get post and cookies when it comes to looking for data inside this website here the thing about using request though is that even though it is kind of like this super super Global where we can get both get methods and post methods and cookies and we just use one thing to get all three of these is that you don’t really know what you’re grabbing whenever the US to submit something so if I were to for example submit a form but also were to go inside and say that I want to just manually add some data inside the URL then if you don’t set it up properly and validate it properly and sanitize everything once they submit the data then it can kind of go in and do some security damage so the rule of thumb here is whenever you know that you’re just going to be handling post or get data just go ahead and use the get or post method instead so just kind of forget about this one for now just remember that we have a get and a post method and and just don’t look at this one for now the next one I want to talk about is going to be the files super Global so we have one called files now this one is going to be used whenever you want to get data about a file that has been uploaded to your server so in case where you have a HTML form again we’re talking about forms here inside HTML forms we can allow users to submit files when they actually want to submit their form so for example a picture or PDF document or something they want to upload to the website then they can do that using a HTML form and whenever a user does that we need to double check all sorts of things about the file once they actually upload the file to make sure that this file should be uploaded to our website because let’s say for example a user decides to crash our website by uploading a file that may be very very very large in file size then we want to have something to double check the file size of that file that the User submitted and we can do that using our super global call file since we get all sorts of information about the files that the User submitted for example the file size we can also get information about the name of the file uh what kind of extension it has is it a PDF file or is it a file format that we should not allow to be uploaded inside our website so using this super Global here just kind of like allow for us to grab information about files that the User submitted using a HTML form the next one I want to talk about is going to be one called dollar signore cookie now a cookie is essentially a small file that your server embeds on the users computer which means that we have a bunch of information we can store on the users computer and using this super Global here we can actually store or grab information about cookies inside our website and in the same sense we do also have one for a session so I can also grab a session variable so in this case here we could for example grab some information about um let me actually go and demonstrate this one so if we were to go some of PHP tags I could for example create a dollar signore session and inside the bracket I’m going to make sure to include a name for this session variable here so I could call this one username and if I were to go inside and store this username inside the browser using a session this could for example be a username called Crossing then I can access it by simply reference to this particular session variable that I just created called username then if I were to go inside the browser and refresh it even though we don’t have a session running we can actually gain access to this one because it’s inside the same page so right now you can see that we have this cring stored inside a session variable so we can store information about the user inside this session which is on the server side this means that if I were to close down the browser and actually close down the session we are running inside the website it is going to forget about the session variable unless I set it again inside the website which I do actually do right here because it’s not the same page and again we will get to talk much more about session variables and cookies in the future episode for now just know that we have these super Global session and cookie variables that we can use in order to grab data from inside a session or inside a cookie and the last one we have that I just want to mention here which we should definitely not get into right now because this is heavy stuff for a beginner uh but we do also have something called a EnV which is a environment variable that we can gain access to inside our PHP code environment variables are essentially very sensitive data that you want to have inside the particular environment that the user is working in so you know data that should not be accessible to either the user or other environments um but this is not something we’re going to talk about right now this is something we’ll have for a later episode and just so you have all of them right in front of you so you can see how they all look like these are all the super globals that we have inside phsp again it’s very important for you to know that I don’t expect you to memorize all these especially since we haven’t actually used these in any sort of practical examples inside our code so far but the reason I wanted to discuss super globals is because right now we will get to talk a bit about a couple of these in the upcoming lessons so instead of telling you that oh by the we have something called super globals and we’re just going to use two of them right now I thought it was a really good idea just to introduce you to all the super globals that we have so you know that they exist and what they do so in a future episode whenever we visit some sort of lesson that is related to for example sessions inside our tutorial then you know that there’s something called a session super Global because we talked about it so it is important that you know that these exist but I don’t expect you to memorize any of these just quite yet in the next episode we’re going to talk a bit about operators inside pH P which is something that isn’t quite complicated it’s it it’s pretty simple but it is the last lesson that we need in order to do a practical little exercise together where we build a calculator together since this is kind of like a tradition on my channel that we build a calculator using whatever programming language we’re using right now and when we do get to that episode we will talk about the server and the get super Global since we have to use those in order to do our calculator exercise which is why I wanted to talk about these right now since we have to use them so why not introduce them to you this early on and before we end off the episode here I just want to mention that there is another Global that we haven’t talked about just called Global which is a way for us to gain access to variables that we created from any sort of scope inside our code and the reason I didn’t mention it is because we will get to talk more about Scopes once we get to our function episode which is not far from now but once we do get to talk about creating functions we do need to talk about something called the local and the global scope inside our code and that particular super Global is relevant when we come to that particular episode so I will talk about that once we get to that episode there so with that said I hope you enjoyed this video and I’ll see you in the next [Music] [Music] one so now that we know how to create a variable and a super Global we can now talk about how to create a form inside our website and actually submit data that we can grab using PHP and do something with it using HTML forms together with PHP is something we do quite frequently with PHP and it is one of the main things that we actually use PHP for when it comes to handling any sort of data inside a website so if you don’t know how to create a HTML form I do have a very thorough HTML tutorial that does talk about how to create a HTML form that I will link in the description if you have the need for it we have to remember that this is a PHP course so talking about too much HTML and CSS is something that my subscribers actually told me not to do so if you don’t know how to create a HTML form and you want to know the specifics of creating a HTML form then watch that tutorial inside the description with that said I do have a form inside my index. PHP file here so as you can see I have a very basic main tag that has a form inside of it and inside this form I just simply have a input for the first name I have an input for the last name and I do also have a select which is a drop-down that allow you to pick your favorite pet type so just a basic form that allow for you to type some basic data inside the form and then submit it and just because I know some people don’t use labels inside their form do make sure that you use labels whenever you create a form since it allow for people with disabilities to better read your form so this is a important thing I do see some people use paragraph tags instead which I’ve done too in the past so I’m also at fault for doing that um but I’m also seeing people not use any tags whenever they create these labels for their form so just make sure that you use a label element when you want to create a form tag again this is not supposed to be an HTML tutorial and now I’m sitting here teaching HTML when it comes to a form we have talked about inside my HTML course that we do have a action and a method attribute inside the form tag and when it comes to these two different attributes here these are the ones that we use in order to tell our PHP how we want to submit the data and also where we want to submit the data too so in this case here you can see that I did actually tell it that I want to include my data and send sended to a PHP file called form handler. PHP which is inside my includes folder so as you can see inside my root directory I do also have a includes folder that I just simply created by creating a new folder and inside this form handler. PHP I have nothing inside of it so right now we have a clean file you could have called this anything you want so form Handler of test.php just something it doesn’t have to be form Handler it’s just kind of to tell us what exactly this is but in this case here I do have this empty PHP file so just to start with here let’s go ahead and open up our PHP tags and just like we talked about in my syntax video we do not want to include a closing tag because this particular file here is going to be a pure PHP file and when you do that it is best practice not to have a closing tag so now going back to the index of phsp file you can see that we have this post method that I set inside my form now we do have two different ways we can submit this data either using a post or a get method now a get method is going to actually submit the data inside the URL so you can see it whereas the post method is not going to show the data inside the browser so the general rule of thumb here is that whenever you’re submitting data and allowing the user to submit data then you want to use a post method and whenever you want to show something to the user inside a page then you use a get method so just kind of rule of thumb there but you know of course it’s not going to be in 100% of cases but in 98% of cases that is going to be how you’re going to do it and just to kind of show it here because I did talk talk about this in the last episode when we talked about super globals if you want to submit a form and send the data to the same page that you’re inside of there is a way to do it which is to go inside your action open up the PHP tags like so and then you just go in here and you do actually just include the server super Global that we talked about so we’re going to Echo out the server super Global and Target the phsp self so this is one way to do it just to mention it but with that in mind you do also need to do something else here so don’t just post this and use this because this is actually prone to hacking or xss which is called cross- site scripting uh so therefore you should not just post this just like it is right here uh so for now we’re just going to go and send it to a separate document which is how you do it pretty much most at a time I do see a lot of people in my comments they they want to know how to send data to the same page as the form is on which is of course you know in some cases you might find a use for it but in most cases you will be submitting the data to another page so in most cases is this is how you’re going to do it and now that I mention security here for a second because I know some PHP people will maybe point this out um whenever you have any sort of include files that are just pure PHP files you’re supposed to have it inside a private directory inside your server and that’s not how we’ve done it right now everything is public at the moment but we will talk more about Security in a future episode we’ll we talking about private folders and public folders and where to include certain phsp files and where should your HTML files be for now we’re practicing right we’re practicing PSP so this is how we’re going to have the directory right now so that was a lot of information that wasn’t really supposed to be included inside this lesson here but I thought it was important to talk about so I just wanted to mention those things so with that said as we talked about we have a action and a method now when we send this data to the other page we need to be able to grab it somehow and that’s something we need to talk about because inside your HL form all your different data or inputs should have a name attribute because because this is the reference name that we’re going to grab once we send the data to the next page whenever you grab the data using the name attribute you’re going to be grabbing whatever the user input so right now for example inside a text field uh whatever the user typed into the text field is what you’re going to be grabbing on to reference to for example first name but inside a select down here if you have a drop down the data that you’re going to be selecting when you reference to for example in this case here favorite pads is going to be the data that is inside the value attribute so again just a little bit of HTML knowledge there for the the non-html people who should know HTML by now but let’s go and talk about how to actually grab this data inside our form handler. PHP file so once I submit this form inside my website which by the way looks something like this if I fill in information for example Danny Crossing and then I choose a pet so in this case here I do actually have one of each of these types of pets and I don’t want to make any of them cry so I’m just going to select none for now cuz I’m a good dad once once I submit this it is going to send it to whatever I set inside the action attribute so going back inside our document here if I were to go inside the form Handler you can see we have nothing in here which means that if I were to actually submit this data inside the website you can see that we just get a blank page and burning eyes warning here a little bit late but the warning came so right now nothing is happening this is the exact same thing is just an empty page inside HTML or something like that so what we can do is we can go back inside our code and the first thing you want to do is you want to check if the user accessed this particular file in the proper way because it is possible to just go inside the URL inside your website and just go up here and type the address of that particular file that is inside the includes folder which by the way is also why we have private and public folders inside our directory which is something we’ll talk about later because those allow the user to not be able to access the private files just by going inside the URL however we always need to think in security whenever you do PHP always think security so the first thing we’re going to talk about here is going to be how to let the user not access the code if they didn’t access this file using the form that they had to submit the way we’re going to do that is using something called a condition which again we will have a more thorough tutorial on a little bit later but essentially a condition looks like this so we have a if statement that says if something is true then run the code inside these curly brackets that we have here which are these right here so so whatever condition you want to set inside this statement has to go inside the parentheses so if for example true then run this condition here which will always be true because true is true right um so what I can do is I can go inside of here and I can use one of the super globals that we talked about called server which I did mention that we had to memorize because we would be using it in a upcoming lesson which is going to be this one so we have this super Global here and what I want to check for is a request method so requestor method now just to kind of show you here because if I were to take this server super Global and let’s comment this out for now and go up here and use a method called V dump actually this is a buil-in function but if I were to use Vore dump which would actually output some data about this particular super Global inside the browser so we were to do this just to see whatever this is outputting I can go back inside the browser refresh it and then you can see we get string three get which we’re not supposed to be getting oh I forgot to set this one back to post so let’s go and do that for a second inside the form um so go back inside the website refresh it again and now you can see we get well we actually have to resubmit it so we go back again resubmit and now we get post so this basically tells us that we access this particular page using a post method which means that we can go back inside our code and say okay so if the user we just comment this V dump out because we don’t need it anymore if this user access this page using a request method that is equal to post then we allow for the code to be run inside these curly brackets here and this brings me to a good point because some people including myself in the past by the way have been doing this in a different way so instead of checking for a post method we would actually go in and instead check for a is set function which basically goes in and checks if something has been set currently so if were to go back inside my form and inside my button down here I could actually add a name attribute and set this name to submit which means that now if I were to submit this form I also submit a a post super Global that has submit inside of it so I could go back in here and check for a post super global Post and then we can check for brackets go in here and check for a submit so this is also a way to do it but it’s not considered to be the best way to do things so you should be using uh this method down here to do it so every single time you submit data to another page you want to run this condition because that has to be checked for every single time then once you’ve done that you go inside the condition here and then you want to grab the data and we can do that the same way that I just showed using the other if statement so that is by using a post super Global so we can create a variable which we talked about is kind of like a container and we can name it something like first name and I want to set it equal to some sort of data now in this case here I want to grab a post super Global which is the data that we sent to this page here and I can grab it by referencing to the name attribute inside the form so if I go back to the form I can actually go and delete this name attribute down here because we don’t actually need it and I can grab the first piece of data and this one has been set to first name so if I copy that go back inside my PHP and paste that in now I’m grabbing the data from the form however we’re not actually doing this in a very secure way we did talk about cross site scripting so if we were to go back inside my form here just go back again uh if I were to go inside this form you can actually write code into this form here and that is going to allow for users to hack your website or do certain things to your database that might destroy it inject JavaScript in into your website which is not a good thing so you want to make sure that you sanitize your data every single time the rule of thumb here never trust data that is submitted by a user which means that you always need to sanitize data that the user was able to submit so we go back inside our code here and what you want to do is you want to use a built-in function inside phsp which is called HTML special characters so what I can do is I can say HTML special characters and what you want to do is you want to grab grab the data so the post method here and you want to put it inside the parentheses of this particular buil-in function and now there’s a couple of parameters you could put behind this particular function here but for now this is pretty okay so we’re not going to do anything else what this function does is that it takes your data and it converts it into HTML entities which means that we can no longer inject code inside uh the fields that we posted inside our form those are going to get sanitized so we don’t see it as code but we just see it as HTML entities which which means it’s not going to be picked up as code a good example of this just to kind of demonstrate it if it were to go inside my index file I can go right above my form and I can create a HTML Ampersand so if I were to write this HTML entity and save it and go inside my browser you can see it’s going to be picked up as a Ampersand cuz that is the HTML entity for a Ampersand which means that if I were to actually go inside my form and write a Ampersand because it might be part of some code that I’m maliciously trying to inject into this website here to break it um then it’s not going to be seen as this symbol up here but instead it’s going to be seen as this right here which is definitely not some sort of JavaScript code so just to kind of talk a bit about what exactly that function does you know that’s what it does uh so you want to make sure you use this particular function every single time you grab data from a user to make sure they don’t inject any sort of malicious code into a website so we do have two more pieces of data so I want to just copy this down down and I want to change the next one to last name and then I want to make sure that we go inside the post method and we go back and check what is this one called it is called last name so we can go back inside here and copy that in the next one I can call uh pets or something and then we go back we check what did I call this one I called it favorite pet so I can post that in here and it is important to keep in mind here that the naming of the variables doesn’t matter you could call this one test but it wouldn’t be very descriptive so we have to make sure whenever we create a variable that we know what it does by describing what exactly it does so this one would be the first name this would be the last name and this would be whatever pets I submitted so this should technically probably be a little bit more descriptive favorite pet like so now with that said I do also just want to mention this we do also have another function so right now you can see they have HML special characters but we do also have one called HTML entities which almost does the same thing as HTML special characters but instead of just taking special characters and converting into a HTML entity HTML entities takes all applicable characters that you could use for example any sort of other non-code characters and it converts that into HTML entities as well but again in most cases we do just use HML special characters so just keep that in mind for now that we do have this one and I will of course leave documentation to that particular function if you want to check it out inside the description but just know that we will be using HMO Special Care characters in most cases now that we have the data we can start doing something to it so I could go down here and just do some sort of code so I could say I want to Echo out uh a string and I want to Echo out these are the data that the User submitted and then I can go down below and I could also Echo out a break just to get a HTML break so we can actually jump down to next line we could also written a PHP new line which would have been something like this this but let’s just go ahead and do a break uh so what I’ll do here is I’ll jump down to the next line and I want to Echo out a piece of data so in this case I want to grab my first name and I want to Echo that one out then I’m going to be copying these two lines and paste it below last name and then we want to write our favorite pet so just like so we can copy paste copy paste the favorite pet and with that we can now go back inside the browser and refresh the page just to reset everything and then type something else in so I could for example say Danny Crossing and then we could choose a pet let’s just go and choose a dog in this case here cuz Bess is sitting right there I don’t know if you can see him but he is just kind of sitting here at the back he’s a bit tired um but I could choose dog and submit this one and then you can see these are the data that the User submitted Denny cusing Dog so now we grab the data and we could actually Echo it out inside the page just to kind of show what data we grabbed from inside the form now of course in most cases you would not just be echoing out data but instead you would be going in here and actually doing something with the data so for example inserting it inside a database or run a certain function inside your website to to do something with the data but just to kind of show that this is where you would actually start doing things with the data so what you could also do is so we don’t get stuck inside this page because this is just meant for a page where we run phsp code that the user is not supposed to have anything to do with this page is only for us as a developer so what I’ll do is I’ll send the user back to our front page using a header function so I can go in here and say we want to set a location colon and then we want to set the location that we want to send the user to so in this case we want to go back One Directory so I’m going to sayt dot slash and then I want to go inside index.php so with this header function here we now run the code and once we get down to the last bit of code we now send the user back to the front page so if we were to do that go back inside the website let’s just go ahead and refresh it here if I were to submit this data you can now see that oh we went back inside the front page because we just ran the code inside the other page and then we get sent back again to the front page which by the way brings me to just another little security thing um if I were to go back in here we can also run a else statements which basically means that if this condition turns out to be false then instead of just getting stuck inside this page here I want to to send the user back to our front page so if the user got in here in some sort of weird way by not actually posting the form but they just went inside the URL and typed in the address for this page here then they still get sent back to the front page because they access this page illegitimately so including this down here just as a fail save is just kind of like a good thing to do with that said I do want to address one more thing that I often get comments about and I just want to just say this once and for all whenever you create any sort of error hand inside this script here that you created yourself for example if I were to go down here and let’s say I want to check if any of these has been left empty when the User submitted the form so they went inside the website and they did not fill in the first name they did not fill in the last name and then they submitted it then what should happen well of course we don’t want the user to be able to submit the form right cuz there’s no data to submit but we do want to require that they submit all the data and one way you can do that is going inside your phsp code so I can create another condition so I can say we have a if statement and inside this if statement I want to check for a method called empty so basically this one checks if a variable right now contains no data inside of it so if it’s empty essentially so I can take the first name and I can put it inside here and if this one returns true it means that there’s no data inside the variable which means the user did not submit a first name so what I could do is I go in here and I could say I want to exit the script because I don’t want the rest of the script to run I just want everything to stop right here and then I might want to send the user back to the front page so again we copy this header and we send the user back to the front page maybe with an arrow message or something so what people tell me is Daniel you silly little man you can just go inside your HTML form go inside the attribute for example inside this first input here and you can write required if you do that then the user cannot submit this form right I can’t tell you how long I’ve been waiting to gloat about this cuz people they keep telling me inside the comment section even though we have this required attribute you can still submit the form it is very important for me to point out that any sort of front end whether it being HTML CSS or JavaScript is not going to be good security let me demonstrate for you if I were to go inside my form Handler the PHP and just for now so we don’t accidentally exit anything or something like that and I’m just going to go ahead and delete all these header functions here because I I want to stay inside this page if something happens let’s just go and delete everything here uh so we stay inside this page and Echo out all the data once we submit the form so if I were to go inside my website and I refresh the browser right now we have a required attribute inside this form here so if I were to try and submit this without typing anything inside this first one I’m going to get this little error message here so it says please fill out this form right so we can’t possibly submit this right now because it’s telling me when I click it that I need to fill out the form however if you know a little bit about browsers you know that we do also have a depth tool built into every single browser at least every single mutton browser so what I can do is I can rightclick and I can inspect anything inside this website here so when I do that we get this little depth tool that opens up at the bottom here now let me just go and zoom in so you can actually see what is going on here so right now if I duck this one over on the right side so you can actually see uh you’ll notice that inside this dep tool we can see everything about the front end of our website which means that we cannot see any sort of PHP but we can see every single HTML CSS and JavaScript inside this web page here which means that we can actually change it I can go inside my input and as you can see it says required so I can just go ahead and delete that one and if I do that and now go back inside the website so I can close this down I can now submit the form even though I did not input anything inside the first input so it’s very important that you know that any sort of front end HTML CSS JavaScript or at least as long as it’s not backend JavaScript like for example node.js or something but any sort of front-end javascripts is not going to be any sort of security so always use server side security when it comes to security inside your website and a really good server side language to protect your website with is of course phsp because it runs in the server so any sort of time you do anything with phsp inside your website or handle any sort of data from the user inside your website you should always sanitize and run error handlers using PHP in order to check for any sort of thing that the user might do in order to try and hurt your website so that’s very important so with all that said this is the basics when it comes to submitting data using a HTML form and then doing something with the data using PHP so hope you enjoyed this lesson and I’ll see you guys in the next one [Music] today we’re going to talk a bit about operators inside PHP and operators is something we use all the time whenever we do anything inside PHP now essentially a operator is something that helps us with logic connecting data together or math or any sort of thing that has anything to do with operations inside code and when it comes to operators we have many different types and I’m just going to cover the most essential ones that I know we’re going to be using for the next many couple of lessons uh so we’re not going to cover all the operators that exist out there we will talk about the ones that you will be using most of the time operators is also something we’ll have to learn a little bit about in order to actually do our projects in the upcoming videos since we have to do that one calculator uh project that I promised but we can’t do without talking about operators first so we have to talk about how to do various kinds of operations the first kind we’re going to talk about is something called a string operator and a string operator is a way for us to conect connect Different Strings or just different pieces of data together inside one string so to speak so essentially let’s say I have two different variables I have variable a and I have variable B and if I want to connect these two together what we could do is we could create a variable C and say we want to set it equal to hello world but I already have this data somewhere else I already have it inside variable a and variable B so what I could just do instead is I could connect these two together to create one string so what I could do instead is I could actually go inside variable C and instead of just rewriting everything again because we already have the data so there’s no need to rewrite it right so what I can do is I can take variable a and I can say I want to connect these two together by writing a punctuation and then I can include variable B so in this sort of sense we can concatenate two pieces of data together by using this punctuation in order to say well I have this data and I have this data and I want to combine them using this punctuation here I do also want to mention that you should be leaving spaces so don’t do this but instead do this and if I were to actually go and Echo this out so if I go below here and say I want to Echo out variable C what I could do is just kind of take a look at how this looks like cuz it’s not going to look exactly like we think it is if I refresh it you can see we get hello world because we can catenated these two together um but we don’t have a space in between the words so how do we create a spacing between two pieces of data well the way we do that is by going in and say well okay so I I just concatenated two variables but what if I want to concatenate a string together with this so what I could do is I could for example say that I have a string and I want to create a space inside this string and then of course we need to concatenate the string with variable B by creating a punctuation so just like this we now concatenated a string in between these two variables so we created a small space here so yes this is a way to to create spaces between data by just concatenating a empty pair of double quotes uh so what we can do is we can go back in refresh it and then you can see we get that little bit of spacing there and this just kind of like a really neat way to you know connect two pieces of data together so we don’t have to recreate it again so we don’t have to rewrite hello world inside a new variable so we just use old data we have already and just combine it in here and with this we do also have something called arithmetic operators so if we were to go in and paste that in and delete what we have already a arithmetic operator is essentially math it’s just like you learned in elementary school I think you learned this kind of math so essentially like plus minus multiply division uh we do also have some other things like um we do also have something called modulo and exponentiation so we do also have some high school things added in here but what I could do is I go in here and just simply Echo out some data so I could say 1 + 2 and we’re going to Echo this out now this is actually just a arithmetic operator when we add two numbers together like we just did here so in this case here of course if we would to save this and go inside my browser you can see we going to we’re going to get three because 1 + 2 is equal to three and the same sense we can do with all sorts of operators so we can also go in and we can you know minus we can also go in and multiply we can also go in and divide if we want to do that uh but we do also have this called modulo which is essentially when we go in and we want to have the remainder of something specific so in this case here let’s actually go and take 10 and say we want to divide by three or not divide modular by three uh essentially what you’re doing here is you’re dividing 3 into 10 and when you can’t do it any further then you need to see how many numbers are left over in the end 3 6 9 and then we can’t do anymore right but we we got to nine which means in order to get to 10 we have one more left so this would actually equal one if we were to go back inside the browser and refresh it so as you can see we get one and then we of course do also have to the power of which is basically going in and writing two multiplication symbols so if we take 10 to the power of three if we were to go back inside and refresh the browser you can see we get a thand because 10 to the th to the power of three is a th000 so we can do you know basic math calculations here uh but we do also have something called U procedence which is something something that goes in and helps us a little bit when it comes to doing a little bit more complicated math because let’s take an example here I do actually have an example on the side here in this example here you would normally if you know math from back in you know like back in the days when you learned math in school you would know that in this case multiply always comes before plus and minus which means that we have to say 4 * 2 which is 8 + 1 which is 9 so if you were to go ahead and do this go back inside my browser refresh it you can see we get nine however if I want to change the procedence of what gets calculated first inside a arithmetic operator or just a basic uh mathematic equation I can use parentheses order to do so so if we were to go in here and say you know what I want plus to go first so in this case here I write parentheses around one + 2 which means that these two are going to get calculated together first before anything outside the parth gets calculated afterwards so 1 + 2 is 3 and then 3 + 4 is 12 took way too long for me to calculate but this should end up being 12 so if we go back inside the browser and refresh it you can see we get 12 so we do also have something called operator procedence whenever we use parentheses we can do calculations and we can use more than one parentheses so we would to do uh 4 minus 2 then I can also use parentheses around here and then of course uh once we calculate these two together we’re then afterwards going to calculate these two together and then we’re going to multiply at the end there so again you can use this many as you want with that said we do also have something called assignment operators and what we can do here is basically assign things to something else which means that if we were to go in and say uh variable a is equal to two so in this case here I just assigned two to variable a and it is important to note here that we do not say equal to two cuz there is a small difference between saying that it’s equal to something or that we assign something to something it’s not really that important to know but I I just thought I’d mention that it’s not equal to it’s that it gets assigned to because variable a is a space in the memory so if you assign a piece of data to that space in memory then it’s not the same as saying that it’s equal to basically we just assign data to um to variable a that’s that’s what you need to know here with that said this is how we can assign a piece of data to a variable which we have done plenty of times up until now but let’s say I want to do something a little bit different let’s say I do also want to say variable a is going to be equal to itself plus something else what you could do is you could go in and say variable a + 4 and this would actually work out this is variable a which is 2 + 4 and then it gets assigned back to variable a which means that now now variable a is going to be equal to 6 right however this is extra code and this is just not how we want to do things we’re essentially double writing variable a which uh is not really considered best practice so what we can do instead is we can just go ahead and delete and do something like this so we can say plus equal to 4 so whenever we use any sort of arithmetic operator which we talked about which is plus minus multiply divide because we could also do divide if we wanted to do that but whenever we do something like this we’re essentially saying go ahead and take variable a and set it equal to itself plus whatever is after the equal sign so in this case we would also still get six so if we were to go and Echo this out so we’re going to Echo out variable a then you can see we get six inside the browser and the same way like I said we can do with any sort of operators that we learned about previously like minutes ago uh so I could go in and say multiply so in this case here it’s 4 * 2 so I would to go back in you can see that we get eight but now let’s talk about the next operator type which is something called a comparison operator and this is something that you will be using very often whenever it comes to any sort of conditions inside your code uh we have talked a bit about conditions in the past you know when you have a if statement says if this code is true then run whatever code is inside this like the curly brackets below so to give an example here let’s go and delete what we have here and let’s go ahead and create a if statement we haven’t really talked about if statements in depth we will get to do that I believe in the next video but let’s just go and create an if statement essentially when you have an if statement like this with the if keyword whatever is inside the parentheses has to be true in order for the code inside the curly brackets to run but let’s go and create a couple of variables here just to to talk a bit about a comparison operator so let’s say we have variable a and variable a has a piece of data assigned to it which is two and I can also go ahead and say we have something called a variable B which is going to have something like four assigned to it now what I can do is I can go inside my parentheses here and I can say is variable a equal to variable B what you’ll notice is that I’m actually using two equal signs here so I’m not using one because this means that we’re assigning something to variable a so a is going to be equal or be assigned variable B um and that’s not the same thing as doing two equal signs when you do it like this you basically checking if two pieces of data are the same and we’re not really checking for data types here we’re just checking if they’re the same what I mean by that is if I were to actually let’s go and output something so let’s say if this is true then Echo out this statement is true just to Echo something out inside the browser so if we were to do this and go back inside Firefox here refresh it you can see we get nothing so far and that’s because of course these are not equal to each other two is not equal to four but let’s say I went down and changed this to two and went back inside my browser now they’re going to be equal to each other right cuz two is equal to two however if I go back in here and say what if variable B is not a number but let’s say this is a string like it’s still two but now it turned into a string so is this going to be equal to each other what is your guess cuz we’re going to go in and find out now it is still going to be true and that is because we’re not checking for data types in this case however if I go back down to the equal signs and write a third equal sign now we’re checking for if they’re true and if they’re the same data type so we’re taking for two things now so if we go back inside the browser refresh it here you can now see oh it’s not outputting anything and that’s because it’s not true because this right here is a string data type again we can go and remove this just to test this go back inside the browser and now it is going to be true so two equal signs means that we’re comparing two pieces of data and three means they we’re comparing two pieces of data but also if they’re the same data type with that said let’s go and go back to the first one so two equal signs means we’re just checking if they’re equal to each other right what I can also do is I can replace one of the equal signs or the first equal sign I should say with a exclamation mark if I do this then I’m checking if they’re not true so right now because 2 is equal to 2 this condition down here is actually going to turn out false so if I were to save this go back inside the browser you can see that we’re not going to get anything but if I were to go back inside my code and make this four again then they’re not equal to each other which means that this condition is going to be true so if we were to go back in refresh it you can now see that we’re going to get this statement is true and with that we do of course also have three equal signs we replace the first one with a exclamation mark so this is going to check if they’re not the same data type or if they’re not the same number and we can also do other things and just comparing if they’re equal to each other we can also go in and say what if one should be lesser than the other numbers so right now we’re checking is a lesser than b which in this case is going to be true so if we go back in you can see that we actually output this statement is true but if we were to change this one to a five so we have you know is five lesser than four this is going to be false so we were to go back in you can see we don’t output anything and just like you learned in school we can also take for other things so not just lesser them but also greater than or we can also check for lesser than and equal to the other piece of data so in this case here if 4 is equal to four then this is going to be true right cuz it’s lesser than or equal to B so we would to go back in refresh it you can see we get an output and just to show one last thing there is also another way of writing this right here so is not equal to each other we can also write like this which does the exact same thing we’re just checking if they’re not equal to each other and we’re not really caring about data type in most cases just to mention it I do this one it’s just the way that I think is easier for me to make it make sense so this is the one that I use and with these this is a perfect time to talk a bit about something called logical operators because logical operators whenever we go inside a if statement like this one down here let’s say right now I’m checking is a equal to B which in this case is going to be true because 4 is equal to 4 so if we were to go back in and actually refresh you can see that we get this statement is true now let’s say I want to check for more than just one condition what you could do is you could copy paste a condition and put it inside another condition and now all of a sudden we start doing something called nesting nesting is something that most people frown upon because it starts creating very messy code I personally have done it in the past and I I regret doing it because it looks extremely messy but essentially you want to try and avoid having as many conditions inside other conditions as you can like in some cases you can’t avoid it but of course you know if you can then you should try not to and one way we can do that is by going inside the original condition here and say okay so what if I want to check for something else as well let’s say I have another pair of variables and this one is going to be C and this one is going to be D and this one is going to be two and this one is going to be six what I can do is I can go inside my condition here and say I want to check if this condition is true so is a equal to B which right now is true right so we output something inside the browser but I also want to check is c equal to D so what I can do is I can write and is variable C equal to variable D so right now we’re checking for two different things so the first condition has to be true but also because we wrote and the second condition also has to be true so both of these have to be true whenever we use and so would to go and do this go back inside the browser refresh it you can see oh we don’t get any sort of output because one of them is not true but let’s say instead I don’t want to check if they’re both true but I instead just want to check that one of them is true what I can do instead is I can write something called or so if I write or we’re basically saying this has to be true or this has to be true and if one of them is true then I’ll put something inside the browser so in this sort of way you can use logical operators in order to you know perform multiple conditions or multiple pieces of logic inside the same condition and it is possible to chain as many of these behind each other as you want so you can also go ahead and say we want to check for a and and then we can check is variable a equal to variable C then we can also do that and we can change as many of these behind each other as we want I do want to mention something here though which is something you will see in most cases when it comes to people doing programming which is that people don’t really write or or and uh because we do have another way of writing these and even though this may not make sense to a lot of people why we choose to do this instead um that’s just kind of like how people do it instead of writing or what you can instead do is write two pipe symbols and this means the exact same thing as writing or and instead of writing and we can use two ENT symbols and these two mean the exact same thing as or or and now the pipe symbol one is is the reason why I think this is going to be a little bit annoying for most people because the pipe symbol is not really the easiest thing to figure out where is on your keyboard I’m using a ntic keyboard which means my layout is going to be different for Americans or other people around the world but this is called a pipe symbol so pipe as in PIP PE pipe this right here so my best suggestion is to Google this to figure out where it is on your keyboard layout if you want to figure out where it is in my case I have to hold down alt and then the button right behind my backspace button and that is going to create my pipe symbol but now let’s talk about something here because right now I just chained three of these together but how exactly do U operator procedence function when it comes to this just like when we talked about the parentheses around you know when we were doing math uh we could determine what was going to be happening first but in this case here what is happening first are we going to be running these two first because we’re checking that one of these has to be true or we running these two first and then running the other one like what exactly is going on here when we use a Ampersand or a pipe symbol if I were to save this go back inside my browser you’ll notice that we get this statement is true which means that right now if I were to go and check this this statement is true but none of these are going to be true which means that we’re going to take the pipe symbol and this is where the divider is so essentially we’re splitting apart these condition checks and we’re saying Okay so this over here has to be compared first which which means that both of these have to be true but in this case none of them are so this is going to fail right but then we do also have a pipe symbol that says well okay so even if this fails we still also have this other side to check for and if this one is true then we’re still going to print something out inside the browser so in this case here as you can see we printed out this statement is true because the pipe symbol is going to be the divider that checks with these different conditions here so the pipe symbol is going to be the last determiner of what exactly is true inside this condition check here but now we do also have one last one that I want to talk about which is called incrementing and decrementing operators and these are essentially a way for us to do something inside Loops most of the time we can use them outside Loops if you want to um I can actually demonstrate this so if I were to go ahead and say variable a is going to be equal to 1 if I then go below here I can also Echo out variable a just so we can see EX exactly what this looks like inside the browser and then you can see we get one because variable a is equal to one however we do have something called a increment which means that I can go ahead and say variable a and add a Plus+ in front of it which means that we’re adding one to variable a which means that if we were to go inside the browser we now get two so a increment is basically just a way for us to add one to a piece of data and I can also go ahead and do a minus minus and this case we’re going to subtract one so we want to go back inside the browser you can see that we’re going to get zero however we do also have something called variable A++ which is a little bit different because basically the order of when we add one to this variable here is going to be changed so in this case here when we had Plus+ we say that we add one to variable a and then we Echo it out whereas if we were to go ahead and do plus plus after variable a we want to say that we want to Echo out variable a and then we want to add one to it so we would have go and do this what do you think we’re going to get inside the browser we’re going to get one so even though inside our code this is going to be two we don’t actually Echo out two because we’re adding one to it after we output it inside the browser so it would to go below here and actually say Echo and say I want to Echo variable a one more time then the second Echo is actually going to be two and the same thing goes for minus minus of course we can also say minus minus and then we’re going to Output a which is going to be equal to one and then we’re going to subtract one to it which means that the second time we Echo it out it is going to be zero so want to go back inside the browser and do this you can see we get one and zero and why does this matter you might be asking well in some cases when we start talking about loops inside programming and Loops is something that we will get to talk about a little bit in the future but essentially a loop is a way for us to Output the same code multiple times inside the browser as long as a certain condition is still true so let’s say I want to Loop out something until a certain number is lesser than 10 then we’re going to add one to the number that we’re checking for every single Loop and then when we get to 10 then it’s going to stop looping because now the number is not lesser than 10 anymore again this may be a little bit confusing because we haven’t talked about loops yet so don’t worry too much about it if you don’t quite understand what I’m talking about here I just want you to know that we have something called plus plus and minus minus so if you want to add a number or subtract a number you can do it by writing plus plus or minus minus so with that said I hope you enjoyed this lesson here we will get to talk a bit about conditions in the next video which is something we have touched upon in this video here and in some of the previous ones with the if statement you go in you check for a condition and then you output something if that condition is true but there’s a little bit more when it comes to condition so we’ll get to talk about that in the next video so hope you enjoyed and I’ll see you in the next one [Music] today we’re going to learn about something called control structures inside PHP and a control structure is essentially a way for us to navigate the code in different directions so if we want something specific to happen depending on something else then we can leave the code elsewhere and do something else if that makes sense we have many different types of control structures we have conditions which we’re going to talk about today we have switches we have a new thing in PHP 8 called a match we do also have include so we can include other files into our code and then we do also have something called Loops inside our code to Output code multiple times inside our browsers so there’s many different kinds of control structures and we’re going to talk about a few of them today we’re not going to talk about all of them since there is a lot to talk about um but we will get to more of them as we continue this course here but for now we’re going to focus on something called a Edition a switch and we’re going to talk about the new match thing that we just got inside PHP 8 so now we have talked a bit about a if statement before because we have used it a couple of times up until now in the previous video so essentially what you do is inside your PHP code you go inside and create a if statement and inside this if statement we can write a condition inside the parentheses to only run the code inside the curly brackets here if that condition is true so it’s important to point out here that we’re not talking talking about if the result inside the condition returns as true but if the condition is true so if I were to go inside and say that we have a bullan let’s create a variable up here I’m just going to call it Bull and I’m going to set this one equal to true so we’re not actually checking what is assigned to this Boolean up here so if I were to go in and actually copy this and paste it in we’re not actually checking if it is returning as true I mean right now we are so this is actually going to run the code but we can also go in and check if it’s not true this is actually also a operator that we forgot to talk about in the previous video but essentially I’m going in and I’m checking if this statement is not true then I want to run the code inside the curly brackets so we’re not checking if this value up here is true we’re checking if the condition is true okay whatever we’re checking for has to be true I just want to make sure people are not confused about that so with that said uh what we can do is we can actually go in and we can create a variable so I’m going to create a variable called a I’m going to set this this one equal to one and then I’m going to create another variable and I’m going to set this one equal to four so what I can do inside my condition down here is I can go in and use one of the operators that we talked about in the previous episode where we actually compare some of these different data so I can go in and say you know what I want to check for variable a and see if it’s lesser than variable B so in this case I can go in say is variable a less than variable B if so then Echo out first condition is true so in this case if I were to go back inside my browser refresh it you can see we get first condition is true because it is in fact true one is less than four but let’s say I want to check for multiple conditions inside one check here let’s say there’s two things that needs to be true what I could do is I could go inside my if condition here and just copy paste another if condition and then we would say Okay first we check for this thing if that is true then we go inside the statement and then we check for this thing and then we output something else that is one way to do it but we do something what is called nesting which is not really looked upon that fondly when it comes to programming uh since this creates a very weird spaghetti um messy code and that’s not really what we want to do when we’re doing programming we want everything to be very neat and tidy so instead what we can do is we can go outside and we can use one of the operators that we talked about in the previous episode so I can go inside my if condition here and say you know what I also want to check for something else so if a is lesser than b and our Boolean is true then run the code inside the condition here so in this case it is going to run because our Boolean is set true up here and just remember just like before I can also check if my Boolean is false by going in and adding the exclamation mark to say I want to check for the opposite it is also possible to do something else which is to go in here and say is our Boolean equal to false or as it is right now if I want to check if this Boolean is true then we can also just say is it true and then this would also work but it’s just kind of a habit for programmers to you know look a little bit more professional and actually check for a Boolean if it’s true or if it’s equal to false so using the exclamation mark here is something you should get used to I think because it is just a shorter way to write things and it makes you a look a bit more professional now in this case it’s not actually going to run this condition because our Boolean is true and I’m checking if it’s false so let’s say I want to check for another thing if this one fails I want to jump down to another condition and check for a second thing what I can do is I can go down below and I can create something called a else if statement and an else if statement basically is just a chain that we chain behind our if statement and says okay so if the first if condition is not met then jump down and check for the next one in the chain list so what I can do down here I can actually go and say you know what let’s go and check for the same thing but this time I want to check if our Boolean is equal to true so in this case here we would actually output something else now don’t get too confused about my code jumping back up behind each other because you can write it like this or you can write it like this it doesn’t really matter but because of my plugins inside my my little text editor here uh it automatically jumps back when I save so don’t get too confused about that it’s a way for the text editor to tell us that this belongs together this is a chain so therefore it jump spec behind it which I think is a bit weird but that’s just kind of how my plugin works so what I’ll do is I’ll go inside side and I’ll copy paste my echo and I’ll say the second condition is true because this one would actually be true then so we were to save this go inside my browser you can see that now we get our second condition is true and when it comes to a else if statement I just want to point out that you can write it like this in two words or you can combine it into one word and this would do the exact same thing it is kind of a habit for PHP programmers to have it in one word but in pretty much every other language out there we we split it into two words so the way I prefer to do it is using two words as well so now when it comes to adding these extra conditions behind the first if statement whenever we want to add more we just simply go in and add another else if statement so we can just continue just pasting and pasting as many as we want to create this huge chain where we check for a new thing and the important thing to note here is that whenever you hit a certain condition and it returns as true so let’s say this second condition up here is actually true then all the other conditions below are not going to run so it’s going to stop right there and it’s just going to Output whatever is inside this condition and it’s going to stop everything else from being checked so in this case here where every single one of the conditions are pasted below are actually true it is only going to Output one thing inside the browser because like I said it’s just going to stop the rest from running but now let’s say we want to have a fail save what if all of these fails to get run inside the browser because all the conditions are actually false what we can do is we can add a default Behavior so if a to go below here I can add a else statement without parenthesis and then I can write some code inside of here so we can copy paste paste the echo in and say none of the conditions were true so we can actually do this last effort here in order to say that something has to be output even if none of these are actually returning as true so let’s go inside all of the elive statements and just add a exclamation mark just to kind of say that you know what all of these are going to you know essentially be false so we’re going to save this go inside the browser refresh it and then you can see none of the conditions were true right now it says None of the condition were true which is not right it’s not plural there we go but you kind of get the idea here so what I’ll do is I’ll actually go ahead and decrease these cuz these are a lot of else if statements I’m just going to go and do this let’s just go and change this one so it doesn’t you know fail so we have the second one is actually succeeding so again if I were to save this go inside the browser we now get the second condition is true so with this we now talked about these if else if else statements however we do also have something called a switch inside PHP now a switch is a little bit different I do tend to see a lot of people are confused about when you use a switch compared to using IF else if else statements because they kind of do a little bit of the same thing on the Surfers uh but let’s go and create a switch and then we’ll talk about uh how they’re different and when you should use one or the other so in this case here I’ll create a switch which is using the switch keyword parenthesis and curly brackets now inside the parentheses we want to include whatever data we want to check for so in this case here let’s just go ahead and check for variable a so I’ll paste it inside the condition here and inside the actual switch curly brackets we’re going to write a bunch of cases which is kind of the same thing as taking for all these if else if else statements down here so I’m going to go and write a case and then I’m going to say what should the value be of variable a and if that is the value then we’ll run this block of code here so I’m going to write the case keyword and then right after we have to tell it what we’re checking for so if variable a is equal to something specific then run the code inside this case here so in this case I’ll check if a is equal to one it’s important to note we’re not writing case one so like this is the first case and then the second one has to be case number two and and so on we’re checking for the actual value inside this case here so if this were to be a string let’s say we had Daniel in here then I could ALS be checking for a string called Daniel in this case here so what I’ll do is I’ll just go back so we had the number here and inside the case number one let’s go ahead and create a colon and then say whatever code is in here we’re going to run if a is equal to 1 so I could for example Echo out um the first case is correct and you can write as much code as you want in here so we can also write more code down here below if you want to do that and just keep writing code um um but the important thing is that once you’re done writing the code that you need to actually get run if that case is equal to one is that you can go down below and add a break to tell it that now we’re done this is the break point of the first case so all the code in between the break and the case up there so everything in between here is going to get run if this is equal to one and we can of course add more of these so we can just go below here and say you know we have a second case and now I want to check if the number is three for example then we can go inside and say this second case is correct and just like with else if statements down here we just keep pasting more cases behind it and check for different values right after the case keyword here until we get something that is correct but let’s say we run into a scenario where none of these are correct just like we did below here let’s say we you know we don’t have this lse statement uh but none of these conditions are true but we want to run some default code if none of them are actually correct what I can also do inside the switch statement is I can go down and I can write default and then I can include some code below here so we can actually Echo out something else so we can actually say none of the conditions were true we just copy paste it up here and this will be what gets echoed out if none of the cases above are actually going to return as true and now some of you may be asking okay so when do we use a switch compared to using a you know bunch of if statements because they’re pretty much doing the same thing right the difference here is that inside a switch statement we’re checking for the value of a certain you know piece of data so in this case here variable a whereas inside a if condition we can actually check for multiple things so we’re checking is a lesser than b and is Boolean equal to fult so we can change it and then even in the next else if statement we can check for something completely different whereas inside a switch statement we’re checking for one thing in all the different cases down here so if you want to check for one specific value and then depending on that value you want to run a different set of code then you can use a switch statement but if you want to run different types of conditions that checks with different things then you can use a if else if else statement and just to show you what exactly is going on here because right now let’s say I want to go in here and I want to check for the number two and then I want to also write another case here and I want to check for the number three what we can do let’s say third just to have everything being correct what I can do is I can actually recreate this condition down here to show you exactly what is going on with the switch up here so if you were to go down here you could say is variable a equal to one that is essentially the exact same thing as this first case up here so if I were to go down to the elsf statement I can now check is variable a equal to 2 then I can add another one behind it so we can actually check for the next one which is is variable a equal to three so just to kind of show this is what the switch is doing it it’s comparing the same data to different sets of results let’s go ahead and comment out the switch and also the if conditions down here and let’s go above the switch and create create a match now A match is a little bit different from a switch because inside a switch here we just basically have a block of code that deviates into different directions depending on a certain results so if variable a is equal to something specific then we run a different piece of code however when it comes to a match we actually have a variable so we can call this one results and then we set it equal to our match keyword parentheses and curly brackets now because this one is a little bit different than a switch state or a if else if else condition we do want to add a semicolon at the end here because this is the exact same thing as creating a variable to we call this one result and then we set it equal to some piece of data and then in this case here we would actually add a semicolon behind it so this should have a semicolon behind it too because it’s the exact same thing as going in here and then creating curly brackets because we still need to have that semicolon so with that semicolon what we can do is we can go in and say you know we’re going to check for a certain thing so if variable a is equal to something specific then we want to return a value into our variable result depending on variable a so I can go in here and I can say you know what if variable a is equal to one then we can go ahead and assign a value which is going to be variable a is equal to 1 and in this case here we’re not actually going to add a semicolon we’re actually going to add a comma because we’re creating a small list of items here uh so what I can do is I can copy paste this below and then I can say if the data is equal to two then I can assign the data called variable a is equal to 2 so in this sort of way we’re just adding a different piece of data to a variable depending on what the result is now it is important to note here as well that the last condition you’re checking for in here should have a comma behind it this is how it’s supposed to be done so you do want to make sure that is that comma behind every single condition so don’t go down here and add a third condition and then delete the comma because this is the last statement uh just go ahead and make sure you have a comma behind all of them I do also want to mention here that you can check for multiple pieces of data inside the same condition here so you can actually go in and say okay so if variable a is equal to 1 or it is equal to three or it is equal to 5 then I want to insert variable a is equal to 1 inside variable result so using a comma when we want to tell it what we’re checking for here then we can separate different conditions and then output the same data inside variable results so just to Output this inside the browser let’s go and go below here and Echo out variable result because in order to actually get something inside the browser we do need to Echo it so doing this and going back inside the browser you can now see that we get variable a is equal to one another thing that’s important to note here is that we’re doing a more strict comparison type when we do any sort of comparisons inside this match statement here what I mean by that is we’re actually taking for types as well so if I were to to check for variable a being 1 3 or five but variable a is equal to a string that is equal to one then this is not going to return the actual data in here so if we were to save this and go inside the browser you can see we get a error message that says uncut unhandled match error which is the default error message you’re going to get if none of the actual checks in there is returned as any sort of data and just to mention it here for the people who do need to see it it’s the same thing as going inside a condition and then checking for variable a being equal to one but we use two equal signs so this is a very loose comparison so if variable a is equal to one or a string called one then it doesn’t matter but if we use three equal signs then it’s going to be a strict comparison type which means we also need this to be the same data type but now you can also do a default output inside a met statement so if you want to do the same thing as inside the switch down here where we have a default or with the else statement inside the if conditions down here then we can do the same thing when it comes to a met statement by simply going in and writing default and then point to some kind of value so we can go ah and say want to point to a string and say none were a match so now we have something default in case none of these are actually true so right now because variable a is equal to a string which is call one then none of these are actually going to be true but we’re still going to get an output inside the browser because we have a default return and again now the big question is when do we use a match versus a switch versus a if condition it really depends on what exactly the purpose is of your code so if right here you want to have a piece of data assigned to a variable but you want to have a different result based on something else inside your code then you can do that very easily using a match statement so instead of having to do a switch statement down here where we assign a piece of data to a variable we created up here which is going to be a lot more code than simply doing this then you can use a match instead but if you just want your code to Branch out depending on One Piece data then you can do that using a switch statement just based on the value of one variable inside your code but if you want to do different kinds of checks where you want to switch it up every single condition you’re doing inside this chain then you can use a if else if else statement down here in order to do different kinds of checks inside your code so it’s just kind of nice to have different types of tools inside PHP to do different things that is somewhat the same thing you want to do but slightly different and of course just like with all the other episodes this is quite a lot of information so we will get to do more practical examples with this in the future and with that said I do also want to mention here that in the next video we’re going to learn how to build a calculator together using PHP so we’re going to have an actual calculator inside our website you know using HTML and CSS we can type numbers into it then you can submit it and then you can get some sort of calculation out of it so we’re actually going to build something using what we learned up until now which is going to be quite exciting cuz now we can see how we can use PHP to actually do things inside a website up until until now youve just kind of been Gathering puzzle pieces but you haven’t actually learned how to put them all together to build something so that is going to be quite exciting uh so with that said I hope you enjoyed this video and I’ll see you in the next [Music] [Music] one so now we finally came to the point where we have to start learning how to create something using PHP since we’ve learned a lot of things about until now but we haven’t really learned how to put all those things together and actually create something using PHP the exercise we’re going to be doing today is to build a calculator inside the browser so we can actually go in and type into numbers and then we can perform some kind of operation on those numbers so we can multiply plus minus divide those kind of things uh so we can actually do something so as you can see in front of me here I have a basic index to PHP file that doesn’t really do that much it’s just kind of like a basic setup so we have something inside the browser I do have have two different style sheets inside my project here I do have a reset. CSS and I do also have a main. CSS file Now using these two different stylesheets is not something that should be new to anyone in here because a reset stylesheet is something you should know about already and using a regular style sheet for styling HTML things inside the browser is also something you should know by now if you don’t know how to do CSS there is of course a HTML and CSS tutorial on my channel but you shouldn’t need it at this point but it’s there if you do need it I do want to point something out about the CSS though because I have been told by my subscribers over and over again not to include CSS inside my videos because they’re just taking up space so if you want access to my personal files for these lessons here for example for these CSS files then I do have them available to all the different YouTube members and patrons so you can just go ahead and click the link in the description if you want to become part of that with that said I should also say something else which I shouldn’t really have to say but I I still got to say it because I keep keep getting questions about it CSS has no effects on your PSP code you can make the calculator in however way you want using CSS and it’s going to work the exact same way as my calculator with my CSS in here if you get any sort of errors in this video it is not because of the CSS okay just so it’s said so with that out of the way let’s go ahe and talk a bit about how to actually create a calculator so right now we have this basic front page and what we want to do in here at least what I want to do with this exercise is I want to build a calculator and have it run inside the same page because typically the way we do things is that whenever we want to have any sort of input from a user we use a HTML form so we can actually create that now to begin with so if I go inside my body tag here I’m going to create a form just a basic form it doesn’t have to be fancy and inside this form you need to have a action attribute and we do also need to have a method since we do need to submit this data and tell it how we want to submit this data should it be a get method or a post method now a get method will actually show the data inside the URL when we send this data because when we send data using forms we use the URL in order to do so but using a post method would actually hide the data so we can’t see it inside the URL and for this exercise here we’re going to go and use a get method just to begin with here because I do want to demonstrate something once we get a little bit further so if I were to go in and actually say I want to use a get method which means we can see the data inside the URL and then go inside the action here now when I submit this form I want to stay on the same page because typically when we submit the data we send the data to another PHP file and then we have that file handle the data and do things to it and then we go back to the front page with some kind of results however in this video I want to just stay on the same page I want to calculate things inside this same page and just show the data inside the same page here so the way we’re going to do that is we can either leave this action empty or we can go in and include something called a server super Global that points to the same page that we’re on right now one of the benefits to doing it this way is if I were to go in and say I want to open up my phsp tags because we do need to add phsp in order to add a server super Global is I can go in here and I can say I want to reference to Dollar signore server and then inside the brackets I want to reference to PHP self and of course a semicolon so when when we do this it is going to send the data to the same page that we’re on right now so we can do something with the data inside this page here now it is important to note that whenever you want to have anything shown inside the browser using PHP you want to make sure you escape it using HTML special characters otherwise you can have users that inject code inside your browser which is not very good always think security when it comes to PSP so inside of here we’re going to go to Echo and we’re going to Echo out HTML special characters or just CS with an S behind it parenthesis and then I want to grab the server super Global and paste it inside the parentheses and I don’t want to paste in the semicolon it has to be outside the the parentheses so we have it like this right here uh so doing this is going to escape our server super Global so users can’t accidentally accidentally people will UNP purpose try to hurt your website using this particular action here if you don’t sanitize the output of your code there’s a couple of different ways you can sanitize data and it really depends on what purpose it has are you trying to Output HTML into the website so we actually show something inside the website or are you trying to sanitize data submitted by the user then we use something else so there is a couple of different ways we sanitize data using PHP and in this case here because we’re writing HTML that is being output inside the browser we have to use HTML special characters now let’s go ahead and make sure that we have everything just jumping down on a new line because because I want to make sure you can see everything so I don’t have to scroll sideways like this constantly so I’m just going to make sure to wrap everything and I’m going to go and grab the form closing tag and I’m going to move it down and inside the form closing tag we’re going to go and include a input because I want to make sure that the user can actually type in a number that they want to calculate inside this calculator here so this is going to be a number type I’m going to include a name attribute and this one is going to be set to num one and then I do also want to include a placeholder just so the user knows exactly what to type in so we’re going to say we have a placeholder and this one could be number one or just something something that you think makes sense so they know what to type in inside this input the next thing I want to include is not the second number but I want to include the operator so in this case here I could add a select which is a way for us to create a drop down inside a form so I can call this one operator and then I can go inside and delete this ID now just to mention it since this might be something people are not aware of but the name attribute inside all these different input so inside the select we have down here and inside the input we have up here are going to be the name that we have to reference in order to grab this data from the URL after we submit this data here so just so you know exactly why we have the name input In Here Also I did not include a label for all these different inputs technically if you want this to be readable and you know allow screen readers to perfectly understand what this form is you know in order to make usability as good as it can you should add labels in here I talk about that inside my HTML form episode inside my HTML course but in this episode we’re just going to do some basic PHP calculator we’re not going to worry too much about HTML conventions and stuff like that we’re just going to build something using PHP so inside of here inside the select I’m going to add a option and inside this option I’m going to go and give it a value which is going to be add so we can just say we want to add something here so inside the option for the symol we’re going to see inside the browser I’m going to add a plus just so we know that this is plus adding so to speak so what I can do is I can copy paste this down and say I want to add a minus and we can call this one subtract we could also have called the above one addition because that is probably how you should say it then I’ll copy paste it below and I’ll go in and say I want to multiply and we can also say multiply inside our value multiply then I’m going to paste it down and I want to say I want to divide in this case here so divide and we’re going to add a division symbol and then for the last one down here we do also need to make sure the user can type in a second number so we’re just going to copy paste our input from up here so I’m just going to paste it in and I want to rename everything so we have name set to number two and also I want to set the placeholder to number two so now we have everything in terms of input so we just need to add a button in order to be able to submit this inside the browser so I’m going to add a button and just simply going to call this one calculate so now we have everything that we need in order to have a form that can actually submit data so if we were to go inside the browser just so we can see exactly what we have you can now see that I can type in a number so I can type two and then I can say what kind of operation do I want to perform so in this case I could say do I want to plus minus multiply divide so I could say minus and then we can say number one so this would actually end up being one once we calculate but in this case here it’s not going to do anything because we don’t actually have any PHP code that does anything inside this thing so that’s going to be the next thing we’re going to worry about like I said in this video here we’re just going to focus on doing everything inside the same page here so below my form I’m going to go and open up my phsp tags because I want to just add in the PHP here and in between these PHP tags the first thing we need to do is we need to actually check did the user actually submit the form data correctly because we don’t want to run any phsp code if the user did not submit the form data correctly so what I’ll do is I’ll include a if condition go in here and say inside the parentheses I want to check for something very specific so in this case I want to check for a super Global called dollar signore server and I want to check for a certain request method so I can say I want to check for a request uncore method which is going to be set equal to a certain method so in this case I want to check for a get method now we will run into a small issue here but just for now let’s just leave this as it is because as a default whenever you load up a page inside the browser it will be as a default set to a get method so this will run the code no matter what which is not what we want we only want to run the code if we actually submitted the form so technically we do need to go in and actually set this to a post method and then up here we do also need to make sure when we submit the data we submit it as a post method so go ahead and change these but don’t refresh the browser because I had a point in including a get method and that is simply that if we were to go inside the URL inside the browser you can actually see because I did actually try to click calculate one time before we changed all of this so using a get method you can see we get all this data inside the URL so we get number one is equal to two and operator is equal to subtract and number two is equal to one so we do get a bunch of data inside the URL and this is my point about how we submit data pass it into the URL so we can grab it again and then do something with it however when we use a post method we actually don’t see the data inside the URL even though we do submit it so if I were to go back in here and actually resubmit everything so we want to make sure we save everything inside the index file go back inside and refresh the browser now if we were to go in and type one and let’s just say 1+ one calculate you can now see that we don’t have any sort of data inside the URL we only have index.php but there’s nothing behind it so the data is still there we just don’t see it so the next thing we need to do inside the PHP code after checking for a post submit is that we need to go in and actually grab the data so we can use it for something inside our code so the way we do that is by going in and say you want to create a variable I’m just going to call this one number one going to set it equal to Dollar signore poost brackets and then I want to grab the name of the input that we included inside the HTML form so in this case here the first number was called num one because if it were to go up here you can actually see that’s what we included inside the name attribute so going back down we can include the num one so we actually grab it however even though this is bare minimum for grabbing data from inside a post or a get method so if it had to be a get method we would actually do this instead however this is not seen as being secure let’s pretend that right now inside your website a user goes inside this form and decide to start typing JavaScript code or SQL for injecting into a database or something then all of a sudden we have a hacker under loose that can destroy our website and database and all that stuff inject malicious code into your site and we don’t want that to happen you should always sanitize data whenever you have any sort of data submitted by the user and this is very important to do you should never trust the users whenever you have anything the user can type something into because they will try to break a website we do have a couple of different ways we can sanitize data either using a filter uncore VAR or a filter uncore input and in this case we’re just going to go and use input since that is specifically meant for either post get or cookies uh whenever it comes to sanitizing data from those particular sources so instead of grabbing the data like this instead I’m going to use filter underscore input parenthesis and then inside the parentheses we need to include some data so in this case I need to tell it what kind of data are we trying to sanitize here in this case here we’re trying to sanitize a post method so I’m going to say we have a input uncore post then I need to feed it the actual name of the post method that I’m trying to sanitize so in this case here it is called num one we do need to make sure this is inside a string by the way and then we need to tell it how we want to sanitize it like what kind of method do we want to sanitize it with in this case here I want to make sure we sanitize a float because when you go inside this calculator here you can go in and type a float number so you can write a decimal point uh so what I’ll do is I’ll go in here and tell it that we have a filter underscore sanitize you can actually see we get a bunch of options popping up here the one I’m looking for is sanitize _ float so that’s the one I’m going to paste in here so just to show it here if I were to zoom out it is going to look like this on one line okay it might be a little bit small for you to see but this is how it’s going to look like so the next thing I’m going to do is I’m going to grab the second number so I’m going to copy everything here and paste it below and the first thing I’m going to do is change the variable name so now we’re grabbing the second number and then I want to go and grab the number that had a num two set to the name attribute inside the form now when it comes to the next one here which is the operator we do actually need to do things slightly different because if I were to go in here and actually say I want to grab the operator so we can say we have a operator name that we want to grab if I were to go in and actually say I want to sanitize a string because this is actually a string data type that we’re submitting with the plus minus multiply divide icons here uh it is actually giving us a small error message it is saying that filter sanitized string is depreciated which means that it is no longer recommended that you use it inside your code and this is actually something new that came with PHP 8 because if you were to go inside the documentation inside php’s website you can actually see that they don’t recommend that you use this anymore because there’s a little bit confusion about exactly what you’re trying to do with this method here so instead they do actually recommend that you used HTML special characters instead of using this particular filter input here so if I were to go in I can actually go and just delete everything and say I have this HTML special characters and then I want to go in and actually just grab the post super Global and reference to the operator name and simply do this of course we do also need to change the variable name so we want to make sure we say Operator just to make sure this is also uh changed I know this looks quite confusing in like multiple lines like this but if I were to zoom out you can see this is like how it would look like when when it’s not looking messy and confusing so now that we grabb the data and sanitized it the next thing we need to do is we need to run something called error handlers because error handlers is a way for us to go in and actually try to prevent the user from doing things they’re not supposed to let’s say for example I go inside the browser here and leave one of these inputs empty so I go down and I leave the first one empty and I try to submit this then you can see oh it got submitted but we don’t want that to happen because then that means that things are going to go wrong there’s nothing to calculate in here so what we need to do here is make sure that the user has to type something in into both of these inputs here and I can already feel people typing comments now because some people will tell me that Daniel you can just go inside the form inputs and add the required attribute then people cannot submit the form so let’s go and do that let’s go inside the first input here and let’s add a required attribute at the end here and let’s go and do that for the second one as well so we’re going to go down to number two and we’ll also going to paste it in down there so now technically we cannot go inside this form and submit it without typing something right so if we were to go inside the browser refresh it just go ahead and say yes to continue the submission and if I were to try and submit this without typing anything oh we get this little popup it says please fill out this field and clearly no matter how many times I click it it is not going to submit so this is security right we are now preventing people from submitting I clearly have a point here in case you couldn’t tell um so if I were to go inside the browser and you just know a little bit about browsers what you can do is you can right click inside the input inspect go inside this little developer tool go in and actually delete the required attributes so I can actually go and delete this one and I can also go in and delete the second one so I’m just going to click enter close it down and now I can actually submit it so this is not going to be a valid way of trying to not submit the form without filling in inputs always use PHP for security don’t do any sort of security with front-end languages like HTML CSS or JavaScript in the case of JavaScript you can do it if you’re using it as a server side language but don’t do it if it’s a front-end language okay always do security using a server language so what I’m going to do is I’m going to go back down to my code and I want to start including some error handlers we can actually write a comment here just so we know exactly what we’re doing so I’m going to go and type error handlers so I know exactly what this code does we can also copy this comment here go above and say grab data so we know exactly what this does here so let’s go and add from inputs just to be precise now when it comes to error handlers we can pretty much come up with as many things as we want so for example I could say I want to check for empty inputs because that should not be allowed I could also check for a maximum number of decimal points or if they didn’t type in a number but instead typed in a letter on the keyboard so we can check for many different things the first thing we’re going to do inside this ER Handler here create a Boolean because I want to actually have a Boolean that tells me is there any errors happening inside my error handlers here so what I can do is I can say we have a Boolean called errors and I’m going to set this one equal to false because right now there’s no errors happening inside this code here so for now it is just going to stay as false but if we were to go down and say you know what let’s go and check if the user left any inputs empty what I can do is I can run a if condition and in inside this condition here I can say I’m going to use a function built into PHP called empty and basically what this one does is that allow for me to paste in a variable so for example number one and it is going to tell me whether or not this variable has no data inside of it so right now if the user did actually submit something inside number one so they type something inside the first input here then it will actually have data inside of it but if they left it empty then it’s not going to have any sort of data so if this one is empty or because we learned about this operator in the previous episode if number two is also empty or because we have a third thing from the user which is our operator so I also want to check if the operator is empty then run some error code inside the curly brackets the first thing I want to do is I want to Output a message inside the browser so I want to actually paste in this little piece of text that I have here so just a basic Echo where we Echo out a string which is going to be a piece of text called fill in all fields and then I simply wrapped some paragraph tags around it the paragraph tags are only there because I wanted to style my error message inside the browser so it actually turned red so people could actually see it but you can style this in however way you want to inser your CSS file after doing this I want to go down to next line and I want to make sure that we now set our errors equal to true because now we do actually have an error so this should be true and this is basically all we have to do right here so what I can do now is I can check for a second error message the second one we’re going to check for here is going to be whether or not the number submitted is actually a number or is it a letter because if someone were to go in here right now you can oh I actually managed to again this kind of proves that even though you go inside your form up here and you say that oh it has to be a number sometimes it doesn’t quite work because I can’t type letters in here but clearly I just did so it didn’t quite catch it when I clicked on my keyboard also you can right click inspect go in autofill it with a you know a value or something again don’t use HTML for security okay it’s not going to be enough I have absolutely no idea why actually type something in here but it proves my point so I’m kind of happy it happened so what I’ll do is I’ll go down and I want to create another if condition so I want to say I have a if condition and inside this condition I want to check for something called is numeric so I can actually go and run a build-in function called is numeric and then I’m just going to go and paste in our number one then I want to include a or and then I also want to check for number two remember we’re only checking numbers right now so we don’t need to have the operator included in here but something else we do also need to pay attention to here is that right now I’m checking are these numbers and if so then run a error message and that’s not really what we’re trying to check for here we want to check if the these are not numbers right so either I can go in and say is this equal to false then do something or we can do it the professional way and go in and just write a exclamation mark in front of is numeric because this is checking is this false and the same thing of course we need to do to the second one over here so right now if these are not numbers then run a error message inside this condition here so I’ll just go and copy paste what we have up here and I’ll change the message so instead of fill in all Fields I’ll instead say only write numbers and paste that in instead at this point here you can include as many error handles as you want to have inside your code I’m just going to go and leave this for now otherwise this is going to be a very long episode so let’s just go and include these two error handlers here and say that’s that’s okay for now so after checking for errors I want to go down and I’m going to create another comment and I want to say calculate the numbers if no errors then what I want to do is I want to run a if condition and I want to go in and say if there were no errors then run this calculation inside the curly brackets so the way we do that is Again by checking if errors up here is equal to false because if it’s equal to false then it means we had no errors because we didn’t change it further down so now we actually want to run the calculation so if errors is equal to false by adding the exclamation mark in front of it after doing this we want to go inside the curly brackets and we want to actually check what kind of operation we need to do here did the user want to plus or minus or multiply or divide we don’t really know so we need to run a switch statement in order to determine what exactly they submitted so going in here we can create a switch say we want to add a pair of parentheses curly brackets and inside the switch condition I’m going to go and say we want to include the operator because the operator is going to decide what exactly we’re doing with these numbers here so I’m going to paste it in because that is the one I’m looking for and inside we’re going to go and include a couple of different cases so I want to say case number one is going to be if we have a string that is equal to add then we add a colon and then we add a break just for now then in between these two we want to actually add in what is supposed to happen so in this case we want to actually add the two numbers together so what I’ll do is I’ll say that we have a variable called value that we’re creating right now and I want to set this one equal to variable number one plus variable number two semicolon and this right here is going to be the first calculation that we do inside this switch statement so now we just copy paste it because we have a couple more we have three more we need to paste in so we’ll paste in like so and then we’re just going to go and change the cases so right now we have subtract and then we also have multiply and we have divide and just to mention it here these strings here are what we typed in inside the options inside the form so if we were to go up inside the form you can see that these are the ones that we included in here so that’s the one that we actually refer to inside these cases down here now we do also need to make sure we change the operation so this is going to be minus this is going to be multiply and the last one is going to be divide and we do also want to add in a default because if something happens and something goes wrong and we don’t actually have any sort of data inside the operator or something something it could happen something might happen Okay so you have to think about everything here what could go wrong at some point so let’s go and include a default which is going to be an echo and this Echo is simply going to Echo out a error message so I’m just going to copy paste what we have up here paste it in and then I’m just going to say something went wrong something went horribly wrong just to be a little bit dramatic here so now the last thing we need to do in order for this to technically work is to go after the switch statement and actually output the calculation that we just calculated here so what I’ll do is I’ll go below here and say we want to Echo and I want to Echo out a string which is going to be a paragraph because I want to actually have this styled inside my browser so I’m going to close off the paragraph as well then I also want to go in and add a class because I do actually want to style my text inside the browser so I’m going to say I have a class and now something is going to happen and you may have noticed this on the previous Echoes up here because if I were to go in because typically when we have a class that equal to something we need to have double Cotes right how however if I were to do that we’re actually canceling out the surrounding string double quote so we can’t really do that if we were to try and write something in here you can see oh that is not working out it’s actually giving me an error message so something we need to talk about here is the use of single quotes because you can either use a single or a double code for for example creating a string so I can actually go and do this instead so we just use a single quote or we can use a double quote and the same thing goes for HTML you can either use double quotes or you can use single quotes and by using single quotes and mixing it together with double quotes we don’t cancel out the string so to speak so I can actually go inside my class and I can say I have a class name set to celc dash results and in this simple sense we now have something that works okay so we’re not canceling out anything here so inside the I want to Output result is equal to space then I do actually want to add in my value which is right now up here so we have a value variable so what I’m going to do is I’m going to concatenate things so we could actually just so it’s a little bit easier for you to understand go in here and delete the last ending paragraph tag and after the double quote I’m going to concatenate my variable and then again I want to concatenate a string because we need to close off the paragraph so I’ll go ahead and say we have a closing paragraph graph and do something like this so now at this point here this is technically going to work however there is going to be something slightly off about this code here let’s say this switch statement here gets run and the default case down here is the one that is actually being used because something goes wrong and we don’t actually run any of these cases up here what is going to happen is we’re going to get an error message because variable value is never created we don’t actually create it inside the default value down here so we don’t actually have it when we reference to it inside the echo down here so it’s going to Output a error message so what I’m going to do is I’m going to go right before the switch statement and I’m going to declare the variable so we have it no matter what so we don’t get an error message inside the browser and now typically we would be able to just go and declare the variable like I just did here so we just have a variable but we don’t actually assign any sort of data to it however in some cases that is actually going to throw a error message for some people it is not actually going to work it’s going to have a reference error or something so what we want to make sure we do here is we want to actually assign something to it as a default which is going to be zero the reason I’m adding zero is because this is going to be a number or a float that has to be assigned to this value here so this is going to be a float data type that is assigned to Value once we actually start doing those calculations down there we did talk about this in the previous episode where we talked about data types so we create variables that don’t actually have any sort of data assigned to it and the fact that this is not something we should do inside PHP because in some cases it is actually going to throw an error message so we do need to make sure we assign a default value to a variable inside PHP again we can keep adding to this project here but for now this is going to be okay so we just want to declare the variable before the switch and everything should be okay so having saved this let’s actually go and test this out inside the browser so if I were to go inside my browser and type in number one actually we need to refresh everything first so that is important don’t worry about those error messages those are only there because I went into the developer tool previously and deleted the required attribute so don’t worry about those right now all the changes we made to the code will take effect now as we click the next time on the calculate button okay so don’t worry about those error messages right now so going inside I can go in and say 2 + 2 is going to be equal to 4 so it’s working yay but now if I were to go inside the form and try to submit it without having any sort of data typed into let’s say the first one up here then we’re going to get a well first of all please fill out this field but if we were to go in and actually remove the required attributes you can see we’re going to get our error messages so in this kind of way we can create a cool calculator inside our website using all sorts of PHP code that we’ve learned up until now so I can actually go in let’s go and test out multipli so we can say 10 * 2 is going to be 20 so we can do a bunch of different calculations and just kind of like experiment with it and and try out what we just created together here so with that this is how we can build a calculator using PHP I hope you enjoyed this lesson here because this is a stepping stone to learning PHP this is the moment where people are going to go and say oh that’s pretty awesome now we have hope that we can actually learn PHP and do something inside websites with it hey so this is a pretty big moment I think when it comes to learning PHP so with that said I hope you enjoyed and I’ll see you guys in the next video [Music] so back in our data types episode we talked a bit about arrays but we haven’t actually talk specifically about how we can create arrays and change them and what we use them for and how to create different arrays with different types of keys inside of them so there’s a little bit we need to talk about when it comes to array since an array is used very often inside PHP the previous episode where we talked about how to create a calculator where we did a small example together uh could have been done a little bit easier if we did use an array in order to Output error messages inside the browser so arrays is something we have to talk about now an array is a type of data structure that allow for us to store multiple values inside one variable so we can have one variable that is equal to many different types of data so we can easier manage many pieces of data at the same time so let’s be a little bit boring here and create a list of fruits because that is going to be a very good way to kind of show you the example of what I mean when I talk about storing many pieces of dat inside one variable because if I were to go down here and actually create a fruit variable and call it fruit one I can set it equal to a apple now the problem here is that if I want to have another piece of fruit and store that equal to another variable then I would have to go down and copy this down and say we have something called fruit two and set it equal to a pair and doing this is not really a good idea because all of a sudden we have all these different variables that could just have been combined into into one variable and then stor it in there so we could just access that one variable to grab all the different fruits inside my code so let’s say instead of doing all of this I’m going to go and delete back and I say I want to have a fruits variable now I’m going to turn this one into an array and there’s two different ways we can do that either I can go in and say we have an array data type parenthesis and then inside the parentheses I can go in and say I want to add a apple a banana yes that’s how I say banana I think you say banana like that might sound a little bit more correct so I’m going to go and add in a third piece of fruit which is going to be a cherry and now we have all three pieces of data inside one variable here inside an array now there is another way to write this though which is a little bit shorter and in my opinion just a little bit easier to work with so if I were to go down here and copy it I can actually go in and instead of writing array I can wrap this around a pair of square brackets so I can go in here and add these square brackets and just like this we now also have an array and just to make things a little bit easier for you what you can also do if you wanted to is you can actually add this down to multiple lines just to make it a little bit easier for yourself it’s really a personal preference if you want to go inside your code and have everything separated on a separate line or if you want to have one big line with everything inside of it I do also want to mention one more thing here when it comes to this particular way of writing things because you can also add a comma at the end here or inside the other one up here we can add a comma which is called a trailing comma this is something that we weren’t allowed to do before PHP 8 but now the PHP 8 is out we can actually do this if you at some point expect to add more pieces of data behind it so this is not really something where you have to like make sure there’s no come at the end because oh no then it’s going to break things but we can actually leave in a comma if you want to personally I don’t like to add a comma at the end because that’s how I’ve always done it because that’s how we were supposed to do it but just to tell you that you don’t break anything if you have that last comma so now let’s go and delete the top array up here and just worry about having one array inside our code and talk a bit about how we can access this data here when we create an array we have something called a key which is a way for us to access a certain data inside an array as a default the array indexes are actually going to be a integer which means that we can go in and just use a number in order to access a certain piece of data inside the array so what I can do is I can go below here and say I want to Echo out my array called fruits square brackets semicolon and then inside the square brackets I just simply refer to the index that I want to access what I mean by index is that we go inside the array and the first piece of data is going to have an index as zero so we can actually write that over here just so it makes sense for you the second piece of data is going to have an index as one and the third one is going to have an index S2 I do often experience that people have a hard time wrapping their head around starting at zero when they have to to count something when it comes to programming we always start at zero so the first piece of data is not going to be one but it’s going to be zero so let’s say I want to access banana then I would actually go inside the brackets down here and say I want to Echo out fruits with the index of one so where to do that go inside my browser and as you can see I tried to dim it down a little bit so it wasn’t completely white and burned your eyes out um but if we were to refresh the browser you can see we get banana so in this kind of way we can Echo our data from inside an array using a index number now let’s say I also want to go down and actually add another piece of data to this array here what I can do is I can refer to my array so I can go ahead and grab the name of it and anytime we refer to an array we always need to make sure we add the brackets behind it because this means that this variable is an array and I want to assign something to it so we can set it equal to let’s say orange because that is another type of fruit if I were to do this it is going to take the orange and move it behind the array so now we have apple banana cherry and orange behind it and that of course would have an index as three so if we were to go below here and say instead of echoing out down here we’re going to go below and Echo out a index of three and if we were to do that go inside the browser you can now see we get orange and in the same sense we can also go in and say we want to change a certain part of the array so let’s say instead of banana banana banana we can go in and say that okay so we don’t just want to assign the array to something new but I want to go in and replace the index number one with orange so now we’re actually replacing banana with orange so if we were to go down here and say I want to Echo out the index one save this go inside the browser you can now see we’re going to get orange so now we no longer have banana inside the array at least when it comes to below this line of code here in between here by the way we still have banana as being index number one but as soon as we add in this line here anything below is not going to have banana inside the array but now we do also have a way to delete data from inside the array so if I want to remove a piece of data I can go in and use a buil-in function inside PHP which is something we will talk about in a upcoming lesson because build-in functions is something we use all the time we did also use a bunch of build-in functions in the previous video where we talked about how to create a calculator uh but we haven’t talked about buildin functions yet but we will get to it so what I’ll do is I’ll use a build-in function called unset and I’m going to say I want to grab my fruits array and then I want to say I want to remove the index number one so in this case here we still haven’t replaced banana because we took out that line of code so now we no longer have banana inside the array so if I were to actually try to Echo this out inside the browser using the echo down here you can see that we’re going to get a error message because oh undefined array key one because we have no data inside of it but now you could argue that using unset here is not really going to be deleting an index from inside the array because technically we might want to have the Cherry being moved back on index because right now we have an index as zero and as two and index number one has nothing inside of it so if I just want to completely take out banana instead of just deleting it or unsetting it we can actually go in and use another build-in function called array uncore splice which is another function we have that we can use where we go in and give it a couple of parameters so in this case here I’m going to tell it which array are we talking about and in this case we’re talking about fruits then the second parameter is going to be where do we want to start deleting from so again we count using indexes so if I were to go in and say okay so we start at index number zero so I have to refer to index number zero and then from zero and then one forward I want to delete inside this array so we’re going to delete one length ahead which means we’re going to take out banana and doing this and then going inside the browser refreshing you can now see that index number two is going to be Cherry it is important to point out here that we do also use array splice to insert other arrays or other pieces of data in between certain array elements but I’ll talk about that a little bit later at the end of this video here so now that we know a little bit about arrays let’s go and talk about keys because right now we’ve used numbers which might not make a lot of sense if you want to have a specific label for each index inside the array so what I can do is I can go and delete what we have here and instead let’s go and create a array called tasks as in like house chores or something so what I’ll do is I’ll set this one equal to an array and let’s go and move this down to separate lines cuz that is going to look a little bit easier for the eyes here so in this case here let’s go and say I want to add a name so I want to say that Daniel has a certain house chore inside this house here what I can also do is I can add in a second person so we could also say we have freedom I can also add in a third person Bess and I can also go in and add a fourth person so in this case here let’s say Bella so in this particular array here I have a bunch of house chores and each person has a name inside this array because they have to do a certain house chore but how can I assign a certain key not as a number but as a string to each person so I know which person is doing what inside this house so what I can do is I can go inside and create what is called a associative array which is when you have an array that has a bunch of strings as Keys instead of numbers this means that I can go in here and say that I have a chore which is called laundry and I can assign Daniel to this particular key so by creating a string and then pointing to a value we can do it in this sort of way in order to create a different types of key so we can actually go ahead and just copy this down and I’m going to go and change the name for each one of these so the first one is going to be laundry the second one is going to be trash and we do also have a chore called vacuum so we can say vacuum and the last one is going to be dishes so what I can do now is I can actually go down below and Echo out a piece of data from inside this array but instead of using numbers I can go in and say we have an array called tasks and I want to reference to a certain key and let’s say in this case I want to figure out who’s doing laundry inside this house here so I can go ahead and say I want to refer to the laundry which means it’s going to Echo out who’s doing the laundry inside this array so I can go back inside the browser refresh it and you can see we get Daniel so this order of way we can create a associative array and actually have a label for each of the data inside the array so now we talked about how to Output one piece of data from inside all of these arrays but let’s say I just for developer purpose want to know exactly what is inside the entire array just to see if something went wrong inside the website you know just to kind of like double check what exactly is inside a specific array what I can do instead of echo is I can actually go and use something called printor R parentheses simp colon that I can paste in the name of the array that I want to actually print out inside the browser so in this sort of way I can go and save this go inside my browser and then you can see we get a complete list of all the data inside this array and right now because this is a associative array you can actually see we get the key then we set it equal to a value then we get the next key and then we set it equal to another value but had this been a index array using numbers then of course this would have been zero pointing to Daniel and then one one pointing to feta and so on and let’s talk about a few other built-in array functions that we can use now there is a lot of them we can use but I just want to show you some of the more basic ones now we do also have something called count which means that we can actually figure out how many pieces of data is inside an array so we’re going to use count parenthesis and then we’re going to go and paste in the array so I can go in and paste it in and then you can see when I go inside the browser that it’s going to tell me you have four pieces of data inside this array here one users of this particular function could be if we were to grab data from inside a database because when we grab data from a database it gets returned as an array so we can actually use this function here to count if we actually had any sort of data return from the database so that’s one particular usage of using count inside PHP but we do also have other pieces of functions we could use for example if I wanted to sort an array I can do so in a ascending order which means that if I were to take this task array up here and put it inside the parentheses I am now sorting it ascendingly which means that we’re going to take letters like a first and then it’s going to be b c d e and so on which means that it’s going to go in and sort these alphabetically if any of these values had been numbers then of course one would come first or actually zero would come first and then 1 2 3 and so on so we were to do this and go down and say print R to get this array you can see that we’re going to get the array but it’s going to be in a different order now so if we were to save this go inside the browser refresh it you can now see that b is going to come first and then Bella Daniel and then feta and it’s actually going to give it to me as a indexed array not as a associative array then we do also have one called array push and for that one we do actually need to use a nonassociative array so if would have commented this one out and paste in the previous one we did called fruits I can go in and say I want to take my fruits and I want to use a array push and say I want to grab this fruits array put it inside the array push function which means that we’re now pushing a piece of data at the end of the array which means that I can go in add the array that I want to add some data to and then tell it what kind of data I want to add so in this case here I can say mango and of course a semicolon at the end here and then I can actually go and print it out so we can take the fruits array go inside the print R and go inside the browser and then refresh it and then you can see we have mango pushed in at the end here of course this is very similar to just going in and just like we talked about at the very beginning just going in and grabbing the array so we’re going to say fruits we have an array and then I said equal to a new piece of data so this would actually do the same thing in this case here and the reason that’s relevant is because if I were to do the same thing to a associative array so if I were to comment out my fruits array here and instead let’s say we’re talking about the task array up here which is a associative array which means that we have these different indexes which are actually strings if I want to add another piece of data at the end here I can’t use array push because that only works for indexed arrays so would actually have have to go in and use my last method down here so I’m going to go and say I have my array tasks and then inside the brackets I’m going to go and add in a new string which is going to be the key so I can say we have something like dusting which is going to be assigned to a person called Tera so this is how you would push in a new piece of data at the end of a associative array so if I were to actually go down and print out this array here so we can actually just delete what we have up here and say we want to print out tasks inside the browser you can now see that we’re going to get Terra at the end here for the dusting assignments and the last build-in function I want to mention here is one that we have talked about already so if we were to go in and delete everything except for my fruits array because that’s the one we’re going to use in this example here and let’s go ahead and write down the array undor splice that we already used previously so we’re going to say splice and parentheses and semicolon so like we talked about if I wanted to delete a certain piece of data inside this array and I wanted all the other indexes to move back one slot what I could do is I go in and say okay which array are we talking about we’re talking about the fruits array right so I put that in here and then I say from where do you want to delete from so I could say for example I want to delete from index number one and then I want to delete one ahead of it so right now we would actually take out the cherry and then replace it with something else but let’s say I don’t want to delete something but I just want to insert some data in between this array somewhere what I can do is I can say I don’t want to delete anything by writing zero and and then I’m going to go and add the name of another piece of data at the end here so I can say I want to add in a string and I’m just going to go and add in mango just to have it here so if I were to actually print all this inside the browser you can notice that we now have mango in between banana and Cherry so I paste it in actually I’m mistaken here because I’m not actually going to insert it in between banana and Cherry we’re actually inserting it after Apple so in between apple and banana and the reason for that is that we did actually say to start at index number one which is here so all this data is going to get pushed over to leave space for the new data so that’s what we’re doing here uh so if I want to put it in between banana and Cherry we have to write two because we’re now going in saying 0 1 2 and this is where we want to insert the data which means all this data here has to move over in order to make room for it so if we were to save this go inside the browser and refresh it you can see that we now have apple banana mango and Cherry but this is not just when it comes to one piece of data so what I could do do is I could insert an entire array inside another array so I can actually go ahead and say you know what we have another array up here I’m going to go and call this one test or something just rename it something so I’m going to set it equal to a array and I’m going to go and insert some more pieces of data in here so could actually say we have mango and I do also have strawberry and then instead of saying I want to insert mango inside these when I splice them I can actually refer to this array up here and just say I want want to grab this array I want to go into slot number two I don’t want to delete anything from inside the array but I do want to merge test into that array so if we were to save this go inside the browser you can now see that we have many pieces of indexes inside this array here so in this kind of way we can create arrays and manipulate them and change data and replace data and just do all sorts of things when it comes to arrays because arrays is something you will be using quite a lot inside PHP code for all sorts of purposes so learning how to do arrays is something that is very important to do now there is one last thing we could talk about here which is a little bit more complicated than just talking about arrays which is something called multi-dimensional arrays and essentially this means that we have an array that has arrays inside of it so now we’re going Inception here there’s an array inside an array so let’s say I have an array called fruits and I’m just going to go and move everything down to the next line just so we have it a little bit easier to see and let’s say instead of calling this one fruits I’m going to call this one food and then I want to have different food types inside this array here and instead of Apple we can actually go inside and say we have another another array by using the array keyword and then go in and say we might have something like so I can say we have a apple and we also have a mango and in this sort of way we now replace one of the indexes inside the food array with another array which means that if I want to refer to for example apple or mango I need to go down below and I want want to Echo out the food array and say I want to grab a certain index and in this case here I want to grab the index number zero because that is the first slot inside this array so we’re going to say zero but then I need to tell what the index is of the array inside index number zero so I need to go after add in a second pair of brackets and go in and say I want to grab the first index which is index number zero and Echo that one out which is going to be apple I hope that makes sense okay so we’re we’re going to go inside the browser and as you can see we’re going to get apple because we’re grabbing the uh first array inside this array which has Apple a mango inside of it so if I wanted to grab mango I could also go in and say I want to grab the uh first index which is going to be the second piece of data inside this array here so we to do that we now get mango and if we wanted to grab banana then we just going to say we want to grab the first index and don’t add in the second pair of brackets so we can go in and then get banana but now what about associative arrays cuz we can also do that if we wanted to so let’s go and go back to our Apple examples now it’s just a very basic array uh let’s say I want to add in a food group and I want to say this one is going to be fruits and I want to point to a array which has a bunch of data inside of it so I could say fruits is going to be apple I do also want to add in banana and then I want to add in a cherry and then instead of having more fruit down here below we can also go in and just just copy this paste it in below and say we might want to have meat and then we can have something like chicken we can also have fish and then maybe something like sheep just so we have a little bit of data inside of here or just have two pieces of data you can also do that if you want to you don’t have to have three every single time and let’s go and add in a third group of food so in this case if we could for example say vegetables vbl I think that’s how you say it in English you write it out veg but you say it vexes okay I do know the difference uh so what I can do is I can go in here and I can for example say cucumber and let’s go and add in a carrot so in this sort of way we now have a bunch of arrays inside an array so we have a top category called food and then inside of here I can now refer to a type of food so if I want to grab something within the vegetables I can go and add that in then afterwards add another pair of brackets and say I want to Output index number zero which is going to be cucumber so going inside the browser we can now refresh and then you can see we get cucumber and of course you can also go inside this array here and add this as an associative array so if you don’t want cucumber but you want to have something pointing to cucumber you can also do that so you have a associative array within an associative array um but just to tell you that this is how you would normally go around doing this if you want to have an array inside an array and this is something we call a multi-dimensional array so with that said we now talked about arrays in pretty detail I think for now so with that said I hope you enjoyed this episode and I’ll see you guys in the next [Music] [Music] video so up until now in these many lessons we’ve had we’ve talked a bit about build-in functions inside PSP which are functions that exist inside the PSP language that we can use in order to do many different operations inside our code and there are so many functions out there that we can’t do one episode and talk about all of them since it’s going to be a very long episode if we had to do that and honestly I don’t know all the functions because there’s so many of them but what we can do is we can talk about some of the more popular ones that you might want to use at some point inside your code for various things so in this episode we’re going to talk about some of the functions that are built into phsp that we can use for different things so inside my document here I’m going to scroll down so we have our little PHP section and the first functions I want to talk about are some that are related when it comes to using strings inside your PHP code so let’s go and create a string here so we can actually do something with it so I’m going to create a variable I’m just going to call it string so we have some kind of name for it and then I’m going to say hello world it is important to mention here that whenever we create a function or reference to a function inside our code we do so by referring to the name of the function followed by a pair of parentheses because the parentheses are going to be used to call upon that function so we can do something with it so what I can do here is I can say we want to Echo something out and I can call upon a function called string length which is written by saying St Len and that stands for string length and what we can use this for is to call upon a function in order to tell us how long a certain string is so if we were to actually save this by pasting in the string inside the parenthesis refresh the browse so you can see we get 12 and the reason we get 12 is of course because we have 12 different letters or empty spaces inside our string so if we also count the empty space in there we do have 12 different characters we do also have a function that can go in and actually tell us the position of a certain string inside this string here so what I can do is I can say something like string position and string position is going to require two different things first we want to have the actual string that we want to get the position from so in this case here our variable string then I want to say comma which is a separator to add a second parameter inside this function here and then I can tell it what I want to see the position of inside the string so in this case I could say okay so what is the position of O inside this function here so in this case I’m can go down and say I want to get o save it go inside refresh and then we can see we get four and the reason we get four is because we always start at zero when we count inside programming so 0 1 2 3 4 which is going to be the O so now we got the position of O inside this string and it’s not just when it comes to a single letter we can actually check for more than just one letter so I can go in here and say I want to check for wo so in this case that would be this location right here so I can refresh and then we can see we get six now we do also have a function to replace a string inside another string so what I can do is I can say something like Str strore replace and by doing so I can also go in and say what do I want to replace inside this string here so I’m just going go to delete everything we have except for string so the first parameter is going to be what do we want to replace so in this case it is going to be world and I want to replace it with something else and in this case we can just say Daniel so we say hello Daniel inside this sentence so if we were to save this go back inside the browser you can see we get hello Daniel because I replace world with Daniel then we can also go in and use another function in order to to convert all the different letters to lower case so if I were to go in and say I want to string to lower then I can save it go inside refresh and then we can see everything is lowercase no longer have these uppercase letters inside this sentence everything has been converted to lowercase and the same thing we can do it the other way so we can say string to Upper which would of course do the opposite so were to go in you can see everything is uppercase and if I want to be a little bit more complex here what we can also do is we can do something called substring which is something something that I do occasionally use so if were to go in here so I can say we have a sub string by saying subst and what I can do in here is I can go in and say that I want to grab a certain part of the string here so the first parameter is going to be the actual string so in this case that this is going to be hello world then I’m going to say comma and then I want to say where do I want the offset to be so where do we want to start from and in this case here I could say we want to start from the index of two so if were to go inside my string and count this is going to be zero one two which means to be started here and then I want to have a length set to two so from here and then two forward which means that if I were to save this you can see that we get LL and we can actually do something quite smart here because if you want to do something in a very long string and you want to start from a couple of letters into the string but also end it a couple of letters at the end of the string instead of having this long string and then saying okay so you know 22 characters later I want you to like stop grabing the string instead what I can do is I can say minus 2 which means that it’s not going to start counting the index from the start but from the beginning so in this case here it is 01 2 which means we start at L and then minus 2 is going to be 012 which is the other L over here so as you can see we get low worldl cuz right now that is what we’re grabbing and with this we do also have a another one called explode which sounds very dramatic but essentially what this one does since we now have already talked about arrays in the last episode this is one we can actually talk about uh it takes a string and it says okay so where do you want to take apart this string and then all the different parts you take apart are going to be placed inside an array because we might have multiple pieces of Parts when we explode this string what I want to do is first of all remove the parameters inside of here except for the string and I want to go in and say that the first parameter because this has to be the first one is going to be what do I want to be the divider whenever I explode the string so let’s say I want to take any sort of spaces inside a string and divide the entire string depending on the spaces what I can do is I can say we have a string and that is just going to be a space which means that now it is going to take all the spaces inside the string and cut it like a scissor which means that now we have hello and world two separate strings and it’s going to place these inside an array now in this case here of course we can’t Echo it because that would actually create a error we can actually check this out because this is actually going to be a array so instead what we can do is use another build-in method called print R which is going to be printing out um I believe it stands for print readable if I remember correctly so essentially it’s going to print out data in a readable format so we can actually read it which in this case because of an array uh we might want to read what is inside the array so what I can do is I can just include it inside my print R and refresh it and then we can see we to get hello world so if I were to go in here and just say that we have more than one space so I can just separate the word a couple of times you can see that we get a even longer array because we have more divisions or explosions inside this array here so now having talked a bit about string functions we do also have some related to math inside our PHP code because in a lot of cases we might want to do math at some point uh so having some math functions is something that is really useful uh so let’s go and delete our function down here and also change our string because right now we don’t need to have a string uh but we do need to have some numbers so we can actually perform math inside this little example here so what I’ll do is I’ll create a variable and call it number and then I’ll go in and instead of a string I want to say something like minus 5.5 just so we have an example to use the first one I want to show you is a function called apps which stands for uh absolute I believe you can actually go in here and check it out because there is a really smart function inside our editor where we go in and hover our cursor on top of a function and then it gives us a little description here and as you can see it says absolute value uh so we can get the absolute value of a certain number so if we were to go in here and paste it in so in this case when we have minus 5.5 it is going to get the absolute value which basically means that it’s going to get uh the value no matter if it’s minus or positive it’s just going to get the actual value so if we were to save this go inside you can see you get 5.5 especially inside my gamep courses on the channel we use apps a lot to get you know the absolute value instead of having to deal with negatives and positives and stuff like that so it’s just a really neat function to have we can also round this up so we can use a function called round and this is basically going to do what you think it’s going to do it is going to round this up to the nearest uh whole number so when I refresh it you can see we get minus 6 then we also have something called p w which is going to be the power of or exponential expression so in this case here we can’t really use number because that is not really how this works but what I can do is I can feed it to number so I can say two comma 3 so again this would be exponential Expressions which means that we have to say 2 * 2 which is 4 and then 4 * 2 which is 8 in this case here so if we were to save this refresh it you can see we get eight then we can also do the square root of something so we can say sqr t which means that we’re going to get the square root of one certain number so let’s say two in this case and then you can see we get 1.4 it might have been a little bit easier if we did something like 16 just to like show this in a little bit more normal way so 16 the square root of that is going to be four but now another one that I have as a favorite is one called random so we can actually go and say R A and D which is going to give us a random number between two numbers so I can go in here and say I want a random number between one and 100 and in this case here we’re going to go in when I refresh it oh okay so in this case it’s going to be 51 if I refresh again oh it’s going to be 49 now it’s going to be three now it’s going to be 6 now it’s going to be 10 so it’s just going to keep feeding us a random number each time I refresh the browser I’ve seen people use this one especially when it comes to reloading images inside the website as they’re developing a website because your browser do have something called a cache that is going to store certain data so it’s easier and faster to load your website the next time you refresh it so when you’re sitting there develop and constantly maybe swapping out a certain image and it’s not really changing when you refresh the browser because oh it stored the cash of your last image so it’s not showing the new version then you can use this one and put behind the image name in order to get a new image but again that’s more of a developer trick you can use but it’s not really something you should use for releasing a website since there’s a a reason why a browser stores a cash of your images that’s because it’s easier to load next time right so now this was a couple different math functions we could use but what about arrays cuz we learned about arrays in the previous episode uh we do have quite a few different array uh functions I did cover some of them in the last episode but we do also have many others I could show you so let’s just go and create a array called array and inside of here we can fill it in with fruits just like we did in the last episode so we can say apple we can also say we have something like banana and we do also have orange and then we can just manipulate this array using many different functions the first one is going to be one called count which is actually one that we use quite often when we pull data from a database I do think I showed that one in the previous episode but let’s just go and talk about it here so if I were to say Echo and say I want to Echo out a count function that has the array inside of it we can actually see how many pieces of data are inside this array here so we do that you can see we get three because we have three pieces of data so let’s say we have an example where I pull data from a database and I need to check did we actually get anything from the database because if I didn’t then there’s no need to run a bunch of PHP code because we didn’t get anything from the database so this is going to be a very useful one that you will get to do a little bit of when we actually start talking about databases inside my episodes here uh so this one is worth remembering but now we do also have one here where we can go in and say is something an actual array so we can say is array so isore array and this one is going to give us a true or false statement so in this case it’s going to be false so it’s going to be true and like we talked about when it came to our data type episode a zero means false and a one means true so in this case it did actually return as true because this is in fact an array and we did also talk about a few other ones in the last episode that we can just briefly uh just mention in this one so if I were to go in here and say we have something called array undor push we can now push in data inside our array at the end of the array so I can go in and say we have this array here and I want to add a piece of data which is going to be a a kywi just to add something else to it so if I were to actually print R this one because in this case it would do actually need to print R in order to see all the data and of course I want to have this after we array push so I’m just going to move it down to the next line here save it go inside and then you can see we get kyv inside our array at the end there but now one we didn’t talk about in the last episode is how to remove data from inside the array so what I can also do is I can go below here and say that I want to do something called array pop so array po o and inside this one we just need to have one parameter since we’re only removing the last array index if we were to save this one and actually Echo it out or print R it out inside the browser then you can see we get the same array but now kyv has actually been removed at the end here so we no longer have it again and we can also go in and use another function where we actually reverse the entire array so if we were to go in here and say we have this array here but this time I want to array uncore reverse the array so parenthesis and then I’m going to insert the array inside the parentheses here then you can see we get everything but it’s reversed so we get orange first banana and then Apple and now in the last episode we did talk about something called array undor splice which means that we’re splicing two arrays together and merging them into each other uh but we also do have something called array uncore merge but merge is a little bit different because it’s going to take the data and put it at the end of the first array whereas splice is going to allow for you to put it anywhere in between any of the the existing data inside the first array so if we were to go in here we can also do array uncore merge so we’re going to say merge and then I want to have another array up here so I can just copy paste this down call this one array one this one array two and let’s go and change some of the data inside of the second array so again we could just use kyv and say we want to merge these two together so we were to do this I can say that I want to have the first array which is array one and the second array which is going to be array two too and when we do this I can go back in print it out inside the browser and then you can see we get kyv which has been placed at the end of the other array so all the data inside the second array here is just going to get added to the first array up there because we merg them together at the end of the first array so just a few more array functions you could know about after we talked about in the last episode but we do also have something else because inside phsp in some cases we do also deal with dates and time and when it comes to these we do need to know how to get the date and time because for example again if we talk about databases in a lot of cases you might want to know exactly what the time is when you upload certain data to a database so you might want to have a datetime format that you need to use in order to get the date time so let’s go and start by echoing out a certain date so what I can say is we have a date function and inside this date function I want to tell it the format that I want to Echo out the date and I will include a link in the description for all these different formats if you want to see them uh but essentially if you want to get the full year you can go inside and use a capitalized y then you can separate it with a dash and then we want to get the month the day and then we can also get the time which is going to be the hours colon then we want to get the minutes and also the seconds so in this case if we were to go inside the browser you can see we get the uh full date with the year month day and the current time inside our little uh function here but now we do also have something else we can use so if we were to go down here and say I want to Echo out the time so we’re going to say time parenthesis then you can see we’re going to get this weird long number inside the browser here so you can see we get this random string and you might be thinking hm so what does that do well let’s try and refresh the browser again and see what happens oh it updated okay so if I click this every second you can see it’s updating by one number every second that I click because this is the seconds since a certain date in history I can’t remember the exact date but what we can do is we can go and hover our Mouse CR on top of the function oh and it actually provides a link to the pspnet website so I’m going and open this one and then you can see we get this little link here what explains that it is since January 1st 1970 that we do get the amount of seconds since then and the reason this is something we can use is because you might want to get a certain time difference between now and now so we can actually subtract these two different numbers and get the amount of seconds and this by the way is called a Unix Tim stamp which we can also use for the next function where we actually go in and we want to know what is the Unix timestamp for a certain date at some point so what I can do is I can actually create a string so we can just go and call this one variable date and then I can set it equal to a random date at some point again using the same format that we talked about before for which was uh the date time format so I can go in paste in a random date from my notes here and then I can go in and say that I want to get the string to time Str str2 time and then I can paste in the date and see what is the Unix timestamp for this particular date here and in this case here it’s not going to update every single time I click it because we’re getting a fixed date or fixed time of seconds from 1970 the 1st of January until this particular date that I have pasted in here which is 2023 uh the 11th of April which is today and we have many other different types of date functions you could use inside your PHP code and the same thing goes for the strings and math and we also have something when it comes to like files inside your uh your PHP or files inside your website you can delete files or do something else to it using functions and I will leave a link to many different functions you could be using that you might want to check out and I will have that inside the description of this video here so if you want to check out something on your own then you’re more than welcome to do so but for now these are some of the different functions you can use in order to change things inside your phsp code so with that said I hope you enjoyed this little episode on built-in functions in next one we’re going to talk a bit about userdefined functions which is a lot more fun because now we actually get to create our own functions which means that we can start creating a function called something specific followed by a pair of parentheses and then we can decide that we want to add parameters to this function to change how the functions work and stuff like that and functions is something that we use a lot inside our code pretty much constantly anytime you create anything using phsp uh it’s going to have functions inside of it so functions it’s important and that’s what we’re going to learn the next episode so with that said I hope you enjoyed this one and I’ll see you guys next time [Music] today we’re going to learn about something called userdefined functions inside PHP and this is the moment where we start moving into a little bit more of an interesting point inside our PHP lessons because userdefined functions is where we can start creating our own functions inside PHP in case there is some kind of function we need that isn’t built into the PHP language user defined functions is something use constantly inside our code and I do mean constantly because we use functions in order to not have to rewrite code as well over and over again because if I need a certain piece of code to do something and then later inside my application I need to do the same thing instead of having to recreate the same code in two different places we can use this userdefined function just to reference to it so we run the same code but the code is just sitting in one place somewhere I do also want to point out here because I do remember back when I was learning PHP like 12 years ago when I took my bachelor’s degree in web development that the teacher would ask me inside the exam so what do we use a userdefined function for and I would say well we use it to do things inside our code but the answer my teacher was looking for was okay so we need to use a user defined function for one particular thing so if you want to create a bunch of code your function should not have a ton of code inside of it doing a lot of different things it should have one particular purpose in mind so don’t use a function to store like an entire script inside of it it’s just meant to do one particular thing we’ll get to do a little bit more examples so you can see what I mean so you know not creating a lot of code um so what I want to do here to begin with is let’s go ahead and just create a function just to see how do we create a function and how do we name it and how do we add parameters to it and and write code inside of it uh so what I’ll do inside my little PHP script here is I’ll go in and I’ll use the function keyword which means that now we’re creating a function and I want to go in and give it some kind of name and you can name this function function whatever you like we can come up with any kind of name that we think is appropriate for this function but there’s of course some naming conventions just like with variables and that kind of thing so the way we usually do it when we start a function is we start with a non- capitalized letter for the name so if let’s say I want to say say hello then you can do something like this where every word after the first word is going to start with a capitalized letter or if you want to do it you can also go in and say you want to use a underscore instead now my personal prefer is to do a capitalized letter because that’s how I see most people do it but it’s really up to you like there’s different naming conventions you can use here after creating the name we need to actually tell it that this is a function by adding the parentheses and these are the same parentheses you see when we create a builtin function so if we were to go up here and say something like string length then you can see that we can go in and actually get the length of a certain string so if it were to say Daniel and Echo this out inside the browser we would get the number of letters which would P six in this case here inside the browser and this is what we need to use the parentheses for because we can decide how many parameters we want to pass into our particular function down here because this is our function we can do whatever we want with this function here so I can decide how much do I want to pass into my function now you can also just decide not to pass anything inside your function so let’s go ahead and go inside the curly brackets here which is going to be where all the code is going to get run that you want to run inside your function so I’m going to go down here and say say I want to Echo a string and I just want to Echo out hello world so by creating this we now have a function inside our code that we can call upon so we’re not actually running this code yet we only run it once we call upon it so if we were to go inside my browser just to prove my point if I were to refresh you can see there’s nothing inside the browser but if I were to go down here and actually run my code by running the function I can go in and say we have a function called say hello hellow parenthesis semicolon and then I can simply run this function by Saving refreshing the browser and then you can see we get hello world and now we did use Echo inside the function here which is something you can do but it is a very typical thing inside a function to not Echo out a value but instead return a value uh so what I can do is I can go in and say return and when I refresh the browser you can see we don’t actually get anything inside the browser but instead I would have to go down and actually Echo our function so if we were to go in now you can see we get hello world and one of the reasons for this is I can actually go in and create a variable and I’m just going to call it test and I’m going to set it equal to my function and because I’m returning a value and not echoing a value I am now actually going in and assigning hello world to my variable test because this is the data that my function returns so now if I were to go below here and say I want to Echo out variable test then you can see inside my browser we get hello world but now we did talk about passing in parameters because we can do that and we can decide if we want to do it because it’s our function The World Is Ours we can do what we like uh so what I can do is I can go in and say okay let’s go ahead and pass in a piece of data now I’m just going to use a placeholder for this data so I’m going to create a variable and I’m just going to give it some kind of name so this could be name for example which now mean that when you call upon this function down here actually see we get a error message it now demand that you pass in one parameter in order for this function to actually work so if we were to go down here you can see that if I were to go in and say okay I’m just going to pass in a string and this is going to be Daniel we’re now passing in a piece of data that is going to be assigned to this variable placeholder up here so we can now use it inside our function so if I were to go down here and say that I want to concatenate so I’m just going to go ahead and say we want to concatenate our variable here just going to grab variable name which is the placeholder or the reference that we need to use inside this function save this one you can now see that if I were to go inside an echo the function down here you can see we get hello Daniel and you can pass in as many parameters as you want so you can go in here and say you want to add another name so this could be last name uh we can also pass in variable pet so we can you know get the pet that we might have inside our household or something uh so we can pass in many different parameters and you can also see they don’t actually light up they’re kind of like Gray out inside our editor which means we’re not actually using this parameter inside our function and just to mention it here because you don’t actually have to use these variables inside your uh little function down here but you do need to pass in the actual parameters inside when you call upon the function I do have two more things I want to show with this example here so let’s go and go back and just have variable name inside our function so what we can do is we can also assign a placeholder and by placeholder I do mean a default value so let say I go down here and I decide not to pass anything inside my my function down here and it’s now giving me a error message H is there a way for us to run this function without having to pass in a parameter and it just assigns a default value if you decide not to yes there are so what we can do is we can go in and inside the parameter inside our function up here I can go and assign my variable name to Daniel actually let’s go and call it something else so we get something else inside the browser here so let’s say Bess so now if I decide to call upon this function down here without actually passing in a parameter you can now see that it’s going to assign Bessa as a default value for this particular parameter here however if I go down inside my function and say you know what let’s let’s have it be Daniel and I save it refresh you can now see that oh okay so there is a value passed into this function here so we’re not going to use the default value that I assigned inside this function here the second thing that I want to show you is also in terms of something called type declaration which is also something we received in PHP 7 something I do believe type declaration is something we have in most other programming languages but for some reason because PHP is a very Loosely typed language we don’t have it and you don’t have to have it inside PHP but what you can do is you can go inside your parameter up here and say okay I do demand that whenever a user or whenever a programmer call upon this function here it has to be a string that is passed into this function here so what I can do is I can say I want to have this being a string data type so whenever we pass anything in here it has to be a string so right now if I were to save this it is not going to give me any sort of error messages because it is a string but if I were to go down here and say I’m passing in a number instead I’m now going to get a error message actually it’s not going to give us any sort of error message because right now we don’t actually have strict types enabled inside our code so that is something we need to do first uh so if you want to have these type declarations you do need to make sure that the very first thing inside your script here is going to be a strict type declaration so we’re going to go to the top of our file I’m going to open up my PHP tags and I’m just going to go ahead and close it again and the first thing inside my PHP code is going to be a declare strict types equal to one which means it’s going to be true so if we were to save this and then go down you can actually see oh now we do actually get a error message because o this is supposed to be a string but we found a int number and if we were to refresh inside the browser you can see oh okay so type error which means that we don’t insert the correct type inside our function here so type declaration is something that can help you make sure that the right data is being inserted inside the right functions so this is something I do recommend using because this is something that I’m used to from other programming languages but again if you want to you don’t have to do any sort of type declaration inside your Cod you can just delete this liner code here and delete the type decoration like you don’t have to have it it’s very very much possible to do without but I do recommend doing it because it is a habit I have from previous code that I have written in other programming languages out there and there is a reason for why we have it it is to make sure that we have one less error that we might accidentally do inside our code so it’s just kind of like a neat little thing we got added to PHP so with my strict type decoration I can now go in and pass in a string and then you can see oh now it works so and again we can use functions for many different types of things we can also go inside and say this is going to be named calculator because we did create a calculator in our exercise in the last exercise so what I can do is I can go in and say I want to pass in a integer and I want to call this One n one and then I can say I want to pass in a second integer and this is going to be number two and again I’m just going to declare these strict type declarations here because I do think it’s a good idea then I can go inside my code down here and say I want to run a calculation so variable result is going to be equal to variable num one plus variable num two again this is a very simple calculator here it it only knows how to add apparently but I’m just trying to prove a point here so what I can do is I can return a value so I’m going to return variable result so now when I go in I can actually call upon this function here and I do need to pass in the right data so I can go in and say that I want to pass in a number so this going to be two and five so we were to do this refresh then you can see we get seven I do also want to mention here that we do have something called scope inside programming in all programming languages out there and a scope is essentially where you can access certain variables so right now inside this function here this variable called variable result is a local scoped variable which means that we can only access this variable from within this function here one thing that I remember confused me when I started learning programming like many years ago is whenever I went up here outside the function and I would create a variable so let’s say I just create a variable called test and I’m going to set it equal to Daniel now if I were to go inside this function down here can I take variable test go down and just let’s say use it inside this function here so if I were to say I want to return variable test oh we get a error message okay so we can’t do this because it is a undefined variable because it doesn’t exist inside the scope of this function here but what I can do inside this function here is I can actually go and take my variable test and say that I want to grab a global variable within the global scope of my code so I can go in anywhere inside the code here and say I want to grab a global variable or at least declare that this is a global variable that I want to have access to and I can say I want to grab by variable test and because I reference to a global variable in this sort of way we can now use it inside our return down here so I can actually go in refresh and then we can see we get Daniel again I feel like I’m piling information on top of people here but it is just important to know that we have something called scope and we will have a episode I think we should do that in the next episode talk a bit about uh Scopes inside our PHP code because that will be a little bit more relevant to talking about global Scopes and local Scopes and that kind of thing so for now don’t worry too much about Scopes let’s just go ahead and worry about creating functions inside our code like so so you know how to create a function that has a particular piece of code that has a particular purpose in mind uh which you can then use inside your PHP application I do know this is a lot of information I piled on top of people in this video here but it is important to know what a function is because you will be using it constantly inside your code so with that said this is how you create a function if you’re still a bit confused about it I do recommend rewatching the video uh because you do need to know how to create a function okay so with that said in the next video we’re going to talk a bit about Scopes inside PHP and and with that said I about to say it again I hope you enjoyed the video and I will see you guys next [Music] [Music] time today we’re going to learn a little bit about Scopes inside PHP since we talked a bit about userdefined functions in the previous episode and talking about Scopes is going to help you understand how we can access different types of variables and functions and classes and so on so we’re going to talk a bit about Scopes today Scopes Scopes I’m pretty sure I’m saying it too fast Scopes so essentially what a scope is is how or when you can access a certain variable or function or something inside your script this means that right now if I were to have this page that has nothing inside of it and I were to create a variable so I can go in here and I can say I have a variable I’m going to call this one something like test then I need to know exactly when I can access this variable inside my code and we do have four different types of Scopes inside PHP we have something called a global scope which is where my variable right now actually is which means that we can access this variable from anywhere inside of our scripts we do also have something called a local scope which is when we’re talking about inside a function so whenever you define find a variable inside a function you can’t actually use that variable outside the function because it’s locally accessible from within that particular function we do also have something called a class scope and classes is something that we are not really getting into right now classes is kind of something you learn about after you learn the basics of phsp since objectoriented phsp programming is something that you should learn uh but here at the beginning it’s not really something you need to worry too much about but I will give a short example in this video here just to kind of give you an idea about what exactly a class scope is since we’re talking about Scopes so we might as well talk about all of them uh we do also have something called a static scope which is essentially when we have something that is statically declared inside our code uh we need to talk a bit about what exactly that is and how and when you can actually access a statically uh declared variable inside your your code uh so that’s something we’re going to talk about as well so now let’s start by talking about a global scope so as you can see right now we have this script um which we I have introduced The Script already uh but we do have this variable that I just created called test which is said equal to Daniel and if I want to gain access to this variable I can just simply go down and I can say Echo and then Echo out variable test and if I were to do that go inside my browser you can see that we’re actually going to get a spit out inside my browser because this is a global variable and I can just sort of access it from anywhere inside my script so as soon as we declare something outside a function outside a class it is inside the global scope of our script so we can can access it but now we do also have a local scope which we talked about in the previous video where we talked about userdefined function since whenever we create a function inside PHP we do have some code inside the function and we need to know exactly when can we use that code and and how can we use it inside our our script in here so now if I were to paste in a small example that I have here of a function you can see that this particular function here is called my function and we right now inside the function have a variable called local variable and it said equal to hello world now this particular variable I can gain access to within this particular function here so if I were to actually go in and and Echo it out or return it we can also do that because that is probably the better thing to do if we were to go inside and actually return this value go down below and call upon my function here you will see that we actually spit out our return inside our browser so if we were to do this refresh you can see we get hello world but now what if I want to G access to the variable inside the function so if I were to go in and say I want to copy this variable and I want to Echo it out down here because I mean I did declare a variable right but it’s inside the function so we were to do that refresh the browser you can see oh undefined variable which means that there is no variable existing that we can gain access to called local VAR so as soon as we declare a variable inside a function it is locally scoped within that function so we can only access it within my function and the same goes kind of the other way around because if I were to go above this function here and create a new variable so I’m going to say we have a variable I’m going to call this one test again and I’m just going to set it equal to a string So Daniel and if I were to try and access this variable within this function if I were to go in here and say we want to return variable test and actually spit out the function down here then you can see that we’re going to get another error meth because again undefined variable variable test because it is inside the global scope but not within the local scope of this particular function but Daniel didn’t you say that the global scope can be accessed from anywhere inside the script yes as long as it’s not inside a particular scope of for example a function or inside a class then we can gain access to it from within anywhere else inside our script so anywhere else below here if I were to go down here write some code that is not inside a function then I can of course gain access to variable test but as soon as I start creating a function like I did here it is going to only take into account the local scope of this particular function unless I pass in the data into the function and we talked about that in the last video too we can do that by simply copying our variable and say that I have a parameter inside my function here so I can pass in a parameter and then I can go down and for example spit out variable test down here because now I passed it into the function and also we do need to make sure we go down and actually pass it inside the function itself when we actually call upon the function because we have to pass in some data so we were to do this go inside refresh the browser you can now see that we’re passing in data and we can now see it inside the browser but now I did kind of lie to you just now because I did say that you could not gain access to a global variable inside a local function but it is actually possible for us to do so it’s just not really a habit that you should get into doing unless you have a very good reason to uh because the reason we passing data into to the parameter of a function just like we did here is because we want the function to work depending on outside data so if I go in and say well if we have this Global variable then all of a sudden the function becomes kind of like not as reusable in the wrong setting so let’s say we don’t have this Global variable and I say I want to grab it then all of a sudden we start getting some weird funkiness going on so what I can do if I wanted to is I could actually go in and just say we’re not going to pass in this variable which of course is going to give us an nrow message just like before because right now we cannot find variable test but what I can do is I can actually go inside a function and say I want to declare a global variable which right now is called variable test and now because I declared that I want to grab one of the global variables inside the global scope I can now use it inside my function so want to save this go inside you can now see that we get Daniel but we do also have a second way we could do this if you don’t want to declare a global variable first and just directly gain access to it so there’s another shortcut to do this which is also you can just go down and say we want to use one of the super globals we talked about in the previous episode so I can go in and say I want to grab a super Global called globals and I want to pass in variable tests inside my Global’s super Global so in this sort of way we’re grabbing a global scope variable called test using this super Global here called globals there was a lot of tongue twisters in a row so if we were to do something like this go inside the browser you can see we get the same result so it’s basically just another way of doing the same thing as declaring a global variable at the beginning of the function but like I said don’t do this unless you have a very specific reason to do so because passing in parameters is really the way you need to do it in 99% of cases whenever you do variables like this or or functions so now you know how to gain access to a global variable but just know to use it sparingly and for a good reason so now that we talked about a local scope of a function let’s talk about something called athetic scope and athetic scope is something you get whenever you create a static variable inside a function for example you do also have it inside classes but let’s go ahead and take a function as an example here so if we were to go ahead and paste in my little example code here you can see that inside my function we now have a variable that has been declared as a static variable and all I’m doing let’s actually go and just do this to begin with here all I’m doing is I’m going in and saying okay so static variable is equal to zero and then I want to add one to it and then I want to to Echo out the result or in this case here just return the result and then Echo it out down here inside my function so if I were to do this what you should get is one because when I run this function with taking zero and adding one to it and then returning it so we would to go inside my brows so you can see we get one but now what happens if I do this a second time if I were to go down here and say I want to Echo this out again but what is the second Echo going to be is it going to be one or is it going to be two because remember we’re adding one inside function so if we to go inside my browser refresh it you can see we get another one and the reason for this is that a function is meant to be a blocker code that has code inside of it that you can just gain access to over and over again inside your code so you can reuse the same code again and again and again and because of this they should not be influenced by each other so if I use my function in one place then it shouldn’t change the same function when I use it in another location otherwise it kind of defeats the purpose of my function so whenever I use the same function again and again we should get the same result every single time however let’s say I go inside my function here and I declare a static variable so if I use the static keyword instead this particular variable is going to be shared by all the functions inside my code or inside my script anytime I use this particular function here so if I were to go in here and say that my static variable is equal to zero and I add one to it it means that now for all all the other functions in the future this particular variable is not going to reset itself it is going to stay as one so when I use the function the next time the next time the number is going to get spit out it is going to become two and again if I were to use this function a third time it is going to be three because it keeps adding one to it and because this is a static variable it is going to be shared among all these different functions down here now the last scope that we need to talk about is something called a class scope and this may be a little bit premature because we haven’t actually talked about classes and properties and methods yet and objects and and all these things but it is something that exists when it comes to scope so I’m just going to mention it so you know a little bit about what I’m talking about here so inside PHP we have something called a class which is basically like saying we have a template that has a bunch of variables and functions inside of it I’m doing this because they’re not actually called variables and functions uh but so you know exactly what I’m talking about they kind of work the same way as variables and functions but within a class so as you can see here I have a class called my class and inside the class I have a variable and I also have a function which is actually called a property and a method and these variables and functions are only accessible from within this particular class here now I’m just going to stop myself here because I started talking about how to create Optics and different things off this class and this is not supposed to be a class episode It’s supposed to be about Scopes um so all you need to take from this is that when we have a class like this all the different properties and methods within this class let’s actually go and delete this static keyword here because that is actually useless right now um if I were to do this all these properties and methods can only be accessed directly inside this class here so if I were to go outside this class I can’t access these unless I make them static and the reason you will make them static is for like entire different reasons like there is actually a reason you might want to do that um but just for like regular usage you don’t usually do that so this is what we call a class scope so now we talked about global Scopes we talked about local Scopes and we talked about static Scopes and we talked about class Scopes uh don’t worry we will get to talk more about classes at some point in the future but for now let’s just go ahead and stick to procedural PHP and then once we have learned all the basics then we’ll get into like classes and off Tech oriented PHP and stuff like that so for for now that is basically what scope is when it comes to PHP so hope you enjoyed this lesson and I’ll see you guys next [Music] time today I’m going to teach you about something called a constant inside PHP and a constant is basically a way for us to create data that cannot be changed at any point inside our code which which is very useful for a lot of reasons for example if you have some data that is very important to a lot of your code and it has to stay the same then declaring it as a constant makes sure that if you were to accidentally change it at some point you get an error message instead of all your code that starts breaking and and showing the wrong thing because that one piece of data has now been changed and everything else is now wrong so creating constants is something that can help us create data that should always always stay the same if I were to create a variable for example here so if I were to go and say we have a variable called name and setad it equal to a string called Daniel you can now see that if I were to Echo this out and say I want to Echo out variable name this is going to give us Daniel because that’s what we wrote but what I can also do is I can take my variable name go down below and I can change it to something like Bassa and if I do something like this it is just simply going to change the variable in to B now which is okay because this is just a variable however if I were to do the same thing using a constant this is actually going to throw me an error message so if we were to go up here we can declare a constant by saying we want to Define parentheses semicolon go inside the parentheses and give it a name so to begin with here we can call it something like Pi because Pi should never change because it is always going to be 3.14 so let’s say I’m doing a bunch of calcul ations and I need to use Pi in order to do this and I wrote it as 3.14 if Pi were to change then all my calculations are going to go wrong so I want to make sure that we always get this particular value even if I were to accidentally change it at some point in the future which I should not be able to do but hey mistakes happen but we just want to do as much as we can to avoid those kind of mistakes so what I can do here is I can go down and say I want to Echo out not variable name but just Pi if would to saved this go inside the browser you can see we get 3.14 and you may have noticed something here because I did actually create a variable name using all caps so right now it is pi using capitalized letters this is not something you have to do I could also go in here and say Pi with a non- capitalized lettering so if we were to do that and actually spit it out inside the browser you can see we still get 3.14 however it is a convention inside any sort of programming language that when you create a constant that you use capitalized lettering because it shows other programmers that this is a constant so it’s just kind of a visual indicator for other programs to know that this is a constant so now if we were to spit this out inside the browser but I were to go down and say I want to change Pi into 4.14 so let’s say I want to do this but hey whoops I made an accident I accidentally changed something that I shouldn’t change if I were to do this you can now see that we get a error message because we’re not supposed to redefine a variable called Pi elsewhere inside our code and this is just a very useful way to make sure that if I were to accidentally change something that we get a error message instead of all the code starting you know to go wrong and of course this can be any sort of data type so it doesn’t just have to be a float number like it is right here I could also go in and say this is going to be name and then I can create a string and say this is Daniel and if we were to actually spit that out you can see we get Daniel inside the browser we can of course also create all the other types of data we can create a true or false statement so I could say isore admin you know is the person and administrator then I can go in and say this is a true and of course I can go in and actually spit it out so we can see it it is also important to note here that a constant is inside the global scope whenever you define it which means that if I were to create a function down here so if I say have a function just going to go and call it something like test just to give it some kind of name if I were to go inside the function I can actually Echo this particular Conant directly inside the browser because we can just gain access to it so even though we in the last episode talked about variables not being able to get passed into functions unless we actually declared that they were a global variable we should access or pass them in through the parameters or something like that uh we can actually do that using constants so if we we to actually go in here and say I want to Echo up Pi then I can actually do that so if we to go below here and actually say I want to run my function here called test and then you can see that we get 3.14 inside the browser of course we’re going to get 13 now because we also echoed out is atmin over here so we delete that you can now see we get 3.14 the last thing I want to mention here is whenever you define a constant is to make sure to always do it at the top of your script it’s just kind of a habit that we have that whenever we want to create a con they should be all listed at the top of the code so even though it’s not necessary I could take the constants and actually move them below all my code if I wanted to do that it is kind of a habit or a good practice for programmers to make sure that it’s all at the top of the code so we can easily find them and this is basically what a constant is so having talked about that we now start reaching a point where we need to start talking about how to actually do things with databases when it comes to PHP because PHP is is kind of like one side of the coin and the other side of the coin is handling data from within a database so we need to start talking about how to you know actually go inside a database and create data and how can we then grab the data using PHP and show it inside a website so having talked about constants I hope you enjoyed this lesson and I’ll see you guys in the next video [Music] today I’m going to teach you about something called a loop inside PHP which is actually going to be our last episode before we start talking about databases together with PHP so that is going to be very exciting cuz it’s kind of like the point where we can start building some very cool things inside phsp so with that said let’s talk about the different types of Loops that we have inside PSP now if you have learned something like JavaScript beforehand this is going to be very familiar to you because a loop is pretty much the same thing in most programming languages so there’s there’s like slight differences maybe but they are going to be pretty much the same thing so when it comes to a loop we use them inside our code to spin out a blocker code multiple times by just writing one block of code so we can spit it out maybe like 10 times or you know maybe we pull some data out from a database and we want to make sure that we spit all the data out inside our website rather than just one piece of data so we can keep spitting out data depending on how many iterations would tell it to actually run inside our code basically just something that repeats again and again and again and again until we tell it to stop that’s basically what a loop is so when it comes to a loop we have the first one which is called a for Loop and a for Loop is a very basic way for us to spit something out depending on numbers so what I can do is I can actually go inside my for Loop here and inside the parameters we need to include three different parameters the first one is going to be a starting point so I’m going to create a variable we can call this one whatever we want but it is kind of like a tradition to call it I for iteration because one iteration is one Loop and then we can do like three iterations which is three Loops so you know we have something called a iteration to begin with here we’re just going to go and set I equal to zero and then I’m going to end this off with a semicolon and add in the second parameter or the second state inside this uh parameter here and that is going to be when do we want this Loop to stop running so at some point this has to stop otherwise we create something very bad which is something called a infinite Loop which is a loop that is going to run endlessly inside your website and eventually crash your browser so we don’t want that to happen that is a very bad thing um so we want to make sure the loop has a stopping point so what I can do is I can goad and say that I want variable I to stop once it hits a certain point and this can be you know when variable I is equal to a certain number which is for example 10 we can also do less than an equal or greater than an equal let me just go ahead and rephrase that we’re running this loop as long as this statement is true that’s what we’re doing okay so we have to go in and say as long as uh variable I is lesser than or equal to 10 then we want this uh four Loop to keep looping that’s that’s what we’re saying here so what I can do is I can go inside and add a third parameter which is going to be how much do we want variable I to increase or decrease every single Loop when we Loop this out and what I can do here is I can go ahead and use a increment or a decrement which is something we talked about in our operations episode uh basically we can go in and say we have a variable for example variable I and I want to add one to it by writing plus plus so the first time we Loop this variable I is going to be equal to zero but once we get done with this blocker code it is going to change it to one and then the next time it’s going to be two and then it’s going to be three and four until we get to a point where this statement here is no longer true and then it’s just going to stop running so what we can do is we can go inside here and we can just go ahead and Echo out something so we can say Echo um this is iteration number and then we can go and add a concatination and say this is iteration uh variable I and let’s also go Ahad and add a break to this because because we do want to have multiple lines just so we can see it properly inside the browser here so what I’ll do is I’ll just add a HTML break and with this I can go inside my browser and as you can see we get this is iteration number zero and number one number two and so forth until we get to iteration number 10 now in this case here we are spitting out 11 numbers because we’re also spitting out the first one which is you know when the number is zero and there’s a couple of ways you can do this if you want this for example to Loop out 10 times then we could go ahead and say this should be uh maybe equal to you know 9 or we can also go ahead and say that we should start at one uh if I do this for example if I were to go inside the browser you can see that we start at one and then we count to 10 uh we can also go ahead and set this back to zero and say it’s just going to be lesser than 10 and this case it’s going to go and stop at nine so there’s many different ways you can split this out 10 times uh this is basically just to show you that you can go inside your parameters if I can find my mouse there we go you can go inside your parameter here and you can change these numbers however many ways you want to so this is a basic way to create a for Loop inside your code and again you can write whatever code you want to in between these uh curly brackets here so you can you know spit out any sort of code that you want and there’s many different uses for a for Loop for example if you have a string that has a certain number of characters inside of it and then you want to spit out uh a loop for each character so you can count how many characters inside a string and then you can do that based on that basically anything you can think of that has something to do with numbers is something you can use in this case here you could also go in and actually replace this you could say instead of being lesser than 10 uh if I were to have another variable up here I can just call this one test I can set this one equal to five and I can actually go ahead and replace variable test with my number 10 and in this case this would also work so in this case we’re spinning out five times so you can replace these in here with variables if you wanted to you know if that’s the thing that you want to do it’s just kind of to show you that there’s kind of like a a free Ro uh to do whatever you want with this kind of loop here but now we do also have a second type of loop which is called a while loop so what I can do is I can just comment this out just so I can demonstrate what a while loop is and the way this works is instead of using numbers I can actually go inside and create any sort of condition that you might want to use from for example Le a if statement so you know when we use a if statement you can also go and compare things you know do something specific uh we can also create a Boolean so if I create a variable here I just call it Boolean I’m going to set this one equal to true what I can do is I can go inside and say as long as this variable here is equal to true then I want to Loop something out and now of course in this example here we are creating what is called a infinite Loop just like we did previously so it is a very good idea that this should at some point make our variable Boolean into fals otherwise this is not going to be very good for our website cuz it’s going to crash everything uh so what you could do is you go in here and say let’s just go and make variable Boolean equal to false in this sort of sense here uh so this basically means that the first time it’s actually going to just Loop out one time and then it’s going to stop looping again because the first loop it’s going to change our variable into false uh which means that this is not going to Echo out anything else so in this case we’re just going to Echo out our Boolean just so we have something to actually spit out inside the website so we can test that this is working uh so if I were to do this go inside my website you can see we get true or one in this case which is the the number version of being true zero would have been false in this case here so we are spinning something out uh what we can also do is we can actually create something very similar to what we had up here so I can take my variable test and I can go down and say I want to say we have a variable called test and as long as variable test is lesser than 10 then I want to spit out this Loop here so what I can do is I can go inside and I can actually say that variable test is going to add one every single Loop and then I can simply Echo out something so we can actually see something going on inside the browser here which could for example be variable test just so we can follow what exactly it’s do doing and then I can go ahead and refresh the browser and as you can see we get numbers so it is looping through five times because we had our variable test starting at 5 and then we just add one each time until we get to lesser than 10 uh so it is doing something here so anything that you might want to think of that you could for example use inside an if statement when it comes to checking for these type of conditions is something you can use inside a while loop whereas for example our full loop up here is more about when it comes to like numbers so two different ways to Loop things out you can just kind of like use the one that you might find appropriate for a certain situation to spit out a bunch of data a certain number of times uh but what we can also do is I can also go ahead and do something called a do while loop because right now if I were to go ahead and say that for example variable test is equal to 10 which means that immediately the first time this is actually going to be false because this is not going to run a single time so so if we were to actually save this go inside and refresh it you can see we get nothing inside the browser hm and that is because we started out with a false statement so it’s not even going to Loop out one thing inside our code but what we can do if I can find my mouse here for some reason is really difficult in this background color here uh what I can do is I can go inside and create something called a do while loop and the way that works is I can actually replace the while statement and the parenthesis with a do keyword word and then afterwards down here I can actually include my while statement so I can go ahead and say semicolon and what this is going to do is that it’s going to Loop this code in the same sort of sense as before but it will always Loop this out at least one time no matter if this is going to be true or false the first time uh so no matter what happens this is always going to spit out something one time so in this example here even though variable test is going to actually be a false statement inside the while loop it is still going to Echo out variable test one time so if we to do this go back inside refresh you can see we get 10 now let’s take a second example here because we do have the last type of loop that we have inside PHP so right now we talked about full loop while loop and dual while loop but we do also have something called a for each Loop and in order to demonstrate this one I will create a array which right now has three pieces of data so we have apple banana and orange and what I want to do here is I want to Loop one time per data inside the array so let’s say I want to spit out all this data inside my browser what I could do if I wanted to and do it manually is I could go inside and say well you know what I’m going to go and Echo out my variable fruits and I want to grab the first index so I’m just going to go and grab index number zero and then I’m going to go and copy this down you know two more times because we have two other pieces of data so I can also grab number one and number two and if we were to do this and go inside my browser you can see we get all three but you may start to see the disadvantage here because now we actually first of all we need to know how many pieces of data is inside this array CU we need to know in order to manually type them out here um but also we have to literally manually type them out which is not really a good thing uh so what we can do instead is we can actually make our code automatically just know how many pieces of data inside this array and then spit them out and I just want to point out here that a lot of people will look at these Loops here and think that oh okay so the you know the while loop might be the one I have to use the most cuz that one is pretty cool but this for each Loop here that’s about arrays and we haven’t done much in Array so far so we’re not going to use this one that much right however when it comes to learning about databases and actually grabbing data from a database and outputting it inside our website you do need to know how to create a for each because that’s the one we use in order to do this um so a for each Loop is quite important so what I can do here is I can actually create one so we’re going to use it for each keyword parentheses and curly brackets and then inside the parentheses we need to first of all add in the array that I want to actually grab the data from and what I want to do is I want to use another keyword called as and then I want to give it a placeholder that I can refer to inside the actual brackets down there or inside the curly brackets uh that is going to to use in order to grab the data from inside the array so in this case here because I want to just grab one piece of fruit I could actually say that the placeholder is going to be fruit you know a singular fruit so what I can do here is I can save this and then I can go inside deep brackets down here the curly brackets I keep saying brackets for some reason um but I can go inside the curly brackets and I can Echo something out so I could say this is a which is not going to make a lot of sense in this case because apple is supposed to be an Apple I do know a little bit of English grammar but you know we’re just doing a small example here so it’s okay but what I can do is I can say this is a then add in the fruit variable because that is going to be the placeholder and then I want to just close it off here actually let’s go ahead and move everything down to the next line just so we have a little bit of you know neatness going on in here so we’re going to add a break and just like so it is going to go through each of these data and spit it out inside the browser so if we would to save this go back in you can now see we get this is a Apple this is a banana and this is a orange but now what about a associative array because this is a indexed array and we did talk about arrays in a previous episode basically we have something called a indexed array which is where we go in and if you want to spit something out when it comes to an array is you refer to the index of the array so in this case if we want to grab Apple then we refer to index number zero if you want to grab banana we refer to index number one uh but what about a associative array so what I have here is another example of a associative array where basically we go in and we say that the key is going to be apple and the value is going to be the color of the fruit so we can keep doing that banana is going to be yellow uh and orange is going to be orange because you know it’s the same name so what I could do here is I could actually just go inside my browser now refresh everything but if I were to do that it is actually going to be echoing out the values uh because when we use the S keyword inside of for each Loop down here it is actually going to refer to the values inside this array so right now the values are actually going to be the colors that we added in here so if I want to go inside my browser refresh you can see we get the colors in here but what if I want to also get the key because that is also something we can do in order to spit this out inside the website so the way we can do this I can just simply go ahe and copy paste this little arrow up here because we do it the exact same way and go after my fruit and say I want to point to another placeholder which in this case it could actually be the color so if we were to go back down inside my echo I can say this is a fruit that has a color of and then I can go ahead and add in another concatenation so just going to go and add in our color uh value here so I’m just going to paste it in and if I were to go back inside the browser you can now see that we get this is a Apple that has a color of red so we’re also getting the key in this case here and this is a small introduction to how to you know Loop something out inside the browser depending on how much data you might have inside a array or you want to Loop something based on how many numbers there are or based on a condition like for example with an if statement uh so we have four different types of Loops that we can use depending on the situation that we might want to find one of them useful so in this case here we have something to work with so with that in the next video we’re going to start talking about databases which is going to be very exciting I know it doesn’t sound exciting cuz database like it kind of sounds a bit dry um but when we start using databases with a website using phsp that is the moment where we really start to see something happening with PHP inside our website so that is going to be very fun to do uh so with that said I hope you enjoyed this lesson and I’ll see you guys next time [Music] So today we’re going to do something very exciting because we’re going to start talking about databases and how to handle data inside a website because when you start doing that that’s the moment where you really start to make a website more Dynamic rather than making a static website which is something that basically means that you have a website that doesn’t really change depending on which user is watching the website so when you have a dynamic website all of a sudden you can start changing content or if you were to hand off a website to a client they can start changing content themselves if you want them to be able to do that that is actually something that I don’t think a lot of people realize that when you start learning how to make websites and you want to become a web developer and you think to yourself okay so I’m going to start making websites for people but when you hand over a website and they have to make a change to let’s say a title or paragraph or maybe they want a image updated or something then all of a sudden they have to contact you because you can’t give them a website and then teach them eight to Mons so they can change things themselves um so that doesn’t really make a lot of sense right so you have to be able to make a website that is dynamic where can allow people to change content themselves without having to know HTML or css in order to do so for example if you want to create a blog inside a website and you want the client to be able to you know upload a new blog post by thems without having to contact you every single time that is going to be an example of something we can start doing when it comes to learning phsp together with a database so with that said let’s go and talk about how to set up a database and what exactly it is databases sound so dry when you say it out loud like that uh it’s not it’s quite fun once you get into it and when you really start seeing content change it’s gets a lot of fun okay so the first thing you want to do is you want to make sure that when you go inside your xamp that we installed in the second episode I do believe that you do have both the Apache and the MySQL server running because the first server here which is the Pache server is going to be the web server where we have PHP running the second one is going to be the actual database server so this one has to be running in order for us to access our database with the xamp that we installed uh because you do have a database installed as well other than just PHP and a server so this is something that you do have already uh we don’t have to do anything special in order to set up a database we just have to open it basically just a small quick tip for you because I don’t think I mentioned this in the first episode where we installed xamp uh you can actually go inside the config menu here and you can actually make it so that the software Auto starts these servers when you open up the program so you can just tick this off right here and then you can click save now if it gives you a error message it is because you need to run this uh software here as administrator so the basic way to do that would be to go inside your exam installation go down find your examp uh Dash control right click properties and then B basically just go in here inside the compatibility and set this one to run this program as administrator if you do that then it’s going to allow you to to set these up as auto start uh without giving an error message so with that done let’s go and talk a bit about something called a relational database management system rdbms for short you don’t have to memorize that it’s just so you know okay so we have many different types of database systems out there which is what we call a rdbms um and the one we’re using is the one called MySQL which is also the most popularly used one when it comes to databases with websites especially if you’re using PHP but there are many different types of database systems out there and that you know some people watching these tutorials may be using something else but if you installed exam you will be using MySQL for this tutorial here most of the time if you do actually have an online server from a hosting company you will also be using MySQL just to mention it so it is the most commonly used one which is also why we’re going to be using that one for these lessons here and just to debunk something here because I know I will get some comments asking about this because it is something I’ve seen on previous videos MySQL servers are not the same thing as MySQL PHP functions okay so before people start typing in comments that MySQL is outdated and it’s unsafe to use then it’s not the same thing as PHP my SQL functions okay it’s two completely separate things so we don’t need to worry about using a mySQL database okay that is something that is very commonly used and it’s not unsafe uh in any sort of way um so what I’ll do is I’ll go Ahad and open up my uh browser and inside my browser I can go up and type Local Host just like we do when we actually want to enter a website but instead of saying forward slash the name of the website in this case I’m going to write PHP my admin and if I type that and click enter you’ll see that we enter our database system so PHP my admin is going to be the dashboard that you’re going to use in order to manage your database and you can actually see that we have many different types of databases on the side here uh you’re not going to worry about these ones that you have over here you may not have PHP tutorial because I actually created that myself at some point but don’t worry about these databases that we have over here you just need to know that any database you create will be over here in the the side so what you can see is we do actually have quite a few TS up here uh you don’t need to start freaking out about oh no there’s so many things going on in here um because we’re not going to be using all these tabs up here do also keep in mind that you do actually see some information about your web server so you can actually see what PHP version you’re using so right now I’m actually using 8.2.0 um so this is actually some information about your server the first thing we’re going to be doing is we’re going to create a database for our tutorials here so what I’ll do is I’ll go up to databases in the top here and then you can see we can type in the name of a database so we can just come up with any sort of name of course a name that makes sense as you can see with these databases down here there is kind of like a naming convention so don’t use weird symbols or something like that uh so what we’ll do is we’ll just go ahead and say my first database just so we have something right then you can just go and click create and then you can see we have a database added to the side over here now as a default it is actually going to be selected once you create it the first time but you can also see we can swap between them and actually see some of the uh other databases that we have here so I can actually click back and forward uh but for now let’s just go and select the one we just created called my first database now inside of here you can see this is quite empty like there’s nothing going on in here cuz we just created a completely empty and fresh database and what you can do in here is a couple of things first of all you can import databas base data from somewhere else if you have a existing database that you want to import in here or we can just go ahead and create a database from scratch we will be doing the lad because we will be creating things ourselves and there is a couple of ways we can go around doing that uh I do want to point out to you that right now it says no tables found in database the first thing you need to know about a database is that we have data inside a database so for example let’s say I have a login system inside my website and in order to have that we need to have users signing up inside our website and with that logic we do also need to be able to save that user information somewhere for example the username the password they used maybe an email address maybe what date they signed up inside the website we can save all kinds of information about our user and that is what we use a database for because whenever the website has to remember something inside our website you use a database to save that information about whatever we want to save inside our website and in order to make that a little bit easier we create something called tables because instead of just taking all our data and putting them inside our database there has to be some sort of structure going on so we want to maybe create a table that is called users where we have all the user information we might also have a table called comments so we have all the different comments the user made inside our website inside that table so basically a table is a place where we gather similar information about something inside our website and we do have two ways we can create that either we can go down here and do this in the confusing way at least I think this is the confusing way this is also the way that I see most people do this when they start out making a database uh but you can go down here where it says create new table and you can actually type in a name so in this case I can just say uh users because we use that as an example and then I’m going and say how many columns do I want uh which basically means how many different pieces of information about this user do I want to save so in this case I could say five which is an ID username password the date they signed up an email address you know so we have some some information about them and if I were to click create here you can see we get this very confusing uh table that we can start filling out uh so basically these are going to be the names so like I said we can have an ID we can have a username we can also have a password you know we can start filling in the names for all these different columns what is what they’re called inside our database um but the problem here is that there’s a lot of information that you don’t really need right now to know about um so this is only going to confuse people even more uh so what we’ll do instead is I want to go back so we can go back inside where it says structure and then you can see oh you have unsaved changes are you sure you want to leave um yeah let’s let’s not worry about this right now what we’re going to do instead is we’re going to go and create all our data using SQL code so we’re going to to do everything manually which is also going to be very useful because once you start talking about how to uh change our database and and talk together with the database using phsp from our website directly uh you will need to know SQL code in order to do that so there’s no better place to practice SQL than directly inside a database so hey let’s do that instead so what I’m going to do is I’m going to go up here in the top where you can see we have something called SQL do make sure that your database is selected otherwise this is not going to be SQL code that you write for that particular database because I sometimes see people who have another database selected or no database selected so make sure that your new database is selected and then click SQL now SQL code is actually quite simple to write a lot of people find a little bit intimidating to start with but it’s it’s actually quite simple and and of all the SQL that you may look up and and try to learn uh there is typical SQL you know like very few lines of code that we use over and over and over and over again so it’s not like you have to learn a lot of code just like if you had to learn PHP for example it’s it’s quite simple and there’s not a lot of code you have to learn for now but this is the tab that we’re going to be using in the next video when we actually start learning how to create a table together so we’re going to take this video by video we’re just going to do one step at a time uh chronologically as we’re making this database uh really really what we have to do here is just create a table and that’s pretty much it for now but although we could take this table we create in the next video and use it directly inside our website I do want to use this particular SQL uh editor here to just kind of show you how to do various things using SQL uh because you’re going to be using the exact same SQL inside your phsp code so the best place to practice it is doing it inside this database here I do also want to point out that even though we are going to have a couple lessons here where we’re not really going to write any PHP code and this is a PHP course this is the other side of the coin when it comes to learning PHP so if you don’t know this stuff here then you’re missing out on half of what PHP can actually do in order to make a website really cool so learning about databases and learning PHP with it is something that is necessary when you’re learning PHP for the first time so this is going to be a couple of lessons of just SQL programming essentially uh but it’s going to be very worthwhile to to learn so with that said I hope you enjoyed this lesson and I’ll see you guys in the next [Music] video so now that we have a database inside PHP my admin we need to talk about how to set up a table inside our database or multiple tables since we can have many tables inside our database and in order to do that we’re going to program this into our database using SQL code which is something that stands for structured query language which means that we’re quarrying the database using this code here in order to manipulate the database and you know maybe create tables or insert data or select data or delete data or you know there’s many things we can do using SQL and SQL is something that is not really too difficult it takes a little bit of memorizing to do but a lot of the code that you write using SQL it’s going to be pretty much the same so it’s not really like learning phsp where you have to memorize a lot of different code it’s it’s more about learning the same queries so to speak in order to manipulate the database so the first thing we need to do here is make sure that our database that we created in the last episode is selected over here in the sign so you need to make sure you click it otherwise we’re going to be writing SQL code for something else outside you know on the side here we don’t want to do that cuz we want to make sure we select our database so with our database selected you can go up here in the SQL tap and in here we’re going to go ahead and start writing some SQL code so we can actually write some you know some instructions to our database for it to do something like for example creating a table so I hope this is big enough because it is quite tiny I mean I guess I can zoom in a little bit more so you can see a little bit extra here just just to make sure that you can actually see what is going on cuz it is quite a a tiny console that we can write into here so now when it comes to creating a table there’s a couple of different concepts that we need to talk about before we get started here because we do have uh data types that we can insert inside a database we do also have something called signed and unsigned we do also have some different commands like autoincrement which means to we automatically assign numbers to a certain column uh we do also have columns that we need to talk about you know we have columns and rows uh which is like columns is the uh the vertical and then rows is the horizontal you know we have some different concepts we need to talk about but what is important to know is that this video is kind of going to be a mega video it is going to be a little bit longer than other videos because there is like I said quite a few things we need to talk about but you need to see this video as something you can return to so if you need to know a little bit of information about for example what a row is or what a column is or what signed and unsigned means what does a primary key mean what is a foreign key you know then you can come back to this video and then it will be time stamps below so you can kind of like fast forward so you can you know find a specific part you need to refresh your mind with in order to know exactly what that was but just know that I don’t expect you to memorize everything on the first go in this video here we will get to do more code in the future when we actually get into PHP we’ll also write SQL code so you know memorizing these things is not something I expect of you on the first goal so the first thing I want to talk about here is data types because when it comes to inserting data just like with PHP we also have you know integers we have characters you know like actual writing like text and that kind of thing we have dates we have uh decimal points that kind of things so we need to talk a bit about the different types of data we can insert into different columns because when we create a table we need to define a row which is all the data we have for one entry and then we have the columns which is each individual piece of data there you might have a one database entry so essentially we would have for example a person so we would have you know first name last name age you know hair color that would be like the different columns and then will we grab one row from the database that is basically grabbing the entire person with all these different attributes that that person has so we can actually pull the row out and display the data inside a website for example so we have you know columns and then we have rows and each column inside a table needs to be defined with a data type in order to tell our database what kind of data do we expect to be put inside this column here so for example if we were to go in here and say that I want to Define a integer data type then we do have an INT data type which is basically when we have four bits of data we can insert as a number inside this column here which is not a decimal point so you know just like a regular number like this and one thing to note here when it comes to these different types of data that you can insert inside a database is that they all have certain amounts of bits you can store inside this specific column here so for example when it comes to a in we can actually store a number that goes from I actually just went ahead and wrote it out here because it’s going to take a little while but when it comes to a integer data type we can store up to four bits inside this specific column here which means that we can store up until minus this number here until positive this number here so this is going to be four bits I’m just going to go and leave this for now because we do also have something called called signed and unsigned we need to talk about but this is basically the integer range that you can store inside a integer column if you want to choose a integer data type so let’s say for example I want to have a much larger number inside my um my column here because this might not be enough for my specific number let’s say I want to store a uh money amount inside my database and maybe that money exceeds this amount which in that case you’re a very lucky person if you have that much money um but let’s go and say I want to store even more money inside this database column what I could do is I could also use something called a big int and it is important to note here that we do have something called tiny int int big int um so we have many different types of integer data types they can store up to you know different types of bits inside of it but for now we’re just going to talk about the more common data types that they might want to use inside a database cuz I it is going to be quite a long lesson if we’re going to list them all out so let’s just go ahead and stick to the the ones that you might want to be using at some point then you can by yourself look up some of the other types if you want to at some point in the future but for now we have something called Big end and this can store even greater numbers so in this case here I’m not going to write it out but this is going to be up until eight bits of data or eight bytes it’s called the previous one up here is also four bytes by the way not bits um so essentially what you can store here is a much larger number which again is also going to range from a negative number to a positive number so it could for example write something like this inside of it and it would actually be able to store it because as you can tell this number is much bigger than this number up here which is the maximum for a uh int data type so you know we can store a lot bigger number when it comes to uh the big int down here and you might be asking well Daniel so if you’re saying that this one can store a lot bigger number than this one why don’t we just use this one every single time and essentially it all counts down to Performance and that kind of thing because we want to make sure that we don’t uh take up more space than we need to if we don’t need to get close to this number here but this is plenty for storing you know a certain type of data inside our database then performance will be better if you just stick to the data type that makes sense for that particular purpose so don’t just go around using the the biggest data type that you can find so in that case you can always store the biggest number um so so choose the one that makes sense for the the circumstance you might want to use it in and now we do also need to talk about something else before we move on to characters and decimals and date times and that kind of thing uh we can also go ahead and put parentheses Behind These data types and actually Define a parameter for these data types here in this case here when it comes to integers it is a device with that we’re defining in here so if I were to write something like 11 um this does not mean that I’m allowed 11 characters like 11 numbers inside this integer this means that the device with allowed for this data typ type is 11 numbers and this is not something that is directly going to be affecting your website this is something that is going to affect certain types of applications that is used to for example show data for example our uh MySQL software here U has a console inside of it where we can actually show the data from inside these different columns so if I were to set this one to five and I were to store let’s say this number right here then I wouldn’t be showing this number right here inside my database I would actually be showing this number right here although this number is actually what is stored inside this column but it’s not shown inside this database because we defined a Max limit for how many uh how much the device width is going to be when it comes to showing this data inside this database here and like I said this is not something that really affects your website when you define a number in here because you can still show the full number inside a website uh so a typical thing that we do when it comes to just making websites is we just Define 11 in here as a default which by the way is from what I remember also the default when you just write this it is going to be the same thing as writing 11 inside the parentheses so this is not really that important if you’re just a web developer and you just want to store numbers that you want to show inside a website but just out of habit we’re going to go and write parenthesis 11 to make sure that it is defined because some database types may be some Legacy databases or applications that needs to show this data do need to have this defined so it is better to have it than not to have it okay so with that said let’s go and talk about a float number so we can also Define a float which is of course also going to be when you have a decimal point so you can for example say you have minus something you know this number right here dot something and you can of course have a Max and a minimum that you can store inside when it comes to bytes uh in this case it is also going to be four bytes which means that we can store I’m not going to type it out here cuz it is you know a long number like these ones up here but essentially you have a minimum and a maximum which is equal to four bytes that you can store inside this particular column here uh the same thing goes when we have something called a double so we have something called a double which can store much larger decimal points so just like we have up here a inch and we have a big int so we have one for storing you know a normal amount of numbers and one for storing a large amount of numbers the same thing goes for float and double this is a small amount of numbers and then this one down here can have a lot greater amount of numbers inside of it when it comes to like decimal points and that kind of thing so uh we do have different data types again just like with numbers we have the same thing when it comes to decimal points um and then we do also have something called vaa now Vara is when we have to do with characters uh so let’s say I go in here we can also create the parentheses which is actually something you should do cuz the default is going to be one uh which is this right here and that is not really useful for anything cuz that means we can store one character inside this column here um so it is you know you should create parentheses outside vaa in order to define something here so in this case here we could for example say 10 so what this would basically mean is that I can store 10 characters as a string inside this data type so if I were to write Daniel uh this would be able to be stored in there but if I were to write something like Danny cing which is going to be more than 10 characters is going to cut off the last parts of this string here because we only allow 10 characters inside this column here so depending on how many characters you want to allow inside this column here you need to change this number in order to allow for that amount of characters now when it comes to something like let’s say a username you could say something like 30 cuz you know 30 characters for a username might be plenty so you don’t want to be able to store more than that so we do have different numbers we can provide in here depending on the purpose of what we want to create inside our database if you have a password uh then we can also go down and say maybe something like um 255 because we want to be allowing many characters for a password but I have rarely seen anyone use more than 255 characters when it comes to using a password U so of course you know you can Define different things depending on the purpose that you want to allow the person to insert inside this particular column here and just like before we do also have a certain number of bytes you can store inside a v chart data type so in this case here it would be in the range of something like and again this really depends on the database because some databases only allow for 255 which is why I use that one as a maximum um but you can also in some database do up to 65,535 bytes so you know it really depends on the databased type you’re using in our case I do believe we can store many bytes inside this uh inside our database here but 255 is kind of like the typical number that you define inside a vacha data type because then you know that it can be stored in many different types of databases because this is the maximum for some databases uh so 255 is also plenty in my opinion for storing U you know characters because you know we have other data types of storing much greater number of characters for example we do also have a data type called text and just like before when we talked about int big int float and double if you want to store many characters inside a column you can just use something called text which is going to just be defined as text and then you can store for example a blog post or a big comment for post inside your website that has a lot of characters and text inside of it so uh using text for for example comments and blog post and that kind of thing is kind of what we need to use this data type for whereas vacha might be something used for usernames and P password you know something that’s not a huge paragraph that needs to be written inside your website so again choosing the proper data type for a certain type of data or usage inside your website that is appropriate to the amount of characters that you might be using is something you should be doing but now the last type of data type that I want to talk about here is something called date and date time so we have something called Date here which is basically when uh you want to create a date for a certain moment in time so for example today it is the year 2023 and it’s May month which means 05 and then it’s the 14th of this month year uh so we do have different types of uh formatting when it comes to our date and date time and that kind of thing so the formatting is something we need to be aware of when we upload a date to a database because if we don’t format it correctly it is not going to get stored inside a database so when you write PHP code you want to make sure you format it in the same way as the databas is so with we do also have something called date time so we have date time and that is basically the same thing so we can actually copy paste this but we do also have the time so if I were to go in here and say that right now it is 11:30 in the middle of the day so it is the 11th hour and then we have the 30th minute and then we have the let’s just say the zero second of the day uh so this would be 11:30 and then of course we go into not a.m. and p.m. but we’re going into for example uh 17 if it’s 5:00 in the afternoon so we go after this time format here so these are the different data types that I want to talk about but I do want to talk about something called signed and unsigned when it comes to using numbers up here because let’s say we have this integer example here let’s just go and delete everything else now we did talk about there being a certain number of bytes available inside these different data types that we have in here and when it comes to a integer data dat type we have four bytes available to us and that basically means that we can range from this negative number here to this positive number here however if I were to go in and say I want to Define my integer as signed this right here means that we can actually store a negative number inside our database column as well so this would be uh this range that we have right here but I can also go in and Define this one as unsigned which means that we don’t want to store negative number numbers inside this particular number column and that opens up a little bit of options for us because right now we only have four bytes available which means that this is the maximum positive number we can use but when we cut out the negative numbers we can store from zero until a much greater positive number because we have more bytes available and now we cut out all the negative numbers which means that we can store up till actually just went ahead and Googled it here CU that was a little bit easier but you can store the twice as much number when it comes to the positive number so inside a column you can define something called signed and unsigned when it comes to numbers that goes down into the negative range because we want to maybe not allow negative numbers to allow more spacing for positive numbers so that is something that is just important to mention here so now that we talked about all of this let’s actually go and talk about how to actually create a table because now we got a lot of dry knowledge about data types and signed and unsigned and you know defining parameters and you know bytes and that kind of thing so let’s talk about how to actually create a database table so if we were to go in here we can define a create table keywords it’s called which basically means that we’re going to create a table named something so in this case if we can name something called users if that’s how we want to create a table called and this of course would be information about a user inside your website so for example username and password email you know the date that you signed up inside the website that kind of thing there is something to note here which is if you were to write this you may notice that we get a popup which says that this right here is a existing keyword inside our MySQL keywords here so we don’t want to be using a existing keyword so this right here is a no no okay so we want to make sure that we write something that doesn’t pop up as an existing keyword otherwise you can end up in a little bit of you know errors and that kind of thing so make sure you don’t do that so one of the things that I do when it comes to naming a table is to say well inside a table we have many entries of data right so we have many users inside this table which means that it makes sense to call it users in plural because we have many uses inside this table here so I like to name mine users and it is allowed to use a underscore for something specific so if you want to write something you can use an underscore but in this case I think uses is good enough parentheses and semic one and then I’ll open up the parentheses and then we can start creating all the different columns inside this table here in between the parentheses so now we need to think about what kind of information do I want to remember about a user inside my website when it comes to a you know database and information kind of purpose the first thing I want to do here which is something you need to do in pretty much all the different tables you create is to make sure you have something called an ID so I’m just going to go and name this one ID and then I’m going to define a int data type and like we talked about we don’t really need to have something behind inter but for the sake of making sure the Legacy databases and that kind of thing can can use this data for something let’s go ahead and make sure we Define 11 in here just to to make sure we have it defined even though it won’t really matter to us in most cases as a web developer we we should still Define it in here uh so what I’ll do is I’ll go after and say that I want this data type to be not null which means that we don’t want it to be nothing uh that’s basically what null means it means nothing it is different than not having any sort of data it just basically means nothing which is a concept we have inside programming um but basically this means that we we need to have data inside this particular column here and what I’m also going to do here is I’m also going to define something called Auto unor increment and I know I’m not really explaining all of this right now so let me go ah and explain it right after this line of code here so basically whenever we have a table we want to make sure that we can find data inside this table very easily which means that having a ID for all the different rows we have inside the table is going to make it a lot easier for us to grab certain data so let’s say I have a user that has an ID as 65 for example if I were to look inside my database table for the user that has an ID at 65 which by the way he’s the only user who can have that number then it’s a lot easier for me to find that user inside the database than trying to search for his username or something so whenever we’re trying to search for something inside this table here having an ID for all the different rows inside the table is going to make a lot easier for us so basically what we’re doing here is we’re saying that we want to have an ID for all these different users that is going to be a unique identifier that is what id stands for and I want this to be a number data type and I want to make sure that there is a number for all the users in here cuz this cannot be empty and now in order to not manually having to write a ID for every user whenever we create a user inside our website I added something called autoincrement which means that our database is just going to handle this ID column by itself and automatically add a number to this user whenever we create a new user inside this table here so user number one is of course going to be user number zero and then the next user is going to have an ID is one and then number two and then three and then four and then it’s going to keep counting up every single time you add a new user to the database so this is automatically going to increment a number hence the autoincrement keyword and this by the way is unsigned which means that it’s going to use the positive numbers and not negative numbers so this is automatically also going to declare this as being a unsigned and this is something that you have to remember this particular line of SQL code because we use this pretty much in every single table we create inside our database because all our entries needs to have an ID so having this particular line of code as the first thing is going to be very very important now we do have something called a primary key that we need to Define inside this table here which is going to be this particular number but we’re going to wait with that until after we declared all the columns because I want to talk about it afterwards uh so for the people who do know a little bit of SQL here just we’ll get to it okay um so the next one here could for example be a username so let’s say we want to declare a username for this user so we can say username and I want this to be a v chart data type because this is of course course going to be a set of characters because we need to have like you know Crossing or something you know as a username uh so what I’m going to Define here is just 30 because I want to allow 30 characters inside this username more than that I think it’s going to be you know overdoing it a little bit so if a user tries to declare something bigger than this then it’s just going to get cut off at the end there because we don’t want to have more than 30 characters you could also say that maybe like 20 characters is plenty uh but let’s just go and go with 30 for now uh we do also want to declare this one as not null cuz I do want to make sure there is some data inside this column here and then I want to go down to next line and we can actually copy paste what we have here cuz the next one is going to be very similar and this one is going to be the password now there’s a reason why I don’t write password and you may see it there because there is a built-in keyword called password so instead I’m going to declare a PWD which is kind of a short hand for password and doing that I do want to allow more than 30 characters and when it comes to passwords we don’t want to really limit our user when it comes to a password we want to allow them to create as long as a password as they want for security reasons cu the longer it is the better it is but let’s not go overboard here let’s go ahead and say we want to allow 255 characters which we talked about is kind of like the maximum number for some databases so let’s go and make sure we Define uh 255 in here which is plenty for password I think so we don’t need to have more than that uh after this one we can go and go down to the bottom and maybe say something like email and let’s go and Define a vaa as well so we’re just going to copy paste here and I want to allow something like let’s say 100 characters cuz I think you know an email of more than 100 characters doesn’t really exist out there so let’s just go and Define 100 characters and for the last column here let’s go and Define a date time for when they us to sign up inside our website so we know when they signed up inside the website so what I could do is I could create a column called something like created underscore at just so we know you know we have some kind of name for this column here you can call whatever you want in my case I’m just going to call it created at and I’m going to call this one a date time format or data type so to speak and inside of here what we can do is first of all Define a not no which means that it should not be empty and we can also go and Define something called a default which means that if I decide not to write something and send it to my database table here to create a new user then if left empty it is going to by default assign something by itself to this particular column here so what I could say is I could use the keyword called default and actually assign a default value so in this case I could say you know just to give an example here that we have a year a month a day uh we do also have a hour we have a minute and a second and this would be a default date time uh that I could set for this particular database here but of course this doesn’t really make sense like this is you know the year zero at the zero hour so basically the creation of the universe or something so this doesn’t really make sense but what we do have is another keyword inside the database here called current and then you can see we get date and time so one here is just the the date format and the other one is the date time format so we can say current time which means that it’s going to automatically create the time based on the server time so this basically means that we don’t really have to define a date time using PHP if we don’t want to we can do it because this is just a default which means that if we don’t submit something then it’s just going to assign the current time based on the database server but you can also submit a date time using PHP if you want to so you have kind of like an option now but now we do also have something called a primary key and the way you could Define that is by for example going up inside the one column that has to be the primary key and just write primary key inside this this particular column here and now this is defined as a primary key so this would be correct but it is also just kind of a habit to go down here at the bottom and say that you want to have a primary key so we can see we have primary key and we want to define a column so we can say parentheses and that is going to be the ID column which is the one that we have up here and doing this here is also a way to do it so that is just a second way of doing it instead of writing it directly inside the actual column up here um and do note that I’m not writing a at the end cuz the last line of code inside this particular SQL statement here inside the parentheses has to be without a comma so all the other ones you need to include a comma but for the last one you leave it out otherwise you’re going to get an error message now a primary key is basically just a way for us to Define which column inside this table is going to be the one that we use that has to be unique so it can’t be duplicated elsewhere inside any other rows inside this database so for example we can’t have one user that has an idea 65 and then another user that also has an idea 65 because then we start getting error messages so primary key is just basically a way for us to create a unique ID for all the different users in here so we can very fast just grab a user and you know find them very fast inside our database so now with this created we actually do have a database table we can just run inside our database and actually create it uh let’s just go ahead and out of habit just copy everything because because in case something goes wrong and it’s always a good idea to have this you can also go and store this information inside a empty text file or something so you have you know all this data somewhere so in case something goes wrong and oops okay so this particular one up here could not have been named username so I have to call it user uncore name or something instead then instead of having to rewrite everything you have everything stored somewhere so that is a recommendation that I have so you have it saved essentially um so what I can do is I can scroll down and then I can say we want to go which means that we’re going to run this inside our database and then you can see we now have our first database table which is called users if I were to click the database you can see okay so we have our users table right here and we can click it or we can click it over here in the side and then you can see we have an ID username password email and created ad inside this column here or inside the table it’s called um so right now you can see we don’t actually have any sort of data otherwise we could see it below here you just listed out we’re going to talk about how to insert data and update and all that stuff in the next episode but for now let’s go and create another table uh because we do also need to talk about something called a foreign key so again we want to make sure the database is selected and because I made everything so tiny by zooming in it’s now a burger menu for some reason if I would to do this you know to zoom out you can see that I have it up here uh but basically we’re just going to go and click the SQL tab once more I’ll zoom in again so you can see it and we’re going to go and create a second table so in this case I’m going to create a table I’m going to call this one comments because we’re going to create comments that the user can make inside a website underneath something so a picture or a video or something like that so we’re just going to go and create a comment table parentheses and semicolon and what I’ll do is of course I need to Define an ID cuz that’s the first thing so we’re going to say we have an ID this is going to be a int data type and just like before we’re just going to set 11 as a default one and we’re going to say this one is not null we’re going to say this is auto increments so Auto uncore increment so it automatically assigns a new number comma next line and then I’m going and say okay so what do we need to know about this comment here we need to know U for example the username of the person who made this comment so we could say username and we can say this is a v chat data type we’re going to define a username length which in this case it could be 30 because that’s what we defined in the previous table so we’re just going to say 30 here as well not null and then I go down to next line and we do also need to have some text in here of course cuz you need to write a comment so there has to be text in here right so instead of using vaa for this one because we want to allow for the person to write many characters inside this comment here we could also use a text data type so let’s go and say we want to have the comment uh message or just comment text let’s go and do that cuz that’s a lot shorter so comment text and I can say this is a text data type I want to set this one to not no and I want to go down to next line let’s also go and create a timestamp for this particular um when this was created so we’re going to create a datetime data type and we’re going to call it something like creatore at cuz again we can just reuse the same name as the previous one um and then we’ll also go and Define a not null and we can also go and create a default and then we can again use the same thing so we can say current time stamp or current uh time it’s called so it will just automatically create a time stamp for this particular comment once it’s actually created and then at the end here we’re going to create our primary key so we’re going to say we have a primary key which is going to be our ID so we’re going to Define ID inside this particular one here now we want to also Define a foreign key in this example here cuz we can create something called a relationship between one database table and another database table so right now we have a user who made this comment so we’re trying to think logically here which means that we can actually tie a comment to a particular user and you might be thinking well Daniel we defined a username isn’t that what you’re saying so if we say that a user called cing from the users table uh now is also named Crossing inside this comment table here aren’t those connected then um to a human that might be connected but for a datab base that is not connected uh there’s no relationship going on between the two tables so what I can do is I can actually say that okay so this comment here let’s say we actually upload a comment to this table here has to be connected to a user that has a certain user ID again the primary key inside the users table has to be connected to that particular comment and there’s a couple of reasons why we can do this let’s for example say I go inside my website and I sign up as a user and now I have a a user account then I go inside a picture and I write a comment underneath the picture now what is going to happen when I delete my user account is it going to delete all the comments inside the website that I made with that account or is it just going to throw me an error message because hey you made comments inside the website so you’re not allowed to delete your account or should we just go ahead and say that okay so we can delete the user account but we now need to Define all the comments the user made as a deleted user because the user no longer exists inside the website so what needs to happen once we have this relationship and you decide to lead a user from inside the website so what I want to do here is I want to first of all Define a column that is going to reference another column inside my users table and when it comes to naming this column here we can give it any kind of name that we want to but in my my case I think it makes sense to say that this is from the users table underscore and it’s going to be the ID for the users table so just a little bit of logic here for me so I know exactly what this is and what I can do is I can define a data type and not null and all this kind of thing um but it’s very important that when it comes to the data type that we assigned the same data type that is inside my users table for this particular column that I want to reference to so in this this case here this is the ID for inside my users table which means that we have the same type of data as we have up here which is int 11 so we need to make sure that we Define the same data type for this particular column here then I can also go and say not null and what I can do now is I can go down below my primary key and I can define a foreign key so we can say foreign key the first thing we need to Define here is which of my columns inside this particular table is going to be my foreign keys in this case here I want to say this is my users ID this is the one that I want to reference to a key from another table so what I need to do is write references because we reference another table called users and we point to a column inside this users table called ID because that is the ID from inside the users table that I’m trying to reference to inside this column here and now with this we could just go ahead and submit it and that would be okay everything would work perfectly fine um however like I talked about previously if I were to go inside my website and create an account and write a comment underneath a video or a picture or something and I then delete my user account what is going to happen now now as a default you’re going to get an error message because as a default we have something called on delete and then we can write something like no action and what this basically means just to kind of explain this for you is if I were to go inside and delete a user from inside my users table that has a certain ID that is connected to a comment that is made inside this table here so right now there’s a relationship going on between a comment and a user from inside the users table if I were to delete the user so on delete then I want no action to be made so essentially it’s going to throw an error message and not delete the user because we don’t want to delete the user because there’s a relationship going on here so if we delete the user then it’s going to break our database table relationship and this is basically the same thing as doing this right here because this is actually the default state of what is going to happen if you try to delete a user that has made a comment so that is not really going to make a lot of sense in most websites like logically in the real world this is not going to make a lot of sense because you know I should be able to go inside a website and delete my user account even if I made a comment somewhere like that should be a valid thing to do uh so we do also have something called Cascade so on thead I want to Cascade which basically means that if there’s any comments inside this table here that has a relationship to a user from inside the users table that is now being deleted then also go ahead and delete all the comments made by that particular user so that is what Cascade is going to do but we do also have one called set null which is basically going to instead of you know deleting all the entries or throwing an error message this one is just going to go ahead and set this column in here as null whenever we delete a user that this one has a relationship to which basically means that there’s not going to be any sort of ID that we’re pointing to inside the users table it’s just going to delete it from inside this column here but now if I were to try and run this code inside my editor here so let’s go and make sure we save it just to make sure if we were to scroll down and actually run this you’ll notice that we get a error message message oh no there is a error which is called error number 10005 which is actually when it comes to the foreign key being written wrong inside this table here now if you know a lot about logic inside a table you may see what is wrong here because right now I’m telling it if I were to delete a user from inside the users table then go ahead and set the comment column which is called users ID to know right but what did we also Define inside this column here we said it cannot be null so right now we’re saying okay so if we delete a user set this column to null but hey oh we’re not allowed to do that so if I were to do this down here I do also need to make sure that we don’t have not null inside this column here otherwise we cannot do it so we need to make sure we do this in order to submit it so now that I have this again we can copy everything go down to the bottom make sure you have no comma at the end here by the way and go ahead and submit this then you can see everything works out just fine so now if you were to go inside my database you can see oh we have two tables now we have a comments and a users table and these actually have a relationship with each other we have a foreign key that points to another table so now we actually have something going on here and with this we now know a little bit about creating tables inside a database or you know a lot about creating tables inside the database of course you can go much deeper into it uh but for now I think as a beginner sort of lesson that is already quite long this is going to be plenty for teaching you how to create tables inside a database so for now this is what you need to know about creating tables and in next video we’ll talk about how to write some SQL code to just insert and select data it it’s much more simple than this episode by the way um this episode was quite long and complex compared to the next episode because we just need to write like one liner code in order to insert data into a database you know into one of these tables here so that is going going to be much simpler okay so with that said I hope you enjoyed this lesson and I’ll see you guys in the next [Music] video so now that we learned how to create a table in the last episode I thought it was a good idea to talk a bit about how to actually insert data inside our database table since right now we have these two tables that we created but we don’t really have any s of data inside of them we’re not going to talk about selecting data in this episode here since we also need to talk about something called joints in order to talk properly about selecting data and that would mean that this would actually be a little bit longer episode so for now let’s just go and talk about inserting deleting and updating data since it’s fairly simple to do so we don’t really need to have a long episode to explain that with that said as you can see right now I selected my database and inside our database we have comments and a users t table since we created that in the last episode now what we’re going to do is we’re going to talk a bit about how to insert data to begin with so I’m going to go inside my SQL tab up here make sure you do have your database selected over here on the side and from in here we’re going to go ahead and write some SQL that is going to insert some data inside our users table just so we have something to to work with you know to teach you how to insert data so what I’m going to do is I’m going to write something uh called a insert into statement which basically means that we’re telling it to insert some data inside one of our tables and in this case we want to insert into users which is our users table and then we want to tell it what exactly do we want to insert inside this table here so in this case here we do have a couple of table rows that we want to do something to and when it comes to inserting a row of data we do have different columns that we need to provide some uh some data for uh so if I were to actually right click on users and open that in a new tab so we can actually see our users table you can see that right now we have an ID a user name a password an email and created at so those are the five columns that we need to insert data for now in the last episode we did talk about ID being automatic so we didn’t have to touch that one it’s just going to automatically create an ID and we did also create a default value for our created ad so we don’t actually need to create data for this one either so right now the only one we actually have to do something for is username password and email so what I can do is I can go back inside my insert statement and inside the parentheses I want to tell it which columns do I want to insert data into so in this case that we want to say that we want to insert inside our uh username then we do also have a password and we had a email so right now we have these three different columns I want to insert data into and you have to remember the the order here because the order is going to matter and afterwards we want to say that we want to include some values to insert inside these columns so we’re going to say values which are going to be inside a parentheses as well semicolon and inside of here I want to provide some strings since in this case we do want to insert strings not numbers and if it had been a number I would just write a number in here but because we’re dealing with a string or characters I want to make sure we have these sing quotes you can also use double quotes but it is just kind of a habit inside when it comes to SQL statements that we use single quotes So for that I’m going to go and insert a username so in this case I could call myself cing just to do that I could also provide a password so in this case yeah I could say something like Danny 123 just to you know have something in here uh I do also want to point out when it comes to actually inserting a password you know in more real life examples we do need to Hash the password first so it’s more secure uh because if a hacker were to gain access to our database it shouldn’t be able to tell what the password is so you know doing a little bit of hashing for the password is something you need to do uh but just because we’re practicing here we’re just going to go ahead and insert a password that we can actually see inside the database because we want to see if this works so afterwards here I’m going to go and provide the last one which is going to be an email so I’m just going to say uh John do John do at so John do at gmail . just to you know give it something this is just a placeholder email and just again to make sure we have this saved I’m just going to copy everything here and I’m just going to go and open up my text editor and just paste it in so now we have it stored somewhere so I can actually go ahead and see it in here you know so we we can just copy paste it again if we need it for another time um so what I can do is I can go back in here scroll down and I’m just going to go and submit this one so I’m going to click go and when I do this you can see one row inserted inside our database table so if we want to click this users table or just go into the tab that we have open refresh it you can now see that we have a piece of data so right now we have aids1 we have clossing Danny 123 John Doe and then we have a date for the the time right now that I created this user here so everything is working perfectly so now let’s go ahead and go in and add a second user just for an example here so I’m going to go and go back make sure my database is selected now because I’m zoomed in it’s going to give me this burger menu up here so don’t worry too much about that just go in Click SQL again and I’m going to go and paste them what we had and I’m just going to change the values here so we can say this is going to be Bess and this is going to be just Bess 123 and I’m also going to go and change my email to Bess gmail.com and I’m just going to scroll down and click go so now for I want to go in you can now see that we have two different users us so now we have an idas one and an idas 2 and remember the ID is going to be a unique identifier so in this case here you know each user has a unique number for each of them that is going to be relevant for a little bit later in this video here um so for now let’s just go ahead and save this as it is and talk a bit about how to go in and update one of these tables here so if I were to go back in and make sure we have SQL clicked I can go in we can now create a update statement so if I were to say want to update one of these rows of data um just to go back in here just to show you uh so this is a row of data as you can see horizontally we have all this data here and then we have the columns which is the ID the username the password email and creat AD so you can see how we have rows and columns right just to point it out uh so going back in I want to change one of the rows from inside my table so what I can do is I can write update which is another command that we have here and I need to tell it which table do I want to update in this case here so right now I want to update the users table and I need to tell it okay so we have the user table selected but what do I want to change and from which specific row and this is where the ID comes in because what I can do is I can say I want to set a new value so in this case here I can say let’s say I want to change the username of Bess for example what I can do is I can go in and say I want to change the username and I want to set it to a new value so I’m going to set it equal to a new string but like I said it is more common to use single quote so let’s go Ahad and stick to what I’m saying um so what I can do is instead of saying Bessa 12 three is I can say Bessa uh 456 just to change it to something else now we have you know not one two three but we have 456 if you want to change the second piece of data you can also do that so you can also say comma and then add another piece of data from inside that particular row you want to change so in this case here I can say that I want to change maybe the I just realized this is actually the uh the password I just wrote in here so let’s go and copy this uh this information here and say I want to change the PWD into Bassa 456 because that makes more sense so let’s change the the username into something else let’s call this one Bassa is cool just to have something right because he is kind of cool he’s sitting right over there um so what we can do now is we picked two columns that I want to change and you could pick all of them if you wanted so you can just keep adding commas and add some other data um but in this case I’m just going to go and say I want to change these two different columns and I do also need to tell it where from inside this table I want to select a row because right now we don’t actually know exactly what we’re picking like right now we’re just saying oh set all the usernames and all the passwords to this value but we need to pick a specific user that we want to graph from the the mix of of users so what I can do is I can say where the ID is something specific so I can say where ID is going to be equal to two because if I were to go back inside our users table you can see the Bessa has an ID as to so in this case here I can just go ah and pick out you know the person with the ID of a specific ID is going to have this data changed about it um if you don’t know the ID of the user you can of course also go in and say that okay so right now it’s the person with the username that is equal to uh what was it Bessa um or if I want to say okay so we need to have the user be a user with a username of Bessa but also so and the password should be equal to something else so Bess one two 3 for example here inside strings of course so we’ll make sure we have single quotes there we go um so in this case here we only change the information if Bess has this username and this password here or we can also go in and literally I just made an unintended pun there uh we can also say or instead of and and say that if the username is equal to cing so in this example here I’m changing the username and the password of two different users inside my database so you can also use you know a username search two times in a row row and just say okay so if the user has a username A Bess or crossing then change them inside the database or ID you can also write ID and say ID is going to be equal to uh one so we can actually say this is a integer so we say one or the ID is equal to two so this would also be the first two users inside the the table so you know like we can mix a match things here and and mess around with it as much as you want um but let’s just go ahead and go back to just is saying where ID is equal to one in this case here so if we were to actually run this and go down say okay or go it’s called Uh then you can see if for where to go back inside my users table notice how bassim uh is going to have his username changed and his password is going to change once I update okay so I accidentally set the user ID as one okay so we changed the wrong one here so instead of changing you know the Bas one down here we actually updated my cing one uh because wrote we wanted to change it where the ID is one and not two uh small mistake on my end but hey it it kind of proves my point so now you can see the old version down here and the new version up here so you can see that it is actually changed um so what we can do now is talk a bit about how to delete data from inside the database and I want to give you kind of a small little example here because I get a question quite often when it comes to deleting data from a database and I want to kind of prove a point here so what I’ll do is I’ll go in here and I want to say we want to delete from our users database so delete from users and I want to tell it which row do I want to delete from inside this users table which is going to be done in the same sense as we just did with the update because we have to pick the specific row maybe based on an ID or username or something you know can mix and Max this with and and or just like we did before but let’s just go and say we want to delete the one that has an IDE D equal to 1 which is the one we also just updated so we had Bessa is cool and Bessa 4556 right so if we were to do this and go back down to the bottom and run this you can see that now we get a small popup so it actually says are you sure you want to really execute this quy and I’m just going to say yes here and then we say one row is affected so if we go back inside and refresh you’ll notice that now we only have our second user inside the database table and this is where I’m going to prove a point because what is going to happen when I insert another user inside my table here because if were to go back inside my little uh code that I saved in here conveniently and went back inside and ran a new insert statement so if we were to go inside my SQL tab here and run a insert statement and say we want to insert Crossing Denny 123 you know blah blah blah and run this what user ID is you’re going to get if you guessed one you are incorrect because if we go back in here and refresh you can see oh okay so Bessa has an IDE is two and then Crossing has an ID as three oh no but that messes with my brain cuz where is user with the ID as one inside this table here I do sometimes get comments underneath my video asking about so what do we do in this situation here cuz you know one is missing so so what are we going to do uh can you just go inside and maybe change this so we write one and then we write two down here uh so you actually do this and you actually update it because you can do it like this as well if you wanted to um so if I do it like this ah now everything is matching right if we can actually get this out of the way so now user number one is B and user number two is crossing so ah now it’s not going to be two and three anymore you know so it’s not like weird or something but it’s very important to point out here that doing what I just did changing the IDS manually by just going in and changing them is a big no no okay you cannot do that let’s say for example that one of my users made a comment inside the comments table which now means that one of those users are assigned to a comment and then I manually afterwards go in and change the IDS of all my users then all of a sudden all the comments and which user made those comments are going to get all messed up inside the database so don’t change the ID manually just go ahead and leave the numbers broken as it is because it’s supposed to be be broken if you start deleting users so if it says in this case here I can actually just show you another thing here uh if I were to try and go in and change the ID to two it is going to give me an error message because this is the primary key which means that there cannot be the same ID for all the different users so in this case because I tried to change this one to two but we also do have another user that has an ID is two uh it it doesn’t allow me to do this uh so going back here I would have to go in and Tin this one to three because now I can tin this one to two because now there’s no duplicates okay so this right here is the right thing okay don’t go in and change these numbers to one and two because oh it makes sense to your brain uh to do this so I get this question quite a lot so I just wanted to make sure that this was answered properly in a lesson I do know I kind of went on a rant here because I do get this question quite often but I just wanted to make sure that people didn’t start changing the IDs manually inside a database because like I said it starts Breaking All the relationships to other tables and that kind of thing so uh with that said we have now learned how to insert update and delete data from inside our database tables so in the next video we’re going to talk a bit about how to select data from inside a database table since that is very important to know as so you can actually select and show data inside your websites and we will talk about selecting data but also how to join data together together if you have data from two different tables uh let’s actually go and do one last thing in preparation for that so let’s go ahead and copy the insert code that we have here go back inside our database make sure it’s selected and go inside our SQL console what I want to do is I want to insert inside comments and I want to insert a comment from one of the users inside my table here because that is going to be relevant when it comes to talking about joints and that kind of thing in the next episode so so what I will do is I’ll open up my comments inside a new tab so we can actually see what is going on and inside the comments table we do want to remember that we have a username a common text and also a users’s ID because these other ones the ID and the created app is going to be automatically created for us so we don’t need to worry about this one uh so we have these three columns here so username I’m just going to copy it go back in here and say I want to you know paste it in it was already in there so we didn’t need to paste anything I do also want to grab the common text paste that in as the second one and then I want to paste in the users’s ID now it is important to keep in mind that because the users uncore ID is a foreign key it has to match one of the users from inside my users table otherwise we’re going to get an error message because there’s no user connected to this comment here and we did set it up in the previous videos to make sure that we do need to have a user connected to it okay so it is important that we have a user that is existing inside the database so with the values here I’m just going to go and say we have a username so the username for this user could for example be cing and in this case here if we were to go back inside my database inside the users table uh cing right now has an ideas three so I’m just going to copy that then we’re going to go back in and make sure that the users ID which is the last one down here does have the same ID as that user inside the users table and I do also want to go in and write a message which is going to be my commment so I can say this is a comment on a website just so we have something in here and with this if I were to just copy this to make sure that we have it saved if I go down and click go you can now see that we’re going to have a comment inside my comments table so if we want to go in here you can see we have an ID we have a you know cing this is a comment on a website created that and then we do also have our users ID from the user inside our users table so now everything is working like intended so with this comment here we’re now ready for the next video where we’re going to select data from inside our database so with that said I hope you enjoyed and I’ll see you guys in the next [Music] video so in the last video I showed you how to insert update and delete data from inside a table and in this video we’re going to talk about how to select data since we we need to know how to do that in order to select data and show it inside a website so with that said let’s just go ahead and dive straight into it here uh in the last video we did create a couple of data inside our tables here so inside my comments table you can see that I have uh one comment from one user and inside my users table I do have two different users that I could do something with inside my database so we have Bessa and crossing and what I want to do here is I want to go inside my database and go back inside my SQL tab now again it looks a bit weird on my screen here cuz I’m zoomed in but if it were to zoom out you can see it’s right there um and what I want to do here is I want to create a select statement so we can actually select some data from inside one of the tables and actually show and we can do that directly inside our console here so if were to go in I can write a select statement so I could say I want to select and then I want to say what do I want to select you know what kind of columns do I want to select here so I could for example say username I could also write a comma and say I want to show the email and then I need to tell from which table inside our database they want to do this from so from inside our users table and then I want to write where so we can actually select these specific row that I want to select data from since otherwise it would just select all the users from inside the database um so right now what I want to do here is just kind of tell it which row they want to select from so I could for example say where the ID is equal to three in this case here so if I were to do this we can actually output data um so if you want to run this you can go down click go and then you can see we get some data in here so one total we got from this Cory here so if we want to scroll down you can see okay so we got a person called cing with an email called John Doe because he is the one that has a ID set to three inside my users table so we selected some data from inside this table here using the select statement and we got the information that we asked for which was the username and the email in this case here and we can do the same thing when it comes to a comment so what I can also do is I can go back up here make sure that we go inside our database I want to select the SQL console and that I can just paste in our select statements and say that I want to select the username the commentor text from not the users table but the comment table and we do want to make sure we change this last ID over here because if I were to go inside my comments table if you followed the last video uh you’ll know that we right now have an ID column but we do also have a users uncore ID and the ID column is the ID for this specific comment but the users uncore ID is the ID for the user who made this comment here so it’s very important that we we pick the right one here uh so users uncore ID is what we need to select over here so users uncore ID and I’m just going to go ahead and copy everything to make sure it’s saved go back down and then I’ll go and quy this inside my database base and then you can see we get another user or at least a comment from a user here called cing and we get this is a comment on a website now we do also have something else we can do which is something that you usually see people do when it comes to selecting data from a database if we were to go back inside my SQL console I can do the same thing but instead of writing which specific columns I want to pick something from I can go ahead and write a star symbol or a multiplication symbol um and that will actually go select everything from inside this row here so not just specific columns but everything okay so what I can do is I can just go and save this go back down run this query and then you can see we get everything so we get the ID the username the comment text the Creator ad and the users uncore ID of this particular comment here so it’s not really that difficult to select data from inside one of these tables you just need to run a select statement and just fill in the blanks essentially but now let’s talk about something something called a join which is when you select data from two different tables at the same time or actually you can do as many tables as you want but let’s just go and focus on two here uh so let’s say I want to select my user called clossing but I also want to select his comment from inside the comment table so now we’re actually grabbing two different uh rows of data from two different tables what we can do is I can go and make sure I select my database and open up the SQL console and I’m just going to go and paste in what we had here from the previous example so select everything from comments where users uncore ID is equal to three so now when it comes to creating a join we have a couple of different types that we can use we have something called a inner join we have something called a left join a right join and in some databases we do also have something called a full join but in my SQL databases like the one we’re using right here I do believe we do not have a full join so instead what you could do is create something called a left join and a right join Union where you basically combine those other two types of join to get the same effect as a full join um again I’m just kind of like rambling here and you probably don’t understand what I’m saying so let’s go and do a example here uh so what I want to do here is I want to go and create a inner join and in order to do that I’m going to say I want to select everything from users and I’m not going to go and add where ID is equal to three because that will actually be created a little bit later on inside this join uh so instead I want to go ah and say I want to select everything from users and do a inner join together with the other table that we have called comments and I want to make sure we do it on a certain column so right now we have two different columns from inside each table and those columns are going to have the same data inside of them to kind of connect them together so right now we have inside our users table we have an ID so our user has an ID is three and inside our comment table we have a comment where the users uncore ID is equal to three so what I want to do here is I want to combine these two tables where we have this same column data right cuz we made a foreign key so we can do that using the foreign key cuz that is perfect for that kind of thing so what I’ll do is I’ll go back inside my quy and say I want to select from my users table so users Dot and then you can see we get some options here so I’m going to select the ID where it’s equal to our comments Dot and then you can see we get users uncore ID and then basically spit out the data based on these two tables here so again before we quy this just to explain it again CU I know joints can be a little bit confusing to people uh we’re basically combining two tables together and we want to select everything from both of these tables and we start by selecting one table so in this case here the users table and then I want to injoin it with my comments table and I want to combine a data from these two tables using one column from each table that has the same data inside of it so if I were to C this just to make sure if we get any sort of Errors we still have it here if we were to scroll down and run this you can actually see that we’re going to get one result and that is going to be my user so in this case here with an ids3 uh cusing password email created at and then we also get the commment over here so everything is combined in one row of data and just to show another example here because you can also go back in here if I were to select my database and run another query and P paste everything back in you don’t have to select everything from both of these tables here you could also just go in and say that you want to select from the users table so users do uh username and you might also want to select something from the comments table so we can say comment dot comment text in this example here and maybe also another piece of data from the comments table so we can say comments. uh created at so if you want to select specific data you can also do that so we would actually run this scroll down you can see we get the same kind of thing but now we just get the The Columns that we asked for from both of these tables here and I do want to point out you that if I were to have another comment inside my comment table made by the other user named Bessa in that case it would actually get two rows of data down here so right now we we have this row of data here but we would actually get a second row below it with Bessa instead because all we’re asking is to grab data from two tables that has matching ID and user ID and spit it out and any other sort of data that does not have any matches is not going to get shown when we actually Cory this which is why we only get one uh piece of data down here but let’s go and talk about left and right join because that is going to change things a little bit so if we would going select my database go back inside my quy and just paste everything in and instead I’m going to do a left join which means that basically this users table is the primary table we have in focus and I want to join it together with any sort of comments that are made by my users so even if a user does not have a comment we’re still going to show all the users from inside our users table but they’re just not going to have the comments shown next to it so by doing a left join you can kind of see here that we have the users on the left here and we have comments on the right side and that is basically what we’re talking about here when we’re doing a left join so you know this is the left side this is the right side uh we can also do a right join which means that we’re talking about the comments on the right side and not the users on the left side so this is the the primary one that we’re focusing on over here but just to kind of demonstrate this if I were to do a left join I am now selecting all the users no matter if they have a comment assigned to them so in this case here if we were to go ahead and do this and run it inside below here you can see if I were to click go we would now get two pieces of data because I’m grabbing all the users but you’ll notice that the user that does not have a comment does not have any sort of data it just has null instead because we have no data so in this case you can kind of see that we still grab everything from our users table but not everything from our comments table only the comments that have a matching user is going to get grabbed and we can also do the same thing the other way so if were to go back inside my database and do a right join instead I can just paste everything in here and say I want to do a right join then I’m going to show all the comments but only the users that actually made a comment where these actually match when it comes to the column so in this case we just going to get one row of data which is going to be the exact same thing as when we did our inner join that is just coincidence by the way so would actually run this you can see we get one row of data and that is going to be our cing because he actually has a commment so we’re showing all the comments here but not all the users which in this case it would just be one row of data so if I were to have more than one comment inside my comments table uh we would have all those comments listed below here but the user information would just say null instead uh so the opposite of doing a left joint essentially in our case here with this example I have uh to show you and that is basically how to select data from inside our database and I just want to point out here that I know we talked about joints in this episode here in a lot of cases when it comes to just grabbing data from a database you’re just going to be doing what we did at the beginning of this video here you’re not going to be using joint for something specific that is more for other specific purposes inside your website we actually do want to combine data from different tables but in most cases you just going to be selecting data using what we did at the beginning so uh don’t worry too much about these joints here they are good to know uh but we’re not going to be using them you know when we start selecting data from inside our website in the upcoming examples when we actually uh start talking about how to use PHP to select data from inside a website database so with that said this is how you select data I hope you enjoyed and I’ll see you guys in the next video [Music] so in the last couple episodes we talked about how to go inside a database and create a table as well as creating data inside those tables and updating them and deleting them you know just kind of like manipulating data inside a database but we haven’t actually talked about how to do that from inside a website so that’s what’re going to do today as you can see I have a very basic website in front of me there’s not really anything special here just basically have a index of PHP which doesn’t really have anything there’s nothing inside the body tag um so what I want to do in here is I want to go ahead and actually create a connection to my database so I can actually go in and run PHP code that can actually query this database so in order to do that we need to have a connection going first so what I’m going to do is I’m going to go inside my project file and I’m going to create a new folder and I’m going to call this one includes now includes B basically means that this is going to contain files that are not going to be seen inside the actual website so for example a pure phsp file that just needs to run a script in order to do something but it’s not a actual file that we visibly see as a page you know in the same senses we see this uh index. PSP file because that’s the front page so the include files are just basically extra files that just run code the first thing I’m going to do inside this folder here is create a new file so I’m going to say I want to create a new file I’m going to call this one on dbh do in.php which stands for database handler. includes. PHP now it’s very important to point out here that it is possible to go in and name it as db. in which is also a kind of file that we can use and create phsp code inside of um but this kind of file can create issues and some people when they hear that I I call it in.php think that we are creating a in file that’s not what we’re doing here the in is just a naming convention so to speak so it doesn’t really do anything uh this is going to be a PHP file so in this case if we could call it db. in or you could call it db- Inc or just dbh Inc if you wanted to it’s really the same thing cuz it’s just a name uh so don’t get confused about the naming convention that I’m using here it’s just a way for us as the developer to know exactly what kind of file this is so what I’m going to do is I’m going to name this file and create it and inside this file I’m going to open up my PHP tag so we can actually create some PHP code and it’s important to point out here cuz we talked about this in my syntax video at the very beginning of this course that when we have a pure phsp file we don’t create a closing tag so for example you would create this at the end of a you know a pair of PHP tags we’re not going to do that when it’s a pure PHP file and the reason for that is if we were to accidentally go below here and create some HTML or something just by mistake then we can create more damage than you know not doing that again you can always go back and watch that episode at the beginning of the course if you want to know more about this but we’re just not going to put it in here okay um so going in here what we can do is we can start off by saying that we want to include some information about our database uh we did of course create a database in the past couple episodes so if I were to go in here you can see that I created a database called my first database and inside this database we also created a couple of tables that could actually have some sort of information inside of it so we have a comments table and we have a users table where we actually do have some users uh just because we learned how to insert and you know update and delete data and that kind of thing so we have some stuff in here is what I’m trying to say all we have to know for now is that we have a database called my first database because we do have this uh PHP my admin hooked up to our server so when we do actually need to connect to our database we do need to tell it which one of all these databases we’re trying to connect to because it is possible to use more than just one database inside a website you can use multiple if you want to and there there is Arguments for doing that you know for different reasons but for most websites you’re just going to have one database for everything um so remember the name my first database so going back inside our file here and I’m going to create a DSN which stands for data source name which is US telling our server uh what kind of database drial we’re trying to use and you know what is the dat database name uh what is the host that we’re trying to connect to here in this case it’s going to be Local Host so we need to give it a little bit of information about this database we’re trying to connect to uh so in our case we’re using a mySQL database so we’re going to create a variable I’m going to call this one DSN and I’m going to set it equal to a string and inside of this string here I’m going to say that I want to connect to a mySQL database driver then I want to tell it what kind of host I’m trying to connect to here in this case it’s going to be Loc host so we’re going to say equal to Local Host semicolon and then I want to tell it the database name which in this case here we did already just go in and check in my case it’s called my first database and again if you called it something else in the past couple episodes you do need to change this so it matches whatever you call your database um so you basically just go in and change the information here depending on what database you’re trying to connect to um so underneath here I need to give it two more pieces of information I want to give it a database username so we’re going to say DB username and this one is going to be equal to root and I do want to explain this in just a second but let’s go ahead and create the next one as well so I’m going to create a database password and this one is going to be empty in my case here password there we go um so basically when we have a database we do also have a username and a password in order to connect to our database which makes sense uh so in my case because I’m using my examp software and I have not gone in and actually changed this the default username and password is going to be root and then no password I do want to point something out here though because if you’re using a Mac computer you may need to go inside your password and write root um because I did experience 12 years ago when I was studying my web development bachelor’s degree that people who were using Mac computers and using xamp did actually need to include root in both places because XM is a little bit different on Mac than it is on Windows when it comes to at least this information here uh so if you’re sitting on Mac and doing this right here doesn’t work for you try writing root both places and see if that works for you or just Google how to change your password and username for your database again there’s a couple of different options here uh we’re just going to stick with this information for now and then I actually want to go down and run a TR catch block so we can actually see we get some a popup here and it looks like this so basically we have a TR cats block which means that we are basically running a blocker code and if an error occurs then I can do something else by catching the error and then doing something with the error mthod that’s basically what a TR catch is and you’ll see this very often inside PHP because a TR catch blog is very useful so what I’m going to do inside my try is I’m going to say that I want to run a PDO connection and we didn’t actually talk about this yet because when it comes to connecting to databases we have three different ways we can do it we have what is called a MySQL connection which is very bad and you should never use that because it’s obsolete and they actually came up with a new way to connect to a database which is called mysqli which stands for improved um this basically goes in and does extra SQL injection prevention um so don’t use my SQL because there is some security things that is just not very good but now let’s not talk more about was you cannot connect to a database cuz we have talked about that now but what you can do is you can connect to a database using mysqli I or we can also use the third method which is called PDO now PDO stands for PHP data objects which is basically another way for us to connect to a database that is a little bit more flexible when it comes to different types of databases out there mysqli is very good when it comes to mySQL databases but if you plan to connect to other types databases for example SQL light or something then you can use something like PDO it has also been a thing in the past lessons of mine that people do request that I use PDO so we are just going to stick to using PDO since that is going to be the one that people lean more towards because it is more flexible um but for people are curious about what exactly the difference is when it comes to the actual programming when it comes to mysqli and PDO um it’s basically just the methods that that you know change a little bit when you when you start programming it if you are curious about mysqli you’re more than welcome to look it up but we’re going to be using PDO in these lessons here so having ranted a little bit about different ways to connect to a database we are now going to create a PDO connection so PHP data objects is a way for us to create a database object when we want to connect to a database so basically we turn the connection into a object that we can use inside our phsp code and just refer to that object whenever we want to connect to a database so what we’re to do is we are going to have a variable called PDO I’m going to go inside of it and create a new PDO object so we’re going to say new PDO and what this basically does is that it instantiates a PDO object off of a existing class inside our PHP language that is going to create this connection based on a couple of parameters so for example what is the you know the database driver going to be what is the uh host going to be what is the database name we’re connecting to what is the username what is the password and then it’s going to create a database connection object that we can use so going inside this PD I’m going to give it a couple of parameters the first one is going to be the DSN which we just created up here uh so we have all of this information then I’m going to give it the username so we’re going to say DB username and then I’m going to give it the database password so doing this here we now have a database object and just to mention it here we could Technic technically just take this one lineer code and do this right here and that would actually be enough to connect to our database if all the information is correct every single time um but we do want to have some sort of error handlers you know if an error happens then we want to be able to grab that error message and show it inside our website um so you know even though this is like the pure bare bone you know enough to connect to a database uh it is a good idea to run this TR cats block here to you know get any sort of potential errors so what I want to do is I want to set a attributes inside this object that we created here uh we can do that by going in and say we want to grab this PDO variable that we just or object that we just created here because now it’s no longer a variable it is actually a object and I want to point to a existing method inside this object called set attributes which is going to allow for us to change a couple of attributes about this particular object that we just created for example how do we want to handle error messages that we may run into when we try to connect to our database so inside the parameters here I can say I want to grab a specific uh attribute so in this case it’s going to be PDO colon colon aore error mode so e r r m o d e you can actually see it pops up over here uh so we’re going to grab the arror mode and then we’re going to say we want to set it to a PDO colon colon e r r m o d eore exception so right now we are saying that if we get a error then we want to throw a exception which means that we can go down inside our cats block down here and actually grab that exception which is you know information about this error here so what I can do is I can say I want to catch my PDO exception and I want to name this one variable e so we’re basically just saying that this is a PD exception type which is going to be named as variable e which is a placeholder that we can refer to inside the curly brackets here so if an error message happens then I want to go in and Echo out a message connection failed colon space and then I want to concatenate a error message so right now we are grabing the Exception by referring to variable e so I want to go after here and paste that in and say I want to run a method called get message parenthesis and semicolon so right now we’re getting the exception which is the error that maybe thrown and then we want to grab the actual error message and Echo that out inside the browser so if we don’t connect correctly to a database then just go ahead and throw an exception here but like I said this one liner code here is actually the one line that we use in order to actually connect to our database so all this other stuff down here is error handling and throwing you know error messages inside the screen if the connection fails that kind of thing so for now just know that this line here is the important one so now that we have this we can actually go in and actually do stuff inside our code so if I wanted to you know select data from a database or if I want to insert data inside my database I can do that by simply running uh this one connection here and actually querry something into my database using PHP code and we haven’t talked about how to do that yet but that is something we’re going to talk about in the next upcoming lessons uh so for now we learn how to connect to our database and in the next upcoming lessons we’re going to learn how to insert data we’re going to learn how to update and delete data so we can actually use the connection for something so I hope you enjoyed this lesson and I’ll see you guys next [Music] time now I just got done watching the last video that I uploaded to my channel and I thought why not just show you how to go in and change your username and password when it comes to connecting to a database because if some of you are sitting there with with you know a Mac computer or something where things are a little bit different when it comes to the password then you may want to know how to change your username and password in order to you know decide yourself what you want it to be and as I did that I did also run into a very well-known bug when it comes to PHP my admin that actually prevents you from going in and clicking on user accounts in order to change your username and password now the error you might be getting is called exam error number 1034 index for table DB is corrupt or something like that so you know having something corrupt inside a table uh there is a very easy way to solve it so I will show you how to do that after I’ll show you how to go and change your username and password and then you know at the end of the video I’ll show you how to solve a corrupt table so the way you change your username and password is by going inside PHP my admin by clicking it up here to make sure you’re inside the main page of PHP my admin uh because if you click a database you can see all the menus change so that is not what you want to do so going inside PHP my admin we’re going to go under user accounts and then you can see we have all these different users that are here as a default now the one that you’re looking for is the one that has a host name of Local Host and a username as root how do we know that well we used Root in the last episode where we actually connected to our database so you know you need to have one where the username is root and also where we connect to a host called Local Host so this is going to be the one down here at the bottom so what you can do is click on edit privileges so you can go in here and then you can see we get a new menu where we can change this user here uh we do have one up here called login information so if you click that one you can see that we can change the username from root to something that we may want it to be um so if I want this to be Denny or something else then we can change it in here just change it go down and actually you know click go at the bottom here in order to make the changes happen uh do not go in here and do the password in here cuz there is apparently a bug that can happen where you go in and change the password directly in here uh I’m not saying it is going to happen to you but it is better to go back up inside the top here where it says change password click it and then change it in here instead so you go in here uh you choose to have a password then you enter you know something so in this case it could be anything that you might want to think of and then you retype it and then you click go and then you basically change the user information and the password for the user that we use in order to connect to a database um but now let’s talk about the bug that you may encounter which is the one called eror code 1034 uh so basically when you click this user accounts up here instead of going inside right here it may throw a error which gives you a popup with the error message that I just told you about and basically can’t access this page here the way you’re going to fix it is by first of all figure out where exactly the corruption is because that is what you need to find out in order to solve it uh so the way you can do that is by going back inside PHP my admin and then clicking on whatever database that it’s actually telling you there is something corrupt inside of so when you give the error message it’s going to give you a quy string where it is going to say there is a corruption or an error happening from a certain database uh so it’s going to have a qu that says something something from a certain database which in my case was from the mySQL database which is the most common one to get this corruption in so if you were to go down click the mySQL database over here in the side you’re going to see all the tables from in here uh in my case it did actually tell me me inside the error message that it was from inside the database table but if you’re a little bit doubt about where the croping is you can scroll down to the bottom here and go down to where you can check all and then with selected you’re going to say you want to check table and when you do that it is going to check and give you you know some status thing now in my case just checking the tables here automatically fixed the error for me which I actually thought I was going to show you how to actually fix the error when I started this video here because I did not go in and repaired it yet uh but just checking the table gave me a couple of error messages it said that my MySQL DB here there was some sort of Errors inside of it it was corrupt uh it gave me red warning messages and I basically just went back again to PHP my admin from here and that fixed the errors for me uh but if that doesn’t work for you then you want to go down and just take note that it was the MySQL do DB table go back inside the mySQL database and then you want to make sure you select the DB table that is over here then you’re going to scroll down to the bottom and with selected you’re going to say repair table and when you do that it is going to try and repair it and when you do that it should also fix the error message for you so after you repaired the table that is broken uh you can go back inside PHP my admin and then you can click on user accounts and then everything should be fixed so you can go in here and and actually um you know change your username and password so that is how I can solve it in my case it solved it just by me checking the table I didn’t even have to repair it in order to to fix fix this issue here but if checking it doesn’t work then choose repair and basically that should work for you so with that said I hope you enjoyed this lesson lesson fix I guess this is kind of well I did show you how to change the username password so this could be considered a lesson so um thank you for watching and I’ll see you guys next time [Music] so in the last episode we learned how to connect to a database directly from inside a website and in this episode we’re going to learn how to insert data directly from inside our website so we don’t have to go inside the database and start typing SQL code in order to do that uh so we’re going to do everything from inside our website here yes I did cut my hair uh it is quite a bit shorter for health reasons so it is a little bit different it wasn’t my choice but it is what it is I do want to start out by pointing out a little bit about what exactly we’re going to be doing when we connect to our database and insert data into our database since there is a couple of ways you can do it uh we did talk about us using PDO in the last episode which is what we’re going to stick to in this video here so we’re not going to use mysqli or MySQL which is outdated uh we will be continuing to use PDO to do this and we’re also going to be using something called prepared statements and that is something that is very important for you to do uh you can insert data into a database without using prepared statements but that is not secure so I don’t think it’s a good idea to teach you how to do it without using prepared statements since there’s never a reason for you to do so uh so we will be using prepared statements in order to securely insert data into a database and just to talk a bit about what exactly prepared statements are and what exactly they’re supposed to do uh let’s say we have a website like this where we have a signup form where you can go ahead and type in your username your password your email and if you use a were to go inside your website here and go inside one of these puts it is actually possible to type code directly inside these inputs here so just like we talked about cross site scripting in a previous episode like you had to sanitize your data and validate it to make sure that people couldn’t inject JavaScript code into your website it is also possible to go in and write SQL code so if you were to write SQL code directly inside this input and the user submits it then they can actually destroy your database because maybe they decide to write a SQL query that can go in just delete the database or something so to prevent the user from being able to write SQL code directly inside an input like we have here uh we need to use prepared statements now the way a prepared statement work is basically we send in the query that we write so the SQL code and we send that to the database first and then afterwards we bind data submitted by the user and then send that to the database afterwards so because we separate the query from the data that the user submits to us we can do them separate ly and not have SQL code have an impact on the query that we write inside our PHP code because they’re separated so using prepared statements is a very good idea so having talked a bit about that let’s actually get started on creating an actual PHP script that can actually insert data into our website so going back inside our editor here you’ll notice that I do have one thing that you do not have from the previous episode uh so in the last episode we did create this database Handler together uh where we can just go in and grab this PDO variable in order to connect to our database but inside my index page I do actually have a form that I created which is the one you just saw inside the browser uh this is just basic HTML form you should know HTML by now so this shouldn’t be anything new to you uh this is just a basic form where I go in and say I want to submit this data to a PHP file which is going to be inside by includes folder called form handler. in.php we did talk about the naming convention that I use here with Inc so if you watched the last episode I did explain that in that episode and I am using a post method since we need to submit data and when we submit data it is more secure to use a post method and that is the method you’re going to be using most of the time when it comes to submitting user data when you want to grab data from a database you use a get method most of the time and then you can see I have a couple of inputs down here I have one for the username I have one for the password and I do also have one for the email address now I do want to point something something out here which is that we do have an attribute inside each of these form inputs which is called name uh we did talk about this in a previous episode I we talked about submitting data using a form uh this name attribute is the name that we’re going to be grabbing inside this file up here when we send the data to the other page so it is very important that you have a name attribute and you remember what they are or you can just go back and and look at your form um so you know exactly what you need to grab in order to grab the data so having talked about this uh let’s go ahead and start creating this form handler. in.php file since that is what we need in order to actually you know run this data submitted by the user so we can actually insert it inside our database I do also want to point out to you before we continue that this is the data that is fitting into the table that we created together in the uh table episode so as you can remember we did actually go inside our database here and we created two tables we created a comment and a user table and inside the users table we do have an ID username password email and created ad now we did set it up so that ID and created ad is automatically created for us so we don’t need to submit any sort of data for that uh but we do need to submit data for username password and email which just so happens to be the three inputs that I included inside my form so now that we know this let’s actually go and create our form handler. in. phsp file so I’m going to go inside my includes folder over here right click say I want to create a new file I’m going to call it for form handler. in.php and having created this one we can now start creating a script that actually goes in and submits this data to our database so the first thing we’re going to be doing is we’re going to start up our PHP tags we’re not going to close them though which we talked about in the previous episode since this is a pure phsp file that is just going to run a script and then that’s it we don’t need to have a closing tag because it can actually cause issues which we don’t want to happen the first thing we’re going to do is to actually run a check to see if the User submitted the data and entered this page the correct way because it is actually possible to go inside our website here and go inside the URL and then directly say I want to go inside my includes folder forward slash and then form Handler uh. in.php and then you can see I actually enter this script that we just created and entering this page here in the way that we just did just by typing into the URL is not a good thing uh so we do need to make should we check if the user actually submitted this form in order to access that page because otherwise we don’t want them to access it so going inside our code I’m going to go in and create a if statement I’m just basically going to check for a super Global so in this case we’re checking for a dollar signore server and then I want to set brackets and go inside and say I’m looking for a request method requestor method and check if it’s equal to a post method so if the user actually submitted a form using a post method which we did actually do cuz we just did it right here and enter this page using that method there if not then I want to create an lse statement and basically say that I want to send the user back to the front page because you know they’re not supposed to be here and we can do that using something called a header function so basically create a header function and say we want to add a location colon and then you add in the link that you want to send them to so in this case here we’re inside a includes folder so in order to get to our index page we have to go back One Directory so we say do do forward slash and then we say index. PHP so basically now if the user tries to access this page without actually submitting the form so if we were to go inside the URL here and say I want to go inside my includes folder and access this page you can see oh okay now I got sent back to the front page so everything is working perfectly so now what we want to do is we want to go inside the actual if condition and say okay so if we did actually access this page legitimately then I want to actually grab the user data so I’m going to create a variable called username and I’m going to set this one equal to a dollar signore post since we sent this data using a post method and inside of here I’m going to reference to the name attribute that we actually submitted inside uh the form so in this case here we call the username or at least I did I don’t know what you called it but if you followed my tutorial you did call a username and then I’m going to cover this down two more times and the second one is going to be PWD for password and the third one is going to be email and just like so we now grab the data and you may point something out here because hey Daniel you forgot something you didn’t use the HTML special characters function in order to sanitize the data why didn’t you do that uh this is actually something we have to do when we want to actually output data inside the browser so when you’re not outputting data into the browser it is not dangerous at least as it is right now to not sanitize the data so anytime you have to Output data into the browser and actually spit it out so if we to go down here and actually uh do something like this here so if I go down a couple of lines and say I want to Echo out the username then I would need to sanitize this because I’m now outputting data into the browser so I would need to go in and actually wrap this in HTML special characters otherwise this is not going to work and it’s going to be unsecure but because right now we’re just submitting data into a database and not outputting it inside the browser uh we’re not going to be sanitizing anything just quite yet you can of course do it if you want to and sanitize the data like we did in the last couple of episodes and just you know submit the data into the database being sanitized uh but it is best practice not to do so unless you actually try to Output data into the browser and the reason for that is that we are converting this to HTML special characters so in some cases you know we want to use data from inside a database uh we don’t necessarily want to have it in HTML special characters and use it inside our code for example if we’re not planning to actually output it inside the browser so do be aware that there are some cases where you don’t want to have HTML special characters translated data inside your database so in some cases you don’t want to have it the next thing I’m going to do here is I’m going to run a TR cats block which we talked about in the last episode basically we’re just trying to run a blocker code and if it fails then we want to catch an exception so we’re just going to go down here and say if there is some sort of error happening then I do want to go in and say I want to grab a PDO exception and I’m going to create a variable e as a placeholder that I can refer to and then inside of here if something happens that goes wrong when I actually try to insert this data into the website then I do want to you know output a error method so I’m going to die which is a function we have inside PHP that is just basically going to terminate this entire script and stop it from running and it’s going to Output a error message so going in here we can actually say we want to write a custom error message in this case here I could say something like Cory failed so I’m going to say Cory failed colon space and then I can concatenate the error message so I’m going to point to the exception and then get method on up method message get message it is a method but it is called get message so it is the same thing um the next thing I’m going to do is I’m going to go inside this try block that we have up here and I’m actually going to grab my connection to our database because we have that inside our db. in.php file to do that I’m going to use something called require require uncore once and this is basically going to say that we want to link to a file that we have somewhere so I’m going to grab a PHP file for example and just say we want to link it inside the script here so when I go in and say I want to link to a db. in.php file I’m just basically linking to this file that we have up here do keep in mind that because I’m inside the includes folder right now and typing this script here uh we don’t need to go inside another directory or something if this dbh the link the PHP was inside another directory you would of course need to go back out of the directory and go inside the correct directory and doing this here is basically the same thing and just going in and saying oh okay I’m just going to include all this code and just paste it in here like this is the exact same thing so we’re just basically linking to another file which means that we have access to all the code inside that file uh after this point here and I do also want to point out because I don’t think we talked about this yet we do have require uncore once we do also have require if I can spell that correctly there we go we do also have something called include so we can say include and we can also say include underscore ones all of these basically do the same thing but with slight variations so include for example we’ll go in and say oh okay so we’re going to include this file just like we did up here but if we can’t find the file then it’s going to give you a small warning saying oh I can’t find the file include underscore once it’s going to do the same thing but it’s also going to check if the file has already been included earlier inside the script and if it has then it’s going to throw you a warning and when it comes to require and require underscore once they do the same thing as include and include underscore ones except instead of just throwing a warning it is going to actually run a error so going to have a fatal error saying oh okay we can’t find this file so stop everything from running or it’s going to say oh you already included this file once so stop everything from running uh so these two slight variations of each other with you know different exceptions in this case here we’re just going to go and use require uncore once because we don’t want to run the connection if we already have the connection included somewhere else so what I’m going to do now is I’m going to write a variable called query because I now want to actually create a query that I can send inside the database to insert data so I’m going to set this one equal to a string which is going to be our SQL quy string that we’re going to submit and I’m going to run a insert statement and you may recognize this one because we did learn how to do this inside our database episode this is the exact same thing so the SQL code is basically insert into and then we’re going to choose a table so in this case it’s users and I also want to make sure that we include our column names so in this case if we have username we do also have some something called a PWD and then we have email then I want to include the values so I’m going to say values and then parentheses and I’m just going to go and wrap my code here to make sure that it doesn’t disappear off screen so it goes down to next line instead and then I’m going to go inside and give it the actual values now we could do this here and just say we want to copy the variable and just paste it in and say comma space and then password paste it in and then the email and paste it in and this would actually be okay uh do keep in mind to close off with the semicolon at the end here because this is a SQL statement which means that you do need to end off the SQL statement with a semicolon just like we did inside the database episode so it may look a little bit weird that we have a semicolon here and also one here but do keep in mind this is the SQL and this is the PHP but like I said earlier we’re not supposed to insert user data directly inside our query otherwise they can do something called SQL injection and destroy our data base so doing it like this is not really seen as a good practice now there is two ways we can use a prepared statement either you can use something called name parameters or you can not use name parameters I will show you how to do both ways and we’re just going to do one of them at a time so using not name parameters what you basically just do is you replace these different user data with question marks so you say question mark question mark and question mark and these are going to act as placeholders so we later on can actually go in and insert this data or bind the user data to this query after we submitted the query so going down to next line I’m going to create an actual statement which is a prepared statement that I can actually prepare to query this query inside the database so what I’ll do here is create a variable called stmt for statement then I’m going to set it equal to our database connection which is variable PDO which we have access to now because we actually required this file up here and then I’ll point to a method called prepare parenthesis semicolon and then inside this prepare statement I’m going to submit my query so basically now I’m submitting the quy to the database so it gets run into the database and then afterwards I can actually go and say okay but now I’m going to give you the data that the User submitted so I’m going to reference to the statement we just created so statement and I’ll go ahead and point to another method called execute so parenthesis and semicolon and inside this method here I’m just basically going to submit the user data and I’m going to do that using a array so I’m going to add a pair of brackets and then I’m going to go in and just submit these data one by one so we’re going to say username then we’re going to say password and then we’re going to say email so doing this here is going to actually submit the data from the user and actually sign them up inside the website uh but before we test this out let’s actually go ahead and just finish off the script here uh cuz there’s a couple more things that we need to have in in order for this to actually be kind of proper properly done the first thing we’re going to do is manually close the statement and also the connection to our database it’s not something you have to do because this is actually going to happen automatically uh but it is considered best practice to do so manually to free up resources as early on as you can uh so going down here what I’ll do is I’ll refer to my uh database connection so that is variable PDO and I’m going to set it equal to null then I’m going to go ahead and go in and say I want to grab my statement and I’m going to set it equal to null and I just want to point out here there’s a couple of ways you can do this there’s also methods for closing off a connection or a statement um but I’m just going to refer them to null which is the same thing as just saying okay so just you know not set them equal to anything and free up those resources and the last thing I’m going to do is I’m going to write a die method just like we did below here when you know some sort of error message happens then we want everything to stop running I do also want to point out here that you can use dive or you can use something called exit and people do argue a lot about you know whether or not it doesn’t matter which one you’re using the general rule of thumb is that if you’re just closing off a script that doesn’t have any sort of connection running then just use exit but if you’re running something that has a connection inside of it then use die and of course we do also need to make sure we send the user back to the front page after they signed up inside our website so I do want to go down here and copy this header function and then paste it in right above the die statement so we send the user back to the front page and then kill off this script here so this is everything that we need in order to get this working so I could actually go inside my website here and go in and say I want to sign up John uh do you know just to give him some sort of you know username uh password is going to be one 12 three and then I can call his email John gmail.com just to give him something if I were to sign him up inside the website you can see we get back to our front page if I go inside the database and refresh it you can now see that we have another person signed up inside our website so as you can see our script is working perfectly I do want to point something out here though which is something that I know some people might point out uh why is my user id 10 on this person here it’s just basically because I inserted some users before this tutorial here so the the ID is going to change a little bit compared to yours so having done this we now did this using non-name parameters but what about name parameters inside our code uh so if we were to go back into inside the form Handler I do recommend using name parameters because it actually allow for us to know inside this query here which data is supposed to be inside where when it comes to using non-name parameters like we did here I do also want to point out that the order in which you insert the data down here inside the execute has to be the same order as inside the columns up here so these have to match up with each other but when we use name parameters this is not the case because I can actually go in and say instead of question mark I’m going to write a colon and then then I can give it some kind of name so I can say something like username uh I can also say the second one is going to be colon PWD then I can say the third one is going to be colon and then email and in this sort of way instead of question marks I’m now giving them actual names so after preparing my query here I can go below and I can actually go ahead and bind my user data to these different name parameters up here and I can do that by referring to my statement so I’m going to say statement and then I’m going to point to a method called bind param which stands for parameters then I can go in here and say that I want to have two pieces of information I want to first of all have the actual name parameter so the first one is going to be the username going to insert that one and then the second one is going to be the actual user data so in this case our username variable up here so if we were to paste that in we now have a name parameter bound to a actual data submitted by the user so I’m going to copy this down two more times and I’m just simply going to change these so password then I’m going to change to email and then I want to make sure I delete the array that we have inside the execute down here because now we don’t need it anymore because we actually B them up here instead so doing it like this we now use name parameters instead of notame parameters so what I can do is I can go inside our website here and test this out one more time so I can say Jane do in this case here so we can say pass 1 2 3 4 then I can say Jan gmail.com and then I can sign up go inside the database refresh it and then you can see we have Jane do instead and this is basically how we can go in and actually submit data using our PHP code from a website instead of going directly inside a database and manually coring the database in there so this is how we can insert data uh I hope you enjoyed this episode and the next one we’re going to talk about how to actually update and delete data and then after that one we’re going to talk about how to select data and show it inside our website so hope you enjoyed and I’ll see you guys in the next video [Music] so in the last episode we learned how to insert data into our database directly from inside our website and this episode we’re going to talk about how to update and delete data from inside our database directly from inside our website now as you can see I did change things a little bit from the last episode inside my index page I did actually include a second form and I did also change a couple of things inside the original form up here uh so just to quickly go over what exactly I changed I did go in and change the title so now it says change account I did also include a title for the second form down here so it says the leete account and I went in and changed the action of the first one so went inside the update form and said I wanted to send all the user data to a user update page that we haven’t created yet but we’re going to in just a second and inside the delete form down here I just went in and said I wanted to send the data to a user delete. in the PHP file and I did also delete the email input from inside this form and that is basically all I did here and just to point it out here I do also have the form handler. in the PHP found in the last episode since we basically just need to copy paste everything so just to show it I still have it in here so we have the code here uh for people who have not followed the last episode you can just kind of copy paste what I have in here um and just use this code when it comes to that next part so what I’m going to do is I’m going to go inside my include folder and create these files here so I’m going to create a user update. in phsp so I’m going to right click on includes and say I want to include a new file and just basically paste in the name of that file then I’m also going to be creating one for the delete user or user delete. in.php so I’m going to copy the name here go inside includes right click and create a new file so the first thing we’re going to do is of course talk about how to update a user inside our website so what I’ll do is I’ll go inside my user update and paste in the code from my form Handler so going inside my form Handler I’m just going to copy everything go inside user update and just paste everything in and all you need to do here is essentially just go in and say you want to change the query down there just slightly so it actually matches up with a update statement instead of a insert statement so it’s quite simple to just go in and run a update statement instead of a instant statement uh from the last episode so I’m just going to text wrap everything here so we can see everything on screen and we’re just basically going to change the insert statement into a update statement so we’re going to say we want to to go in here and update and I want to update my users table and I want to set some certain values I can just basically delete everything that we have here I want to set the username equal to something new which in this case is going to be a placeholder uh because we did talk about prepared statements in the last episode so we are going to create a placeholder called username and then afterwards here we’re going to say what else needs to be changed so in this case I do also have a password column that needs to be set equal to the password submitted by the user so again we’re going to say single quotes and inside of here we’re going to refer to a placeholder called PWD and then we’re going to add in the last one which is going to be the email so we have a email column that is going to be set equal to again single quotes and then we insert a placeholder called email after doing this we need to tell it where inside the table we want to change this because if I were to just submit this then all the users inside my table are going to be uh updated to what the User submitted just now so I want to go in and say where and in this case here we’re just going to go and say we want to grab a user that has a certain ID as something specific so I’m just going to say ID is equal go inside my database here and just pick a random user that I have so I can say Bess is going to have his username changed uh so we’re going to say his ID is two I’m going to go inside and again if you have another user with a different ID just go ahead and choose some sort of user from your database in my case I’m going to choose B that has an ID as2 um of course this is very unorthodox because typically inside a real website you would have a user that is locked into the website currently who’s trying to change his user information and because of that you would actually have his user ID grabbed and stored inside a session variable so we could actually just grab the user ID and say oh okay so that’s the user we need to change this information of uh so right now we’re just manually going inside the database and grabbing a random user and typing it in here cuz you know we’re not we don’t really have a real login system right now so this is just for practice okay so we’re just grabbing a random user here uh so doing this now basically what you would just do is you would go down you would bind the parameters in the same sense you know you would actually prepare the statement find the parameters execute the statement and that is actually pretty much it I just realized that we don’t actually need to have these single quotes up here so let’s actually go and delete those so we’re not going to have single quotes around the user data uh in inside this quy up here so I’m just going to go and delete them like so and with that Sav we’re going to go back inside the website and actually test this out so I’m going to actually have something written in so in my case here I’m going to change bass’s username to Bassa is cool and I’m going to have 1 2 3 4 as the password and then I’m going to change the email to bis cool at gmail.com and if I were to click update here you can now see that we get sent back to the front page if I go inside the database refresh it and now everything is has been updated so Bessa now has a username as B is cool 1234 and B iscool gmail.com so everything gets updated in here and looks correct but now what if I want to delete a user from inside my website how can we do that because that is also very simple to do uh so if I were to go inside my user delete and copy paste everything from inside my form Handler so we’re just going to copy everything again insert that inside user delete now we basically do the same thing we just go inside the Corey up here and say okay so we’re not running a insert statement we are actually running a delete statement and this one is going to be even easier because we have less data to handle so we can just go inside and say okay so in this case here the user did actually not submit a email so I’m just going to go and delete that one for now then I’m going to go down and change my insert into statement into a delete statement so I’m going to say I’m going to delete from users and I’m going to say where a certain username and password is equal to what the user submitted I could also use an ID just like we did with update cuz that would be the typical thing when you have an actual login system where the user is logged in so you have their ID and you can do that uh but for now let’s just go Ahad and use the username and password since we did submit it here so why not just use it so I’m going to say where the username column is going to be equal to a placeholder which is username and then I’m going to say and where the password column is going to be equal to the password that the User submitted and do also make sure you close off with a semicolon here and then what I’m going to do is I’m going to go down delete the last bind parameter because we don’t need that since we don’t have a email and this is basically all we have to do then we can actually go inside and delete the user so if I were to save this go inside my website here and refresh everything and say I now want to go in and delete the user that has a certain username and password so in this case I could say let’s go and delete Danny that has a password as 123 so we would to go inside my website here go down inside delete account I can say Danny that has a password as 1 2 3 delete his account then we’ll back again so if we were to go inside and refresh you can now see that Danny has been deleted and this is basically how you can go in and update and delete data from inside a database directly from inside a website so it’s quite simple to do uh in the next video we’re going to talk about how to actually select data and show it inside our website so that is going to be very fun to do so I hope you enjoyed this lesson and I’ll see you guys in the next video [Music] so now that we learn how to insert update and delete things from inside our database directly from inside the website now we have to talk about how to actually select things from inside a database and show it inside our website so to begin with let’s go and take a look at what exactly I have inside my text editor so you can actually you know copy what I have here since we need a little bit of HTML in order to get this working inside my index page here I do have a very basic form at the bottom I’m just going to go and text wrap so you can actually see what’s going on here I just have a very basic form that I styled a little bit inside my website so it actually looks somewhat nice to look at uh which is why I have this class up here you can style this in however way that you want to The Styling has nothing to do with the phsp so it’s still going to work even if it doesn’t look very good inside your website I just did it to sort of like have something nice for this tutorial here but as you’ll notice inside the form here I actually included a action that does take us inside a include file now we’re actually just going directly to a regular page inside the website here called search.php and we’re still using a post method since we’re trying to submit data in this case here inside the form you can see I have a very basic label just to have a label for this input down here that goes in and just simply takes a input from the user where we can search for something inside the database now in this case here because I wanted to create something just a a very simple little thing um I wanted to go inside database and search for any sort of comments made by a certain user where we type in the username of that user so if that user made a comment then I want all the comments to show inside that page that I’m linking to called search. PHP so technically we’re creating a small search system here for a website so if you want to have a search system inside a website you can build a very basic one in this sort of sense here uh so you actually learn how to build something that you could potentially use inside a small project if you wanted to so so essentially it’s just a basic form where we go in and we type in a search word and then we just search for something so uh the only important thing here to really note is where exactly we’re taking this data to so in this case the action the method as well as the input down here where we actually assigned a name called user search so with this basic form here let’s actually go and start creating a search. PHP file so going inside our project folder I’m just going to go and create a new file not inside the includes folder but just inside where I have my index page uh so I’m just going to create a search. PHP and then I’m just going to go ahead and create it now inside this file here I’m just going to copy paste everything from inside my index page since this is just a regular page inside our website so I’m just going to copy everything and paste it in and what I’m going to do here is I’m just going to go and remove my form since I don’t think we need to have it inside this page here and what we have to do now is just basically go in and write some PHP code that queries our database and searches for certain uh data in inside the database using the search term that we wanted to search for and show it inside this page here so what we’re going to do is we’re going to go to the very top of this file and I’m going to go above my doc type and I’m just going to start off my PHP tags now in this case here we do actually have HTML like this is an actual page inside our website so we do need to include a closing tag around the PHP code here so we can’t just not have it like we did in the previous episodes um so what we’re going to do is we’re actually going to go in inside our previous file just any of the previous files we created in one of the last episodes um so we did create a form Handler we created a user delete and a user update it doesn’t really matter which one you want to to go into I’m just going to use the form handler. ink the PHP file here and as you can see we have a bunch of PHP code that we did create in the last couple of episodes I’m just going to text wrap everything here so we can actually see everything if you want to copy what I have here you can just kind of see what I have and I can just very slowly here scroll past it and you can pause the video uh but this is something that we did create in the past couple of episodes um so what I’ll do is I’ll copy everything except for the beginning PHP tags since we don’t need that cuz I did open and close phsp tags inside the top of my search. phsp file here so I’m going to paste everything inside at the top of the site here and inside of this PHP code we now just need to make the alterations that we need in order to match it up with the form from inside the index page so if I were to go inside my index page again you can see that we did have this form that I talked about extensively a minute ago um and we just basically have one field which is called user search so I’m going to copy that name go back inside my search. phsp and say I want to grab a user search and I’m just going to delete the other two uh post methods so I’m just going to change the name here as well to user search so we do actually have a variable that makes sense with the naming and with this we can now just go down and change the Quarry since we need to make sure this is actually a select statement we have learned how to do that in a previous database episode uh so what I’m going to do is I’m just going to go and delete everything again we’re just going to make sure we text wrap here so I can select everything and I’m just going to delete the entire query that we have in here what I’ll do is I’ll create a select statement so I’ll say select uh everything so select all from a comments which is our comment table inside the database where a username is equal to a certain value in this case here it is going to be our user search so I’m just going to write a placeholder called user search and this is basically all we need inside this quy here we’re just selecting all the data from inside that row including you know the the actual comment the user made when the comment was made which user made that particular comment uh what user ID do they have what just selecting everything from inside that row inside our comment table just to show exactly what comments table I’m talking talking about here if I were to go back inside my database so inside my database here we do still have the same tables that we did create together some episodes ago I’m going to go and Link those episodes in the description if there’s someone following this tutorial here thinking oh well I don’t have this so I’ll go ahe and Link that in the description so you can actually keep up with what we’re doing here but basically we just created two tables we created one called users and one called comments and inside my comments table I actually went in and included a couple extra comments uh which we did learn how to do so you can go back again watch that episode and create some more comments in there I just basically went in and manually typed those in inside the SQL tab up here I created a couple of comments for cing a couple for bess’s cool and Jane do because those are some of the users that I have inside my website so if I were to go inside my users table you can see that I have some of these users in here so I do have quite a few comments now uh that I can go inside my website and I can actually pull these out depending on the search term that we put inside our query so going back in you can see we’re selecting everything from comments where a username is equal to what we submitted inside the website so going down below here uh first of all we need to actually send in the query so we’re doing that with this prepare statement here again it is important to mention here that we are going back to grab our database file which is inside a includes folder with the connection to our database again this is something we learned in a previous episode which I’ll also link below if you need to have that one but we do need to go in and actually change the path because like I said we’re not inside the includes folder anymore so inside the require above here where we actually grab this database connection we do need to go inside the path and say we want to go inside and includes folder and then grab the dbh that in the PHP file otherwise it’s going to say oh we can’t find this file cuz it’s not linked correctly right so with this done I’m going to go back down and the place where we actually bind the data that we submitted from the actual form uh we do need to change these as well since we don’t have three pieces of data data submitted we just have one and we do also need to change the names of these down here so I’m going to copy my user Search and say that is what I have as a placeholder and I’m also going to grab the data called user search and put that in as my variable and then I’m simply going to execute the statement here and at this point here things are going to be a little bit different than the previous couple of episodes so we just simply went and made changes to the database or submitted data to it uh because when it comes to actually grabbing data we need to actually grab the data and set equal to an array inside our code so we can actually do something with this data so we need to have the data put inside our PHP code so to speak so what I’m going to do is I’m going to go below my execute and I’m just going to go and create a variable called results and I want to say that I’m going to take my statement that we sent in and execute it and I want to point to a method called Fetch all because in this case I want to fetch all the results from the database there is also something just called Fetch for just one piece of data but in this case here we are potentially grabbing many comment from the database so this is going to be uh many results in our case so fetch all is the one that we’re going to be using parenthesis and semicolon and inside the parentheses we need to tell it how do we want to fetch this data now we did talk about arrays in the past because we did have a array episode in one of the previous ones and inside that episode we talked about indexed arrays and we also talked about associative arrays and when it comes to grabbing data from inside a database it is is much easier to handle the data as an associative array because essentially each array data is going to have a name associated to it so we can refer to the name in order to get the data and in this case when we grab database data the column names inside the database are going to be the name for each data so doing this as an associative array is a very easy and fun way for us to grab data from inside a database in order to know exactly what we’re referring to so what I’ll do is I’ll go inside and say I am using a PDO connection and I want to fetch this as an associative array so we’re going to say fetch ESO which is for associative so doing this here we can actually go down and actually delete this header statement because we’re not trying to get back to an index page or anything here uh we’re just basically going to say that we don’t you know we we have the data so now everything is done we don’t need to do anything else here I do think it’s also important to point out here that we do still have this header function down here since that if the user tries to access this search page without actually having searched I don’t see a reason for them to access this search the PHP page um so if they were to try and access this file without having actually searched for something there’s really no need for them to be in here so again just to summarize all the data that we just grabbed using the query from the database are now stored inside variable results as an array and each data can be referred to using a associative name so in this case if I want to grab um let’s go back inside our database here if I want to grab this particular comment down here from a certain user so let’s say I search for crossing and now I’m grabbing all the comments from Crossing if I want to grab this is a comment on a website then I just need to refer to commentor text because that is the column name and this is going to be what is assigned to our associative array as the name for this piece of data I think I may be confusing you more just by explaining this over and over again so let’s actually just go Ahad and do it CU that’s a lot easier for you to see um so what I’ll do is I’ll go down inside my body page and actually do something with this data because we grab the data at the top of our file so we can just go further down to file and just refer to variable results because it’s available inside this file here cuz we just created it uh so you can just go aead and go further down to file go in and say that maybe we want to create an H3 where we can say this is our search results go down below here open up the PHP tags so we’re going to open up and we’re also going to go and close it here and then we’re just simply going to do a simple if statement where we go in and check if we actually have some sort of data pulled down from the database because in some cases if I try to write in a username that doesn’t exist inside the database of course we’re not going to have any sort of comment from any sort of users because the user doesn’t exist uh the same thing goes if a user just didn’t make a comment then they’re not going to have any comments so we do need to have something default to show the user if there’s no comments to actually grab from inside the database the way we can do that is just by creating a simple if statement where I go in and say if right now we don’t have anything in inside this array that we just created so variable results so if Mt which is a built-in function inside PHP I can check for if variable results is currently empty so if there’s no data inside this array then we don’t have any sort of data and if that is the case then I just simply want to go in and I want to Echo out a piece of HTML which in this case here I did actually di a little bit inside my style sheet so I’m just going to go and create a div here I’m going to open it up I’m just going to copy this Echo two more times and I’m going to go and close the div down here and then in between here we’re not going to have a div we’re going to have a paragraph and we’re also going to go and close off this paragraph here to make sure that we close it and in between the paragraph I’m just going to say there were no results or something you know you can come up with any sort of message you want here there’s a little bit of freedom in these tutorials so you can just sort of say whatever you think makes sense in this case here so there were no res results um so if we don’t have any sort of results from our database quy then we just Echo this out uh if not and we did actually get a result I’m just going to go and copy this go down below write a else statement then I’m going to actually Echo out uh the user or at least all the comments from the user inside this page here now the way that is going to work is currently we don’t know if we have one comment from this user or we have many comments from the user you know we do have an array here um but we don’t know how many results that might be inside this array either way we do need to make sure that all the comments that we grabbed inside our associative array do get looped out inside the page because we need to Loop out the result so to speak I can actually do something just to show exactly what is going on here so you have a a small idea about what is going on if I were to do a Vore dump and actually go in and refer to my variable results uh before we do that though there is one more thing we need to do inside our little PHP code at the top here cuz I actually forgot about that this D method here we do want to delete otherwise we are basically terminating our entire script and stopping everything from running even if we do grab something from inside the database so do make sure you don’t have that die method up there otherwise it’s not going to work for you uh so we’re going to go back down and then we’re just going to make sure we save everything and going inside our website I can now go in and actually search for a user so let’s go and search for crossing or whatever you might have inside your database there if we were to do that you can see oh okay so we get a search result because we didn’t get our uh small message that we just created we did actually get a v dump here and basically you go in and see that we have a bunch of data we have a lot of data in here and this is actually what we call a multi-dimensional array because we have an array that has a bunch of arrays inside of them so each row is going to be a separate array inside this array that we just created and you can actually see at the very top up here does actually say that currently we have a array that has three other arrays inside of them so that is basically what this says up here uh which means that we have three different rows of data with commments from this particular user again this might confuse you even more than actually help you with anything but let’s go and go back inside our website here and instead of doing a v dump let’s actually go ahead and run a for each Loop because what we can do using a for each Loop which I do think we talked about before is how to Loop out an array so using this can actually Loop out all the multi-dimensional arrays inside this for each loop from inside variable results so what I can do is I can go in and say okay so we do have variable results here so that is the array that I want to grab and I want to have a placeholder that I can refer to inside this Loop here so we’re going to say as variable row so I’m going to grab my variable row and just copy it go inside the loop and then I’m going to say for each Loop when we Loop out one row of data from inside this array with all our data inside of it I want to make sure to Echo out a variable row and then I’m going to refer to a associative name so in this case I’m going to say I want to grab and we can actually go back inside our database here uh I want to grab the username and also the common text and the created ad so I can actually go back inside my code and say I want to grab the username then I’m going to copy this down to the next line and say I want to grab the commentor text and then I want to copy it down and say also want to grab the created uncore at and at this point here we can actually go ahead and test this out inside the browser but we do have two other things that we need to do before we can actually do so the first thing is we need to make sure it actually looks pretty so we need to style it in some sort of way uh the second thing we need to do is to make sure we don’t have any cross-side scripting going on because two episodes ago when we talked about inserting data from your website into the database we talked about the fact that you have to sanitize the data when you actually output data inside the browser to make sure there’s no cross-site scripting happening uh so we do need to make sure that since we’re outputting data right now we’re actually echoing it out inside the browser then we go in here and actually run a HTML special character function to make sure that we don’t have any sort of cross-side scripting happening uh so if a user were to Output some sort of JavaScript inside our database and now we’re echoing it out inside our code here we could actually have a potential issue here we actually allowed the user to Output JavaScript inside our website which is not a good thing uh so we need to make sure we use this HTML special characters whenever you want to Output data from a database inside a website or just any point when you want to have any sort of user data uh spit out inside your website so making sure to wrap everything in HTML special characters is very important or any of the other uh filter uncore input method or something like that that we have inside PHP in order to properly sanitize data now in this case here we’re just outputting string so HDML special characters is the proper one to use here so at this point here I would like to actually test this out inside the browser even though it doesn’t look that pretty yet when we actually output it so if I were to go inside my browser and type in a username that we don’t have inside the database you know because I want to test out the error message then you can see we get there were no results which is good cuz that is what we’re supposed to have but if I were to type in a us that I know we have inside the database for example cing and actually run a search then you can see we get get his entire all the comments that he made inside the database so you can see we get uh one comment up here then we get a second comment over here then we have the third comment over here but as you can see we have three different comments from this particular user here so we do have his comments uh showing inside the website that just not styled yet so that’s the next step we have to do so going back inside the code I will continue styling things here so I do need to make sure because I did actually do that inside my notes here that I wrap everything inside a section tag because my notes say I did that and I did style it you know depending on this so I have to do it otherwise my styling is not going to work so I’m just going to make sure I paste this in and then I’m going to go inside my for each Loop down here and I’m going to Echo out a div because I want to wrap this inside a div just like we did up here I’m also going to close the div right after and then I want to wrap my data inside an 84 and two paragraph tags so we actually have something you know style when it comes to the text as well uh so I’m going to say I want to Echo and I want to Echo out a84 and I’m also going to go ahead and concatenate here to make sure we concatenate everything then I want to go after and say I want to close off my H4 so I’m going to close off the H4 here I’m just going to scroll to the side here so you can see everything and then I’m going to copy paste and do a paragraph for the other two down here so I’m just going to change this to a paragraph paragraph and the same thing when it comes to closing off at the end here but changing it to a paragraph of course like so and I just want to point out here that there is another way to do this when it comes to HTML inside PHP which is not to have it echoed out inside a string uh but actually close off the PHP TX up here for example then you open it up down here if you want to do that and then you can actually just write HTML in between here and then Echo out the data in between the HTML by opening and closing the PHP tags so that is another way to do so but in this cases since we don’t have that much h going on I think it’s just easier to Echo it out so doing this here and going back inside the website just to test how everything looks like I’m going to go back here refresh and again if I were to search for someone that does not exist inside the database for example this random person here then you can see that we have there were no results and it’s been styled because I wrapped everything appropriately and if we were to go back and search for crossing now you can see that we get three different search results and because I styled it and made sure that everything was below each other and wrapped it inside a dip container to have a a white background color everything now looks a lot cleaner and we can also go back and search for another user so if I were to search for besser is cool which is another user that I have inside my database then you can see we get his comments inside his comment table and just like that you created a very basic search system using PHP so that is something you could actually use inside a website if you wanted to um so learning how to do this is a very good and important step to learning how to Output things using PHP when it comes to data uh in the next episode we’re going to talk about something called a session because a session is a way for us to store data inside our uh well inside our session inside our browser uh so we can actually store data from page to page without having to send it using a post or a get method so using sessions is something we use constantly when it comes to PHP in order for the website to remember things as you’re using the web page so this is something that is very cool to learn about so we’re going to talk about that in the next episode but for now this is how you select data and output it so I hope you enjoyed and I’ll see you guys in the next [Music] one today you’re going to learn about something called a session inside your website and a session is very important to know about since it is the way that your website remembers information across all the pages inside your website now we have talked about a post and the get method where we can send data from one page to another page but this is more for when it comes to submitting data from the user or uh submitting a lot of data inside the website that isn’t really permanent but it’s more temporary information that just needs to be sent from one page to another but when it comes to a session this is information that we want to store permanently inside the website or at least for a longer period of time inside the website uh when a user is currently using your website let’s say for example we want to create something like a login system in order to create a login system the website has to remember okay is this person logged in or is he not logged into the website and when you go inside your login form and you type in a username and a password and then you click login then if you typed everything in correctly and you were to log into the website then the website has to remember across all the pages that oh this user is logged in so everything needs to change inside the website so we use sessions in order to store information that has to be remembered per permanently inside our website in order for for example a loin system to work there’s one thing I want to show you before we get started on any sort of code inside our documents here which is to go inside my browser and open up this website that I just created which is completely empty there’s nothing going on in here uh you can actually see that I have nothing in here literally there’s no you know code inside the body tags I do have a second page by the way which is called example. PHP but that one is completely identical there’s nothing inside of it and this is just to kind of demonstrate that it remembers information across pages so I just created a second page called example. PHP uh so you can go and create that one as well if you want to but I do want to show you that if I were to go inside the browser here go inside my developer tool which is F12 on the keyboard or if you were to go inside the website and right click and then click inspect then you also open up that way uh if you were to go in here you can see we have this very typical developer tool that we’ve seen so many times before we have the HTML you have the CSS you can also see the JavaScript uh but if you were to go up here where it says storage and this tab may be in a different place if you’re using a different browser I’m using Firefox in this case here if I were to go in here you can see that we have something called cookies and inside of here you can see we do actually have a cookie that is related to Local Host because I right now have a PHP my admin turned on inside my browser so it it does have a cookie for PHP my admin now a cookie is information that is stored directly inside your browser locally inside your browser not inside the server and whenever you start a session inside a website you actually generate something called a session ID cookie which is going to pop up in here as soon as we start a session because now we’re telling the server that okay so there’s this user here who is trying to remember things about the website and the information is going to be stored inside our server so in order for the server to figure out which person you are CU there might be many different users accessing the same website uh the server has to place a session ID cookie on your browser to figure out which user you are and which session variables you need to have assigned to you so if I were to go back inside my editor I’m going to go to the top of my index page and I’m just going to go and open up and close my PHP tag so we can actually type some PHP in here and I’m just simply going to start a session by typing session underscore start parenthesis and semicolon and with this simple method here we now started up a session inside this page inside our website so right now we don’t have a session going on inside ex example so we could actually go in and copy paste this information paste it over here just to make sure we have a session started on both pages and then with this we’re now going to go back inside the website refresh it and when I refresh it and open up my editor you’ll notice that inside my cookies we now have a second session ID cookie which is called PHP session ID and this is actually the session that we just started inside our web page using the session uncore start so now the server knows okay so there’s a session going on inside this web page which means we need to put a session ID cookie inside the browser so we know which session data belongs to that particular user because like I said many users might be using this particular website here so for the server to pinpoint which user is which we need to have the session ID cookie if I were to go inside and delete this cuz you can actually do that and say delete uh PHP session ID Local Host then the server no longer knows who who you are and all the session data is probably going to get lost so uh this is not something you have to do because the browser actually purchased this so if we to close down the browser it’s going to delete all these session cookies so you don’t need to worry about you know them sticking in here because we do actually have some session security when it comes to sessions as well where people can go inside and hijack your session or something and that is something we need to talk about at some point uh for now we’re just going to talk about the basics of sessions and starting them up and how to delete them again and so on so with this here just know that as soon as you close down the browser this particular session that you have right here or this session ID cookie will get deleted and there is a reason for that that is because the timeout for this particular cookie here is set to a negative so therefore the next time you close down the browser uh you can always you know extend this session ID if you wanted to manually but let’s go back inside our editor and talk a bit about session data or session variables that we can create using the session super Global because we did actually talk about this one many episodes ago but we didn’t really talk about it extensively uh but we do actually have something called a session super Global so if I were to say dollar signore session brackets and then I can go inside the brackets say double quotes and give this some kind of name so I could for example call this one username so if I were to type username and set it equal to something I can for example say Crossing then currently I have a session data or session variable able that is equal to a string called Crossing which means that this information is going to get remembered on your server on any page that has this session uncore start started at the top of the page so what I’m going to do here is I’m going to say that I want to start this session and I want to go down inside my buddy tag and I want to start my PHP tags because I want to demonstrate something for you so we’re going to say we want to start the PHP tags and close it again and I just simply want to Echo out my session variable that I just created up here and pasted in down here so you can actually see that we can actually see this session variable now inside our page but I do also want to take this Echo go inside my example page and show you that we can actually see it inside this page as well so even though inside the second page we didn’t actually set the session variable at the top here we should still remember it so if we were to go inside my browser and say I want to refresh my index page you can see oh we get causing up here if I were to zoom in you can actually see it uh if I were to go to to my other page called example.php then you can see we still get Crossing because we echoed it out on the second page as well without even declaring it at the top because our session remembers oh okay so inside the index page he set this session variable so now we can Echo it out so in this sort of way we can store information inside our session that gets remembered across all the pages inside our website as long as we have this session start declared at the top of the page now I do want to demonstrate something else here here as well which is that if you have a bunch of data inside your session variables how can you unset them and delete the data again because that is also something you need to know about so if I were to type a method called onset and actually take my session variable so if we were to go down here and say we have a session variable called username then I want to paste it in here and unset it so if we were to do this go inside my website you can now see that oh okay so undefined array key username used cuz we don’t know what this variable is because now it’s been onset let’s actually go and go back to the front page because I actually think that makes a little bit more sense since we did set it here uh so if we were to go back inside the front page and set the session variable and then unset it again right afterwards go inside the website go back to the index page you can see it still gives us the same error message because oh okay so we we onset this session variable but let’s go back inside the code and say that what if I have more than just one session variable that I want to delete what if I want to purge all of them uh what I can actually do is I can run a method called session underscore unset parenthesis semicolon and if we were to do this one then it’s going to purge all the session data inside our session so we can’t see it inside our website so would to refresh the browser you can still see that we get this you know we can’t find the session variable so everything has been deleted still so this one here is for deleting all the session data and this one is for for deleting one session data and now we do also need to know how to stop a session from running inside our page so let’s say I have a session started here I can also go down to next line and say I want to run a session underscore destroy and if I were to run this one then we’re actually stopping the session from running again so let’s actually go ahead and go up here and delete this onset so right now we start a session we set a session variable and then I destroy the session inside the same page but now there’s a small thing that I want to show you here because if I were to save this and actually let’s go ahead and go back inside our example page here and just make sure that we only have our session uncore start at the top and also to make sure that we have the echo down here inside the body tag so with that in mind if we were to go inside the browser here this causing variable when I refresh the browser should not be available right CU it just said to purchase all the data so if I were to refresh the page oh okay so cosing is still in here so the reason we can see it in here is because because even though the session destroyed does actually Purge all the session data it doesn’t get purched inside the same page so it doesn’t happen or the the effect is not going to happen until I actually go to another page so if I were to go back inside my uh example page here then you can actually see that when I access this page that oh okay so this username session variable is not available because we did purchase on the previous page using session unor destroy so again if I were to go back inside my my my code editor here session unor destroy is going to purge all the data but you can’t see the effect until you access another page often you’ll also see people use the session uncore unset in combination so whenever you want to completely destroy a session and unset all the session variables this is how you would do it so now that we talked about our session uncore start and how to create a session variable and also how to unset data so I can actually write it in here again there we go so we talked about how to unset data inside our session very Ables and we also talked about how to destroy a session and again just to point it out here sessions are used in order to you know remember information across Pages for example login system or if you have a shopping cart inside your website and the user goes in and puts things in the cart then the website has to remember across all the pages what you put inside the shopping cart so there’s many different things you could use a session for to remember things and of course we do also have some security when it comes to sessions which I think we’ll talk about maybe in the next episode or maybe a little bit further ahead in this course here so having talked about this I hope you enjoyed and I’ll see you guys in the next [Music] video so in the last video we talked a bit about sessions and how we could create a session inside our website and in this video we’re going to talk a bit about session security which is going to be quite a it’s going to be one of the more complex episodes we having discour up until now but I will try to take it and explain it as simple as I can and just show you exactly what we need to do when it comes to basic security using sessions so the first thing we have to talk about is what exactly are we trying to defend ourselves from because we have talked about prepared statements and sanitation you know to defend against SQL injection and cross-site scripting um but what are we defending ourselves against in this video here what exactly I would try to prevent using session security uh something that is very important when it comes to having anything to do with the session is to make sure that other users on other computers are not able to steal our session data so whenever we create a session inside the website like we did in the last episode and we start creating these session variables that are going to store data inside the server then we want to make sure that the ID stored inside the server is only going to point to us who is using our computer so the session ID cookie inside our browser should only match up with the ID inside the server for for us so if another user out there were to hijack our session ID then they can actually go in and steal our session data which is not a good thing so we need to make sure we have some session ID security uh whenever it comes to handling sessions inside the website just to mention a couple of ways that people could potentially hijack your session could for example be using something called session ID sniffing where a user can go in and intercept unsecure trafficking going on inside your website and they basically hijack your session ID and then impersonate you as the user inside their computer and this is why it’s important that whenever you have a session running inside a website that you don’t have a HTTP connection but a https connection another method people use is also something called session ID prediction where basically they try to guess what kind of ID you have inside your computer so if you haven’t generated a strong session ID they can try to predict and guess whatever session ID you might have so it is important that we also go inside our code and generate a much stronger session ID to prevent this sort of thing from happening and then we also have another very popular one which is something called session fixation which is a type of attack where the user basically tries to make you use the cookie that they have on their computer so for example by sending you a malicious link to a website that they actually included the session ID for their computer in so in a situation where you might click on a link that they sent you through for example an email then you can actually go into a website using the session ID that they created so basically you’re impersonating them inside the website but you don’t know it and then of course we do also have cross-site scripting attacks where people try to inject JavaScript into your website to for example steal your cookies so there’s many different ways that people can hijack a session inside a website and we have to make sure we try to prevent as much as possible and just to mention some additional security things that you just kind of need to know whenever you have anything to do with sessions inside the website uh whenever you have anything to do with sessions it’s very important that you always validate and sanitize user data because that is always important to do so whenever the user submit some sort of data make sure you don’t have it be unsecure as you use it inside your website another thing you want to do is also make sure you don’t store any sort of sensitive information inside a session variable for example a user’s address or phone number or email or something like that uh because if a hack were to gain access to all the session data then all of a sudden they have access to very personal information which is not a good thing you do also want to make sure that whenever you have any sort of session data that you don’t need to use anymore that you go inside and you actually delete it because if you have old session data stored in there that isn’t usable anymore then there’s no need for a potential hacker to gain access to information that could have been prevented because you don’t need it anymore inside your website and with that said it is also kind of a thing whenever we have session security going on that the more security you have inside your website the more you’re going to inconvenience the user that is using your website because that kind of goes hand inand and you have to find a balance between how much do you want to inconvenience the user versus how secure should your website be if you want to have the maximum amount of security inside your website you should force the user to log in every single time they use your website but that would also mean that the user has to log in every time they use your website so all of a sudden we have this again security or convenience because you also don’t want to have users being scared away of your website so that’s just a very important thing for me to to just sort of point out there I do also want to mention here that some of the stuff that we’re going to be doing in this video will also be changeable inside the php.ini file inside your server so something that we haven’t talked about yet is that if I were to go inside my exam installation then I do actually have a PHP folder and inside that folder we have something called a php.ini file and this file has a bunch of settings inside of it that you can change in order to do some of the things that we can do in this video here but I do want to do everything using code in this video here just to make sure that everyone who is following can just sort of follow and just write the code down and you know that you don’t get scared cuz oh no we have to go inside a weird file inside our phsp installation how will I do this inside a live server and that kind of thing so I’m just going to go and show you how to do everything using code in this video here now the first thing we’re going to talk about is one of the settings that you do have inside the inii file that you can change using Code which is something called session use only cookies and this is something that goes in and make sure that any session ID can only passed using session cookies and not for example through the URL inside your website because that is one of the ways that people they do session fixation where they go in and try to make you click on a malicious link and they take you to a website and then they might have a session ID stor inside the URL of that link so this is one of the ways we can prevent that from happening so the way we can do that is go inside our website and what I’ll actually do here is I will not start creating code at the top of my index file I’ll actually create a new file inside this this uh root folder here so I’ll create a new file and I’m going to call this one config.php and this is going to be a file that I’m going to link at the top of my index page here so I’m going to say require uncore once and then I want to link to my config do PHP and any other page inside the website where we want to include this code we can just go ahead and require the file just like we did here so what I can do is I can go inside the config file and the first thing I’m going to do is open up my PHP Tags I’m not going to close it again though because this is going to be a pure PHP file and what I’m going to do is I’m going to set something called ini iore set parentheses and inside this one we can set a parameter which is going to be our session uh do use underscore only underscore cookies and if I were to set this one I can also set a value which is going to be one and this is going to mean that we’re setting this one equal to true because one is true and zero is false so in this sorder of way we can go inside that inii file and actually change some of the parameters using Code inside our phsp code uh so what I’m going to do here is I’m going to duplicate this because we do actually have a second one that we also want to make sure we set in here this one is going to be called use strict mode so we’re going to say session. use strict uncore mode and what this setting is going to do is a couple of things or quite a few things actually one of them being that we make sure that the website only uses a session ID that has actually been created by our server inside the website it is also going to go in and make our session ID a little bit more complex when they actually get created uh so in that sort of sense it makes it a little bit more difficult for people to go in and try to guess your session ID inside your cookie so there’s a couple of really good things that this particular one does and this is actually a mandatory thing to have whenever you have anything to do with sessions inside your website so you want to make sure that this line of code is inside your website anytime you have anything to do with sessions the next thing we’re going to do is we’re going to create some cookie parameters inside our code so whenever we start a session inside our website and the cookie is created want to make sure that we do have some parameters set for that particular cookie to make it more secure so what I can do is I can create a function here called session unor setor cookie underscore params and if we want to create this one we can go inside of here we can actually create a bunch of different parameters so I could potentially create a array here and inside this array we can define a bunch of parameters and the first one we’re going to set is something called lifetime now a lifetime is basically going to go inside your cookie and say that okay so after a certain amount of time has passed inside the website we want to make sure this cookie is going to get destroyed and the reason this is important is because we don’t want to have the same cookie running inside the website for too long because if that were to happen it is going to increase the chances of someone catching that cookie and stealing it and if they have that cookie we do also want to make sure that after a certain amount of time they can’t use that cookie anymore so what we want to do in here is we want to set a parameter called Lifetime and I want to point to a new value which is going to be1 1800 which is going to be 30 minutes in seconds so in this sort of way we now created a new lifetime for our cookies so they actually get destroyed after a certain amount of time uh the next thing we’re going to do is we’re going to set something called a domain so whenever we want to go inside and create a cookie it will only work inside a particular domain so in this case here we’re going to point to Local Host because right now we have exam running which is a local host server so this is going to be the domain that we have to point to of course if you had to put this online and you had another website you would call it something like example uh.com for example if it has to work for that particular website like I said in our case here we’re using Local Host the next thing we’re going to create is going to be something called a path and this is going to to point to a sort of path inside your domain here so in our case here we could actually say that it just has to work inside any path inside our website so what I can do is I can say that we want to set it equal to forward slash which is going to be any sort of subdirectory or sub Pages inside our website that is currently running uh inside this particular domain up here our next parameter is going to be something called secure which is going to make sure that we only run this cookie inside acq website so only using a http s connection and not a HTTP connection so I’m going to set this one equal to true then I’m going to say I want to add another one which is going to be H TTP only so we’re going to say h TTP only and we want to set this one equal to true as well and this basically just goes inside our website and restricts any sort of script access from our client which means us inside the browser so now that we have these we can actually go below here and actually start our session so we’re going to say session start just like we learned in the previous episode so all this information up here has to be set before you start the session that is very important to do uh because these has to be set before we actually have a session created but now there’s a couple more things we have to do whenever we create a session and I did actually mentioned one of them which was we need to make sure that the standard session ID created by this particular function here is going to get even better because right now when we create a session ID using session unor start it is going to be a very basic not really a secure session ID so we want to regenerate it into a stronger version which we do actually have a PHP function that can do uh so we have a function which is called session uncore regenerate ID and this particular one if you were to set this one to True is going to just generate a new ID for this particular current session ID that we have so it’s not going to create a new one it is actually going to regenerate the current session ID we have and make make it into a better version however even though we did use this function in here underneath the session story in order to regenerate the ID it is also a very good idea to do this automatically after a certain amount of time has passed inside the website so if a attacker were to gain access to a session ID then after a certain amount of time that session ID no longer works for them so we want to make sure we regenerate this periodically inside our website and I do actually have a blocker code to do that so I’m just going to go and copy paste it in and then I’ll go ah and explain what exactly it does so underneath my session undor start I went ahead and created this blocker code here I’m just going to talk a bit about what exactly it does uh so inside this block of code I have a if and an else statement and inside the if statement I’m basically just checking if we right now have a session variable created using the iset function here inside my session called lastore regeneration if I do not have it created it means that this is the first time I’m running this page inside the website and it’s the first time I’m actually starting up my session and if that’s the case I do actually want to make my session ID Stronger by regenerating it and I do also want to make sure actually create this session variable that we’re checking for up here so the first time we’re running this if statement it will actually go in and create this session variable so anytime other than this in the future it is going to run this El statement instead I did also give this one a value which is going to be equal to the current time that we have inside the server here and this is going to be important for us to actually check if a certain amount of of time has actually passed since we last time actually regenerated our session ID so the current time for us actually regenerating the session ID is going to be equal to our session called last regeneration and inside this L statement I created a variable called interval which is going to be set equal to the time that I want to pass until we have to regenerate our session ID again uh so we want to have this in seconds which means that in 1 minute we have 60 seconds and then I’m basically just multiplying it with the number of minutes that I want to pass until we actually regenerate this session ID so in this case 30 minutes so if you want this to be 10 minutes then you can write 10 if you want this to be 30 then we’re going to write 30 and then afterwards I went ahead and created a if condition which takes the current time and minuses that with the time inside our session variable which is going to give us a number of seconds and then I check those seconds if they’re greater than or equal to our interval and if it’s more than 30 minutes then I’m going to regenerate our session ID and I’m also going to go and reset my last regeneration session variable to be the current time that I now regenerated the session ID inside my website so we’re basically just regenerating the ID inside our session every 30 minutes that is what this code does and with this said you now know some of the basics when it comes to session security inside your website um I do want to point out here that there is more we could talk about when it comes to session security for example creating a new session ID so not generating a new session ID but actually creating one using for example a function called session unor create ID and then you could take this ID and combine it with your user ID from inside the database whenever you create a login system in order to create a unique ID for a login session so um there’s many different things we could talk about for now I think this is good when it comes to beginning and just sort of starting up with session security and just to mention this again for people did miss it at the beginning we can just take this file here that we just created together and just go inside one of the pages inside our website and when we want to create a session inside one of these Pages we just sort of link to this file and then we have all of this you know session security going on inside those pages I do also want to mention at the end here that if you are a channel member then you do of course also have access to all my personal notes here so if you want to have all my personal notes for for example this Paton here with all the comments inside of them then you do have access to these files if you are a channel member and you can find the link for that in the description so with that said I hope you enjoyed this lesson and I’ll see you guys in the next one [Music] so now we reached the point where we have to talk a bit about security when it comes to inserting data into a database because we have talked about creating data inside a database and selecting data and sessions and that kind of thing but we haven’t talked about hashing yet which is something that is very important whenever you want to insert data that is sensitive in inside a database so right now just to demonstrate something if I were to go inside my database that we have created in the past couple of episodes where we created a users table and a comments table if I were to go inside my users table here you’ll see that right now inside our password column we actually don’t have any sort of security going on in terms of Hing uh so right now if I were to you know break into a database like this one right here I could actually see everything in terms of what exactly these passwords are so we can see this user here has a password of 1 2 3 4 this one has a Denny one 2 3 and 1 2 3 1 2 3 4 um but the thing about inserting sensitive data inside a databas is that we’re not supposed to be able to tell what exactly is in there so in order to create another layer of security we do something called hashing which is going to turn our password into a hashed string which is going to be this very long and confusing letters so we can’t really tell what exactly it’s supposed to be it’s just going to be jerish basically so going back inside my text editor here you can see that I have a bunch of files just going and ignore those for now because these are for a example a little bit later on but for now all I have that you need to worry about is a file called hash password. in.php this is a file that I put inside my includes folder inside my root folder just because this is going to be a file that has pure PHP inside of it and we have talked about why I name my files in this sort of way many times in past episode so you’re more than welcome to go back and and just take a look at that if you want to but the important thing about this episode here is just talking a bit about what exactly hashing is so going inside this file here which is completely empty I’m going to open up my phsp tags and I’m not going to close it off again because this is going to be a pure PHP file and we’re going to start by talking a bit about how we can hash and what exactly hashing is now hashing is whenever we perform a oneway hashing algorithm on a plain piece of text for example a password and then we basically convert it into a fixed length string that you can’t really look at and tell what exactly is this supposed to be so it is going to be something that even if a hacker would gain access to your database data then they still can’t see what the data is supposed to be so depending on what kind of data we’re feeding the hashing algorithm it is going to convert it into a different thing so it is something that is going to be different depending on what exactly you’re going to feed to it and it is also important to mention here that a hasing algorithm is designed to be irreversible and expensive to do um so you can go in and make a hassing algorithm more complex if you want to we do also have something called a salt which is a vocabulary word that you may hear from time to time whenever we talk about hashing essentially a salt is a random string of text that is going to be included inside the data that you provide the hashing algorithm so it’s going to mix the salt together with the text that you provided it and then it’s going to Hash it afterward to create a more unique and even harder to crack hashing algorithm to make it even stronger it is important want to point out that we do have many different hashing algorithms out there and some of them are considered to be outdated whenever it comes to for example password hashing uh you wouldn’t use a shot 256 or md5 Hing algorithm in order to do those uh whenever you insert those into a database so there are you know different ways of hashing things depending on what you’re trying to do when it comes to specifically just general purpose hashing when we’re not talking about a password to be inserted inside a database uh we can for example go inside our code like we have have here and let’s say I have a variable which is going to be whatever the user gave us so let’s say there’s a form and the User submitted something to us uh then I could go inside and say I want to create a value called sensitive data just to have something here and I could set that equal to some kind of value so I could say for example Crossing as my username the next thing we would need to do is create something called a salt and a pepper which sounds really funny but just to kind of show what exactly those are um I can actually go and create a variable here I’m going to call this one salt and then I’m going to set it equal to a random string that we’re going to generate based off some functions that we have inside PHP so what I could do here is I could say we have something called bin to hex parenthesis and then inside this one I’m going to generate a random underscore bytes and then we just basically feed this one how many bytes you want to randomly generate inside this function here so we could for example say 16 and by doing this we’re basically just going in and saying want to generate 16 bytes of data data and then we want to convert it to hexad decimals in order to actually have something that we can actually actively use inside our code so heximal representation as it says inside the notes here um so basically just generating a random string so if we were to write some notes Here we could say Generate random salt next we’re going to go and create something called a pepper so I’m going to create a variable and call this one pepper and I’m going to set this one equal to a random string of characters that I decide what is going to be so so this is not going to be random characters this is going to be a keyword that I’m going to use to fuse together with this hash in here uh so I could for example say a secret pepper string so now we have something called a salt and we have something called a pepper and we can fuse these together in order to make our Hash a bit more secure so what I’m then going to do is I’m going to go below here and I’m going to create a variable called Data to hash and essentially we’re just going in and we’ll combine in these three pieces of data up here so we have the sensitive data that the user gave us inside whatever input we have inside the website uh we do also have a piece of data called a salt and then we also do have our pepper and then basically we just go below here and actually run a hashing function that we have inside PHP called hash so what I can do is I can say we have a variable called hash and I’m going to set this one equal to a hash function and inside this one we’re just going to feed it what kind of hashing algorithm we want to use and then the next piece piece of data is going to be what exactly we’re trying to Hash in here so in this case I could say want to use a shout 256 hashing algorithm and then I want to feed it data to hash and if we were to go inside my website here and actually try and Echo this out we can actually Echo this out after each other just to kind of see the effect of what exactly we’re doing here so if I were to Echo out a break just so we have everything on a new line and actually Echo out the hash that we have here then I’m going to copy this line of code and go right behind where we actually combine all this data here and I’m just going to go ahead and Echo out my salt as well so we can see exactly what is going on in here so if I were to do this and go inside my website go inside my includes folder and say I want to access my hash password. in.php file then you can see we get these two here so the first one up here is going to be the random ass salt that we generated at the beginning of the code and the second one down here is going to be the overall hash from combining our salt with the data from the user and our pepper string and as you can see this doesn’t make any sort of sense so even even though everything is combined inside this hash in here even the readable data that we included such as Crossing and a secret pepper string we can’t see anything about what this is supposed to be and at this point he would actually take the salt and the hash and store that inside either a database or inside a file storage system or someplace that is actually secure where people can’t gain access to it and you would actually go and take this salt and has and use that together with new data the user might submit in order to check if it matches up with the old data they subm it up here so let’s say somewhere else inside the website I want to go in and actually first of all grab the data from inside our database so we have the salt and the has stored in this case here we don’t actually have the salt and has stored inside a database and we would technically have to run a query in order to go inside the database and grab those data uh but for now let’s just go ahead and grab the ones inside the code here since this is more or less a example so let’s say I would grab the all up here and the hash that we have down here I would also need to go ahead and recreate the pepper string inside my code here because that is a unique string that I have created inside my code and then we would of course also need to have the data that the User submitted again so let’s say a User submitted this piece of data once more we’re going to go ahead and put it up here so with all this we would now have to combine everything again just like we did before inside our previous script up here so if we were to grab this lineer code where we combined everything and then I would need to take the salt that we just grab from inside our database and replace it with the salt that we have down here and with all these combined we can now run the has algorithm again just to sort of check if it is the same as the previous one so I’m going to copy this line of code up here and I’m going to paste it in we could also go ahead and rename this variable here to something like verification hash just so we know exactly what kind of hash this is so right now we’re trying to verify that the data submitted up here is the same as the previous data so we’re hashing the new data in order to compare it with the old data that we have inside our database so if I go below here and run a if condition in order to compare the these two pieces of hash data that we have uh so the first one is going to be the stored hash from inside the database so I’m going to copy this one put it inside the if condition and check if it is the same as our verification has down here and if it is then we can actually go inside and say we want to Echo something out so we could say something like the data are the same and then I can create a else statement just to Echo something out in case these are not the same so we could say something like the data are not the same so we just Echo that out inside our L statements just to get an idea about what exactly we’re getting in here so with this saved we can actually go back inside the website and refresh it and what we should get is either the data are the same or the data are not the same in this case here since we have cing here and we also have cing up here then the data should be the same as so going inside the website here if I were to refresh it you can see we get the data are the same because they are the same if we want to go back inside my code here and go up and change the value of the new data that was submitted so let’s say a user is typing something in let’s say cosing two and I were to Hash that and you know do everything in terms of the salting and the pepper we hash it and then we want to check if this data is the same as the previous one up here if we were to go inside the website you can see we get the data are not the same because they are not the same because you know the data submitted by the user is something different and it is important to point out here that we’re not deashing anything inside the code we are actually taking two different hashes and checking if these two strings are the same so if we to go inside and change my sensitive data back to Crossing just to give you a example here let’s go ahead and Echo out not the data are the same but let’s actually go ahead and Echo out our actual values here so I’m just going to go and create a break and then Echo out our stored hash and then I’m going to go below here and add another break just so we can see exactly what is going on and then I’m going to Echo out our verification hash then you can see inside our browser if I were to go inside and refresh it that these two strings are the exact same strings because we has the same data in the same way and then we are comparing the two so basically we are getting a true or false statement when we go inside and actually check for these two data being the same data and this is how you can do General hashing inside your website and it is important to point out here that this is for General hashing when it comes to password hasing for a database whenever a user wants to submit a password when they sign up inside a website then we do actually have a different method for doing so and this is something that is much more simple than what we just did here just to point it out this is much more complex but it is important to mention that a hassin method that looks something like this is good for when you for example want to hide certain sensitive data that isn’t specifically password specific this could for example be a name or a email address or you know financial data or something like that this is what you would for example do if you want to just has something that isn’t a password so now let’s go and talk about about how to generate a h password using phsp so if I were to go inside my code here and just delete everything I’ve just created uh for you it might be a good idea to take notes of these and maybe put that in a document on the side of something so you have these saved uh but what we’re going to do here is we’re going to actually do a hash function that is built directly inside PHP in order to Hash a password now when it comes to hashing a password we have a function called password unor has which is going to go in and actually run a in algorithm and a salt that is going to automatically do all of this for us in order to hash everything uh together to a unreadable format so we don’t have to add a salt manually or do a Pepper or something like that this is going to go in and do much of this automatically so in this case here we might say we have a user that submits some sort of password so we have a variable up here called PWD for password which in general is going to be equal to a post method you know from a form where a user submits something to you but now case here since we’re just doing an example I’m just going to go ahe and write cing because I just want to you know just set it equal to some sort of string in here so what I can do is I can take this password and put it inside my password unor has down here and then I can tell it what kind of hashing method do I want to use in order to Hash this password now in general we have two common hashing methods or hashing algorithms in order to Hash our passwords we have something called password uncore default which looks like this so so if we were to say password uncore default which is going to get automatically updated in the future whenever something new comes out inside PHP so this is something that the developers of PHP will actually come out and update as things change in the future so this is not something you have to worry about when it comes to any sort of changes uh but we do also have something called password bcrypt now password uncore bcrypt is right now actually being used inside password default so this is the one that will be used so does really matter if you’re using this one if you’re using password uncore default uh but just know that in the future if something were to change then the password uncore default can go in and change something uh because something has changed but in general right now whenever it comes to password hashing it is recommended to use BCP so this is the one we’re going to be using here and what you can add in here as another parameter is something called a cost factor which is in general how difficult it’s going to be to uh do this hashing uh algorithm here so if you have a hacker that is trying to Brute Force the way inside website by submitting different passwords again and again inside your input field then this is going to slow that process down and make it much more difficult and take much longer in order to actually try to break your hashing algorithm so this is something that is recommended to do and this is also a point where we have to talk a bit about convenience when it comes to users because the higher this number is going to be the more inconvenient it’s going to be for the user because it’s going to take longer whenever they have to log inside the website the general recommendation here is to use a number between 10 and 12 uh but this has to be submitted as an array otherwise we are going to get a error message so if I were to type 12 in here you can see oh it is expecting a array so if we’re to go above here I can go in and create an array I’m going to call this one options and I’m going to set this one equal to an array and inside of here we’re going to add a parameter called cost and I’m going to point to a value so this could be for example 12 or 10 depending on how you want to strengthen the hashing that you have running here uh so I’m going to write 12 and then I’m going to include my options inside as the3d parameter and then you can see we have this uh function here I do also want to take this hash password and set equal to a variable so we can say hashed password and this would actually be the password that we put inside the database when the user is trying to sign up inside the website so let’s actually go and change that up inside the naming up here so we can say this is the password on sign up and we’re going to change that inside our hash down here as well so this would actually be what we have in inside our database so now the next question is what do we do when want to log into a website because now the user is going back inside the website and they type in the username and the password inside the input fields for the login system and we would actually have to take that password and hash it again and compare it together with the password inside our database so what I would have to do down here is create another variable for the new password the user submit in when they try to log into the website and what I’ll do is I’ll go below here and run a password on _ verify which is going to go in and compare the new password that we submitted when we Tred to log into the website together with the old password that is hased inside the database so if were to take my password here put it inside as parameter number one and then take the password up here which is the hash version not the one that the User submitted on sign up because we don’t actually have that stored inside the database we have the hash version inside the database so I’m going to compare with that one and this would actually go ahead and return as a true or false statement and basically just tell are these two the same so if they are the same it’s going to return as true and if it’s not the same then it’s going to return as false so what I can do is I can run a if condition down here where we basically just go in and say we want to check for this particular function here so I’m just going to delete this line of code and move it inside our condition so if right now they are the same I’m going to Echo out they are the same but if they’re not the same then I’m going to Echo out they are not the same so in this sort of way we can very easily just go in and hash a password and then recover it from inside the database and compare that with the new password submitted when the user tries to lock into your website so if I were to go inside my website here and refresh the browser you can see we get they are the same if I were to go back inside my code and change up the password I used when I tried to log into the website so now it’s the wrong password I can go back inside the website here refresh and then you can see we get they are not the same and you can actually see there is a difference when I click refresh there’s actually this short half a second going on before we actually get the update inside the browser if I were to go inside here and change the cost into something like 30 and go back inside my website here and refresh you can see oh still processing still trying you can see it’s it’s moving up here so you can see it’s it’s thinking right now um so as you can see we are strengthening uh the hassing process so imagine you had a hacker that were trying to Brute Force the way in by typing one password after the other inside the website that you have uh then it’s going to take forever whenever they try to do this if you have a cost Factor inside your hessing algorithm now this is taken quite a long time so I’m just going to go and stop it here uh and just change this back to 12 so now your question might be so taking the signup system that we created in that episode number 22 inside this course here how can we take this and implement this inside our signup system because what I have here is a bunch of other files that I did tell you to ignore at the beginning of this l here these are actually the files that I had for my lesson 22 so we have the form Handler that actually takes the data from our index page when the user tries to sign up then we do also have our database Connection in here and then we have our front page that just basically has a sign up form again if you don’t have all of this you can go back to episode number 22 and just recreate all of this with me but what we can basically do is we can actually go inside our form Handler and just include this hashing in between what we’re doing inside this form Handler here so when I go down to where we actually insert some data I want to make sure that I’m not actually inserting the actual password submitted by the user so as you can see we grabb the password after a post method is being used and we’re just taking that password and directly inserting it inside our database which is not a good thing so what I want to make sure I do right down here before we actually bind the data is to make sure we run a hashing algorithm so going back inside my hash password. in.php I can just simply grab my options and my has password copy that go back inside my form Handler and paste that in so now what I’m going to do is I’m going to take the password from up here which was submitted by the user on sign up and replace that with my password sign up down here and then lastly we just take the has password and use that as our binding parameter down here when we actually want to insert the data inside our database so I’m going to replace my password with my H password down here and that is all we have to do so now if I were to go inside my website here and go back inside my index page refresh everything to make sure everything is good go inside my username say I want to sign up as Danny Crossing and I want to create a password in this case I could just say one two three then I’m going to include a email which is just going to be Crossing at gmail.com which is not a real email but just to have something in here if you were to click sign up and go back inside my database you’ll now notice that I have a new user but something is going to be a little bit different instead of having this very obvious password that I can just see with with my eyes inside the database we now have this hash that is going to be in here instead and that is what you want to do whenever you have any sort of sensitive data that you want to store inside for example a database because now if a hacker were to actually gain access to my database data then they don’t know what this data is so with all this here we now talked about just general hashing we talked about how to Hash a password for database and this is basically all I want to talk about in this video here it was quite extensive it is quite complex compared to previous episodes inside this course here but I hope this is something that makes sense to anyone watching this video here so with that said I hope you enjoyed this video and I’ll see you guys next [Music] time today we’re going to do something a little bit different we are going to implement everything we’ve learned up until now in these past many episodes to build a login system so we will actually have a PHP application that can do something inside a website and I do want to point out this is a very long video and I will have chapters in the description so you can actually skip ahead if you want to but just to point out this is going to be a long video but it’s also going to be very worthwhile so if you do actually go through this video you will learn many things so this is going to be a very very good lesson for you to just sort of write notes for and you know just have next to you as kind of like a cheat sheet for something you want to build in the future it is okay to be confused just rewatch certain parts of the video and make sure to write those notes that I was talking about so you will get to a point watching this video where now you know a lot when it comes to PHP I do also want to point out here that there is a tendency for long videos like this for people to get errors as they are following the video and I just want to point out that 99% of the time when people write hey Daniel I copied your code exactly and I’m getting an error message this code is not working 99% of the time it is because of a typo it is because you don’t have the same databases I do so you know some of the columns inside your code has to be changed when it comes to the names and that kind of thing you misplace the parentheses you know any kind of syntax error is 99% of the time going to be the cause even though you copied my code exactly so I just want to point out here look at the error message inside your website and then pinpoint where that is inside your code because it will tell you the line that the error is on and if you’re just completely in doubt and you don’t know anything about where to find that error inside your code you’re more than welcome to share it inside the comments so people can help you out I do also want to point out that we will learn a lot of new things in this episode here so we will for example learn how to combine our user ID from the database with our session ID to make it better for certain things uh we’re also going to talk about error handling which is when you go inside your code and you actually check for errors before you actually run the code because a lot of times you need to run error handlist in order to figure out if something is wrong this could for example be if the user didn’t fill in all the fields inside the form and then they submitted it so you have to check for that and then say hey you forgot something and then you go back to the form to tell them to fill in everything uh speaking about that we’re also going to learn how to write error messages inside our form so if someone doesn’t fill in all the inputs then we’re going to write an error message saying hey you forgot to fill in all the input or if the User submitted a username when they tried to sign up inside the website that already exists inside the database because you can’t have the same usernames then we also want to create an error message so we have to learn how to create error messages and to check for these things using error handlers inside our code to make this into a you know somewhat decent application I do also want to point out that we’re going to do something a little bit weird in this episode here because we’re actually going to organize our code in a MVC pattern which is something that usually don’t talk about until you start talking about object-oriented phsp which is when you start talking about classes and objects and that kind of thing uh but just to kind of get you into the mindset of a MVC pattern early on before we actually get into classes and objects it is a very good idea I think to just kind of touch upon it and teach you the concepts behind it so you’re not completely confused once we actually have to start talking about classes and that kind of thing so learning about the NBC pattern is just a really good idea and I think this is a good opportunity to just sort of get you into the mindset of how to think in an MVC pattern the reason that the MVC pattern is a really good thing for you to learn about is because it is going to allow you to organize your code in a much more scalable way so that once you build much bigger PHP applications then it is something that is going to be much more organized and better to look at because it’s not going to get all you know jumped together and because right now we’re creating what is called procedural PHP which means that when we have someplace inside our website where we need something specific to happen using PHP then we create the PHP code in that place which means that if I have another page inside my website somewhere where I need the same PHP code then I have to duplicate the code put it inside that page too and then you know all of a sudden we have this duplicates of code that is unorganized and you know there’s no need for it to be duplicated so an MVC pattern is a very good thing to learn about okay um so talking about that let’s actually go ahead and get started on this login system we will talk about all the different security things that we have talked about throughout these lessons here of course there is some security that we haven’t talked about but since we haven’t talked about it it’s not going to get implemented in this video here it’s a way for me to say that this is a good start for a login system then you can always work on it later on when you start learning new things so right now inside my website you can see that I have a index page I do have a main.css and a reset. CSS these are just my Styles sheets so if I want my website to look a certain way then I can can Implement a style sheet to do that because this is basic HTML and CSS and this is something you should also know by now uh so we shouldn’t talk about sty teet because it’s not PHP so with that I do want to show how my website actually looks like right now so if we were to go inside my page here you can actually see that we have a login system and we also have a signup system so we do have two forms that basically can go in you can type your username and password to log in or you can type in your username password email to sign up inside the website so just something very basic in here and of course the way I created that is simply by going inside my index page and I went down inside my body tag created our login form and I created a signup form and these are just to point it out very similar to each other so one of them has an input that is called username and it has a placeholder as username so the person knows what to type in here and we do also have a password input and the same thing goes for the the signup form down here we do also have a username we have a password but we also have a email so we actually use an email to sign up inside the website uh for the database I do have a file in here that you don’t need to have called db. SQL this is basically just my SQL code in order to create a table inside my database called users so right now we have an ID username password email and a Tim stamp for when the user signed up inside the website again if you followed my previous lessons you should right now have a database with this exact users table so this is not something you should need need to put inside your database but just to show you if I were to go inside my database here I do actually have my first database in here it is the name of my database and I do have a users table go ahead and ignore the comments table since that has nothing to do with this episode here uh but inside my users table you can see that I have a couple of different users already uh these are from previous lessons inside this course so there’s no need for me to have them in here uh so let’s just go and delete these users we can delete them one at a time by clicking delete or you can take them off here and say delete and now we don’t have any users left inside my users table the first thing we’re going to create inside our login system is going to be a connection to our database since we need to connect to our database in order to actually do something with the database because when it comes to a login system uh we need to be able to store the users information somewhere so the username the password the email that has to be stored inside a database so we need to connect to it so I’m going to go inside my root folder I’m going to create a new folder I’m going to call this one includes and I’m just simply going to put every single pure PHP file inside my includes folder so any sort of PHP that isn’t a direct page inside my website but just has some PHP code that needs to run a script inside of it that is going to go inside this folder here uh so our database file is one of those files so we’re going to go ahead and right click on includes we’re going to go in here and say want to create a new file and I’m going to call this one db. in.php for database Handler inside this file we’re going to open up our PHP code and I want to make sure that we go in and first of all create all our parameters we’re going to create four variables and each of these variables are going to be equal to a string of characters in our case here we’re going to have a host name which is going to be a local host if you’re using XA which I am right now you’re also going to have the database name which is the name of your database which might be different from mine but in my case I call mine my first database and then you need to have a database username and a database password now if you don’t know what your database username password are then you can of course just go inside your database and change these I do have a tutorial on that inside this course here which is a bit further back but we do need to have these parameters here in order to actually quy our database so the next thing we need to have is a TR catch Block in order to actually try to connect to our database so we’re going to run a TR catch block which means that we right now try a bunch of code and if it fails then we want to throw an exception down here now inside the catch I’m going to say that I want to throw a PDO exception so we’re going to say PDO exception you make sure you spell that correctly and then inside of here we’re going to create a placeholder called variable e for exception now we’re just going to go and create the error Miss straight away so we’re going to create a die function which basically just terminates this script if something goes wrong in here and we can actually generate a error message inside this die function so we can for example say connection failed connection space failed colon space and then we can add a message so we can say we want to add our variable e and we want to point to a method called get message and in this simple way here we now have a way for our error message to get displayed if we get some sort of connection error so what I can do now is I can go inside this try block here and I can actually try and connect to my database or at least create a variable that is going to contain a object which is going to be a connection object to our database so what we can do is we can create a variable call this on PDO I’m going to set it equal to a new PDO object and again we haven’t talked about object oriented PHP yet which is okay since that is a little bit further ahead in this course here uh but this is going to be a new PDO object based off a a connection class that is going to allow for us to connect to the database so going inside this PDO object here we can actually give it some parameters so the first one is going to be uh what kind of database are we trying to connect to so in this case it is going to be a MySQL and again just to point it out here some people do keep pointing out even though I keep mentioning it that MySQL databases are not outdated but PHP MySQL functions are outdated okay there’s a big difference between the two uh so MySQL databases are not outdated okay so moving on we’re going to go and tell it what kind of host we’re trying to connect to here and we do actually have our host up here so I can just go and copy my host and paste it down here now something we haven’t talked about that many times in this course here is the fact that when we do this we usually concatenate so you know we do something like this like we just it down here uh but it is actually possible to take a variable and just copy it directly inside the string and because PHP have you know nowadays know how to just look at this and say oh that’s a variable then we can actually do that so afterwards I’m going to add a semicolon and then we’re going to go and add our database name which is also going to be equal to our variable up here which is called database name and then after here we can actually go ahead and say we want to add a comma since now we have to add the last parameter which is going to be the username and also the password so we can say username comma and password so can actually paste that in down here now things are disappearing a bit off screen here so I’m just going to go and wrap everything so you can see everything inside my code I’m going to add one last thing below here which is going to be a couple of attributes for our p connection so we’re going to say we have this PDO connection I’m going to point to a method which is called set attributes and then I’m going to go ahead and add some parameters inside this method here now the first parameters is going to be to set our PDO error mode to exception so it actually works properly inside our catch block down here so inside the parameter I’m going to say PD colon colon a tore e r r m o d e for error mode and then I’m going to set a second parameter which is going to be that we want to set it to an exception so we can say PDO e r r m o d eore score exception and this is basically all we need in order to have a connection going so with this file we can now move on to the next file which is going to be our config session. in the PHP this is a file that is going to allow for us to configure our session so we have different things that can help us make it more secure to run a session inside the website so a hacker for example if they were to gain access to a session ID then we update the ID every 30 minutes to make sure that you know people have less time to do any sort of damage it with our session ID so there’s many different things we can do in here to make our session a little bit more secure uh the first thing I want to do here is of course make a new file in St my includes folder which is going to be a config undor session. in.php so inside this file we’re going to set a couple of things and I’m just going to go and copy paste for my notes here since that is a little bit easier at least for me since I’m teaching this and I have a lot that we need to go through um what I’m going to do is I’m going to open up my PHP Tex first and then I’m going to include two lines of code which is going to go inside our inii file inside our PHP folder inside our server and change a couple of inii settings so right now we are setting our use only cookies and I use strict mode to true in order to make this a lot more secure when it comes to handling sessions this is something that is mandatory so anytime you do anything with sessions make sure that you either change these inside the PHP speed. ini file or you change these using Code like we just did here now the second thing we’re going to do is change our cookie parameters in order to make this even more secure inside our website so I’m just going to paste in a blocker code here essentially this is a function called session unor setor cookie uncore parameters or params which is going to accept an array inside of the parameters that allow for me to change things like the lifetime of the cookie we can change the domain this cookie should work on any sort of subpaths inside this domain here that it should work on in this case I’m saying it should work on any sort of path inside this domain here uh we can also set secure to True which is going to allow for us to only use this cookie inside a secure connection so an https connection and we’re also setting HTTP only to true to avoid the user being able to change anything about this cookie using a script for example JavaScript inside our website so there’s a couple of things we need to set using this function here in order to make things a lot more secure when it comes to a session again we did talk about this a few episodes ago so if you missed that one you’re wouldn’t welcome to go back a couple of episodes to our session security video um we do need to add in one more thing which is going to be a uh if condition that is going to run a update every 30 minutes which will go in and take our cookie and regenerate the ID for that cookie and this is something that helps us prevent attackers from Gaining access to the cookie and then using that cookie for more than at least you know maximum 30 minutes so what I’m going to do here is I’m going to create a if condition which is going to go in and check if a certain session variable exists inside the website because if it does not exist then we need to create it in order to check when we last updated our session cookie so what we can do here is I can go inside this if condition and let’s go and wait with the um condition parameter for now because that just confuses people uh so inside the actual brackets here what I’ll do is I’ll add in a couple lines of code the first one is going to be where we actually go go in and grabb our session and run a function called session uncore regenerate ID which goes in and regenerates our session ID to make it even better and more secure because the default one that you get from doing the session _ start is not very good uh so doing this here is going to allow for us to regenerate it and right now it may be asking what session because we didn’t actually start any session yet uh so let’s go and do that right now let’s go and put in a session unor start right Above This condition here so right now we started a session after we set all these parameters of course and then we went in and said we wanted to regenerate our session ID to make it better underneath here I’m going to say I want to create a session variable so I’m going to say we have a dollar signore session going to call the session variable something like last regeneration so lastore regeneration and I’m going to set this one equal to something called time now time is a function we have inside PHP that just simply gets the current time inside the server uh so by setting last regeneration equal to the current time I can now check when is the last time we actually uh went in and updated our session ID because that is going to be the time stamp inside this last regeneration session so what I can do now is I can go inside my if condition and say I want to run a is set function that goes in and checks if this particular session exists inside my website because if it does not exist it means that we have not yet went in and improved our session ID so that is something we have to do uh but right now we’re checking if it does exist and we have to check for the opposite so in order to do that we write a exclamation mark in front of the is set function in order to do the opposite so basically we’re checking if it does not exist inside the website so now what we’re going to do is we’re going to go and create a else condition which is going to go in and update our session ID after 30 minutes so what we need to do here here is we need to go in and say we have a variable called interval and this interval is going to be equal to the time in seconds that I want to pass until we have to update our session ID again so this case here there is 30 seconds to a minute so we need to say 30 times the number of minutes that we want to actually pass so in this case it’s going to be 30 minutes uh so what I’m going to do below is I’m going to run another if condition because now we want to actually check if the current time minus the time inside our last regeneration is greater than or equal to 30 minutes because if it is then we need to regenerate the ID again as so go inside this condition here we can say if our time which is that function we did before as well minus our session called last regeneration is greater than or equal to our interval that we set up here and if it is then we want to regenerate the ID and we also want to reset our L generation equal to the current time that we now again updated our session ID so I’m just going to copy these two lines of code here and paste them below but now there’s an easier way to do things cuz now we start getting into functions because we are duplicating code so these two lines to code here are also down here so you know instead of having to duplicate the code every single time uh we could go below here and create a function and I’m going to call this function something like regenerate session ID so now we have a regenerate session ID function and I can take these two lines of code paste them inside the function and simply run the function inside where we need to have these two lines of code so we can just paste that in there semicolon copy this line of code and paste it inside up here instead as well so now we are running the same code but we’re not duplicating code in multiple places so going back inside my index page we’re now going to talk about these forms down here because now we have to start creating the signup form and the login form and you will notice that inside my sign up form and inside my login form I do have a action that points to a file that we do not have created yet so we need to create these two files inside our includes folder so what I’m going to do is I’m going to right click on my includes folder create a new file and I’m going to call it login. in.php and I’m also going to create a file called sign up. in.php so now we have the file that is going to actually run the code for signing us up and logging us in once we actually do get to those parts inside the website here for now let’s go and close down to login. in.php file since we don’t want to talk about the login system until we actually created the signup system because the signup system comes first right we need to sign up first and then log in the user uh so let’s go and start with that inside this page the first thing we’re going to do is we’re going to open up our PHP tag so we can actually run some PHP code in here and then we’re going to run a if condition to check if the user actually accessed this page legitimately so did they actually submit the form in order to get to this page or did they go inside the URL and try to access this page in a weird way by you know trying to access it directly inside the URL uh because that is something we can do so what I want to do is I want to go inside this condition here and I want to say I want to run a dollar signore server super Global and I want to check for a request method which is going to be a post method so we’re going to say requestor method and I want to check if it’s equal to a post method if the request method is equal to a post method it means that the user did get here correctly if not then they did not get here correctly and we have to send them back to the front page so that is something we have to do now so if they did not get in here correctly then we run a else condition and then we just basically run a header function in order to send them back to the front page so a header function looks something like this uh we just basically go in and tell it where to send a user so that would be a location which is going to be back One Directory because right now we’re inside a includes folder with this file here so we go back one directory and then access the index.php file in order to send them back to the front page I’m also going to go and add a die function underneath here to make sure that this script stops from running so if there’s any other code in here that might accidentally get run uh then we do actually stop the script from running so that is a good thing to include in here so the next thing we have to do inside our if condition here is to actually grab the data from the users so inside my uh sign up form I did actually have a post method that is called username because that is one of the inputs that was submitted and I’m going to set this one equal to a variable which is called username so again just in case people are confused if I were to go back inside my signup form you can see that down here I do have an input and this one is called username so that is why I’m referencing to a username post method because that is the method we chose for this form here so going back inside the sign up page I’m going to duplicate this down two more times since I have two more inputs one is called PWD for password and the other one is going to be called email we’re not going to do any sort of Sanitation here by the way because I do know that some people may be pointing out that we have HTML special characters or you know some of the other filter underscore inputs that we can use in order to check for certain things but it is best practices to not do this until you actually output something inside the website or you try to store information inside your website uh so we’re not going to do HTML special characters until actually output something underneath here I’m going to go and run a TR catch block just like we did inside our connection file and we’re basically going to do the same thing here so we can actually go inside our database connection and say we want to you know actually run a exception and a error message of something would have failed so we can go back in here and say we want to replace that uh so basically we want to run a PDO exception and we want to have a variable e which is the exception and then we can run a error message to say something like query fail instead of saying connection failed so the first thing we’re going to do in here is I want to require underscore once my database file because we do actually need to have the database Connection in order to actually connect to the database I’m going to link to my db. in.php file we do not need to say it’s inside a includes folder because we’re already inside the includes folder so there’s no need for that um and one thing I want to point out here is we will need to require some more files because I did talk about something called the NBC model which is something that we should talk about just a little bit this early on because I want to get you into the habit of thinking in a MVC pattern which is going to be very beneficial for you a little bit later on in this course here and in any other courses you might be taking inside YouTube uh because the MC pattern is something you just need to know about so before we continue here let’s actually go and create our files for the MBC pattern so I talked about the Mec model being a way for us to structure our codes which is going to allow for us to make is a lot more scalable uh a lot more organized inside our code and in order to do that we’re going to create a lot of functions that are going to have different purposes so for example we’re going to have one file that is going to have functions inside of them that are used to connect to a database and actually cor the database then we’re going to create another file which is going to be used in order to actually show data inside our website so whenever we have any sort of PHP code that is going to show something inside the website that is going to go inside the second file and the third file is going to be for actually handling any sort of input or information that needs to get run inside the website and this is what we call a MVC model we have model U controller and whenever it comes to any sort of application like we’re doing right now so right now we have a signup system and we have a login system so we’re going to go in and create a MVC file for our signup system and for our login system so going inside our directory here I’m going to go inside my includes folder I’m going to create a new file I’m going to call call this one sign upore model. in.php I’m going to create a second file which is going to be called sign upore view. in the PHP and I’m also going to create a third file which is going to be called sign upore controller. in.php controller is spelled c n t by the way so now with these let’s go and wait with the login system because like I said that it’s going to wait until a bit later uh so for now what we can do is we you can actually take a look at these different files so right now if I want to go inside my model here you can see there’s nothing inside this file uh basically these three files are going to have a bunch of functions inside of them and depending on the file we’re going to have these functions do a specific thing so they have a certain task they need to do uh so inside the model here that is going to take care of only cing the database and getting data or submitting data or updating data or deleting data it’s only going to interact with our database and it’s very important to point out here that these are very sensitive functions because these are interacting with our database and that is a sensitive thing uh so the only thing that is allowed to interact with these functions in here are going to be our controller file because our controller takes care of handling input from the user and then uses these functions in here to actually send that information to these functions so they can actually do something with the database so we separating different tasks here and I know that may sound confusing but that is something that is going to be something you have to learn to do so what I’ll do to start with inside this model here so I’m going to open up my PHP tags and I want to say I want to activate something called strict types and this is something you don’t have to do this is something that I like to do because it just sort of prevents more errors from happening inside our code if it were to write a typo or something or submit the wrong type of data so by declaring that we want to set our strict types equal to true it means that we are allowing our code to have something called type declarations I will talk more about type declarations once we actually get to it for now just know that this is something we’re going to have inside our code here and what I’m going to do is I’m just going to go and copy this code make sure I save it and paste it inside my controller save it and paste it inside my view because we’re going to have this inside every single file so going back inside our sign up that ink the PHP file we’re going to include two more files underneath our database connection the first file is going to be the model that we just created so we’re going to say we have a sign upore model that ink the PHP and then we do also have a signup uncore controller that ink the PHP the order here is very important because that is going to be relevant for later when we do talk about object or PSP and then instantiating different objects based off classes uh and that has to be done in this order here so this order here is just a good habit for you to get into it uh so the model is always going to come first after the connection and then we’re going to have the controller after the model here in a situation where you did also need to connect to the view that would actually go in between these two so you would have these sign of view in between the model and the controller just to point it out but for now we don’t need to have the view we’re just going to go and delete it here and again if this is confusing to you about model view controls just go and wait because it will make sense in a second I promise okay I know it doesn’t make sense when you get started on it and I’m sitting here talking about it uh but since we haven’t actually done any sort of code based on it yet it is going to sound confusing so you’re not alone if this is confusing you it will make sense in a second okay so going below here the first thing we’re going to do inside our Tri block here after actually grabing these files is going to be running error handlers now error handlers is a way for us to go in and actually do any sort of prevention to make sure that things are running appropriately so to speak so things are running correctly inside our code uh so if the user were to go inside your website and not type something inside one of the inputs when they’re trying to sign up then we want to take them back to the front page and say hey you forgot to sign something up in there so that’s the thing we have to to do in order to make sure that we have some sort of error prevention happening inside our code uh and some of you may say well Daniel can’t you just go inside your index. PHP and go inside one of these inputs here and include a required attribute and with this attribute we can no longer submit this form right uh wrong because this is front-end development this is client side languages so HTML CSS JavaScript cannot be used when it comes to security at least we cannot rely on them when it comes to to security that should always be done using a server side language because if I were to put this inside my website I can just go inside my website here I can click F12 to go inside my developer tool go inside my form down here and I can just go ahead and remove my required attribute and there we go I can now hack this website and bypass it so it’s very easy to do so do not rely on HTML or css or JavaScript for any sort of security only for extra things so to speak so having said that let’s go and go back inside our sign up and actually create a error Handler for checking if every input are actually filled out before the user actually submits the form so what I’m going to do is I’m not just going to write the code directly in here because that is not organized that is not the appropriate way to do things because all of a sudden we have a lot of code inside this file here uh so let’s go ahead and split up the task to our different files so now you have to ask yourself okay so what are we trying to do here are we trying to quy the database are we trying to show something inside the website are you trying to take some user data and do something with it yes we are so we’re going to go inside our controller file which is up here so our sign upor controller. in.php is what we have to use so inside my controller I’m going to go and create a function which is going to have a name that name is going to be is input empty so isore input put underscore mty and this is just you know one of many ways you could name functions just to point it out some people prefer to use camel case other people like to use underscores so this is just a little bit easier for people to tell what this function is at least from my eyes when it comes to naming these functions here uh but inside this function what I can do is I can pass in some parameters so inside my parameters here I want to pass in a username so going to say we have a variable called username I do also want to pass in a password and a email because I have to check if any of these were not submitted when they us to submitted this signup form and remember we use these parameters here to pass in data from outside the function so this is important to have uh so inside the function itself I’m going to run a if condition and inside this if condition we have a built-in function called empty which is basically checking if one of these variables are empty or if they have data inside of them so I’m going to grab my username put it in here and check is this one empty or is another one of these empty so I can actually copy paste here and just simply check for the password I can also copy paste again and then we can check for the email and these two pipe symbols here means or inside our condition so if this one is empty or this one is empty or this one is empty then we want to run a certain blocker code so in this case here this would actually mean there is a error inside our form because they did not fill in one of the inputs if this one is actually true uh so what I’m going to do is I’m going to go in here and say I want to return a true Boolean and then I’m going to run a else condition and say I want to return a false Boolean and in this sort of way we can now go in and actually check is there a error when the person tried to submit their username password and email because they did not fill in the inputs so now saving this I can actually go and copy the name I can go back inside my sign up. the PHP file and inside my error handlers here I’m going to create a if condition that is simply going to check if this one returns as true or if it returns as false because if it returns as true then we do actually have a error inside the website so in this case here if this returns as true by just pasting in the function and at this point here I’m actually going to wait with putting in the code for the actual error message inside this condition here because we do have a couple of different ways we could do it and I do have a way that we are going to do it in this video here uh but it’s not going to make sense until a little bit later on so let’s go and wait with this uh what I’m going to do is I’m going to create a second function that is going to check for something else in this case we can actually check if it was a valid email that the user actually submitted so what I can do is I can go back inside my controller I can copy this function here just copy paste it below and I can call it something different so in this case if you could say something like is email invalid isore _ inval valids and now at this point here we’re only checking for a email so we don’t actually need to have the password or the username so we just go and delete those two from the parameters here and inside the condition here I’m just going to go and delete these empty functions because we’re not going to check if they’re empty we’re actually going to run a filter so we’re going to say filter uncore V which is a build-in function inside phsp and inside this one we can tell it what do we want to filter for so in this case here I want to filter my email so I’m going to paste in my email as the first parameter and then I want to tell it what exactly do I want to filter here and in this case I want to filter to validate if this is a proper email so filter uncore validate uncore email and this is actually a built-in uh validation inside PHP so you can actually check if this is a valid email uh if that is the case then right now we’re returning this as true and if that is not the case then we return it as false but this is the opposite of what we want to do we do actually want to say if this is a invalid email then return as true so we’re going to go in here and write exclamation mark which means the opposite so in this sort of way we now have a function that can check if the email is actually valid and if it is not a valid email then we return this as true so again we can go and copy this go back inside our sign up the dink to PHP so I’m just going to go and paste in my function below here and copy the if condition paste it down below and simply take this email invalid function and put that inside instead inside this condition here here uh so the next thing we can do here is we can actually go ahead and check if this uh username that the user tried to submit has been already taken because inside the database you may have many different usernames and you don’t want to have two users with the same username uh so what we can do is we can run another function inside our controller in order to check for a certain username and if it exists inside the database then the users should not be allowed to use that username so again we’re going to go inside the controller and copy this function and just paste it down and we’re going to rename it into is username taken and we’re just going to go and delete the parameter inside our if condition here and at this point I do actually want to point something out which is that right now we want to run a function that has to go inside our database and check for a username which means that we have to query our database but now I did talk about this earlier I said that we have three different files we have one called a model that takes care of cing the database then we have the view that shows information inside the website and our controller takes care of any sort of information so in this case here what do we do do we go inside this controller here and then we quy the database because that’s a no no only one file is allowed to actually quy the database and interact with the database inside our code which is our model file uh but before we do that we do actually need to do some type declaration here because we didn’t actually do that uh so right now our username up here is actually supposed to be pass in as a string data type or at least that’s what I decide this is going to be because the username is a string of characters so that is going to be a string data type I’m going to do the same thing for our password and our email since that is also going to be a string then I’m going to go below here inside my email invalid function and do the same thing because this is also going to be a string going to go below here and say I want to pass in a username that is also going to be a string so this sort of type decoration here is not something you have to do but it just adds another layer of error prevention inside your code because if I were to pass in a Boolean inside my uh function here then it would tell me inside the website hey that is a incorrect data type so it’s just an extra layer of error protection you could also go after here and say what the return type should be so if this has to return as a Boolean meaning a true or false statement then I can say bull right after here and say that is going to be the return type uh but let’s not go into that right now let’s just go and talk about telling it what kind of data we expect inside our parameters here so having talked about that let’s actually go back inside our model page and continue what we’re doing right here so right now we’re trying to query the database in order to check if a username is already taken uh so going inside my model page we’re going to go below here create a function give it some kind of name in this case here I could call it getor username and I can go ahead and say I want to pass in a username because we need to use the username in order to actually C the database to tell if the username exist in there uh so we have to pass in a username again remember we’re using strict types here so we can actually say we want to declare this as a string called username so now at this point here we do actually need to run a PDO Connection in order to do this and right now our PDO connection is inside our db. in.php file so there’s a couple of ways we could do this we could go in here and actually go ahead and require our file here so require uncore one and link to our db. into phsp but that is not actually necessary because we do actually have that linked inside our signup page so at the top here we link to these files up here we do have the database connection linked up here first before we actually access these files down here uh so going inside the model here I can actually go and pass that in inside as a parameter here so this is going to be a object data type so not a string or bully and this is actually a object data type uh because this is a PDO object that is going to to connect to our database again we haven’t talked about object or ENT PHP so just for now just trust me this is a object data type uh so this is going to be our variable called PDO which is of course the same variable we have inside our dph that in the PHP which is right here so now all we need to do is actually query the database because now we do have our connection passed into this function here so going down I can say that we have a variable I’m going to call this one query I’m going to set it equal to a string which is going to be the query for our database so in this this case it’s going to be a select statement I’m going to select my username from inside this table here because that’s the only thing we need to check for so there’s no need to grab all the data in this case we can just say username from our users table and then I want to say where a username is equal to a placeholder that we’re going to call username and in this sort of sense here remember the semicolon at the End by the way uh we now have a query statement that we can actually quy into the database using our connection but we do need to do this in a secure way using prepared statements so below here I’m going to create a variable and call this one stmt for statement and we’re going to set this one equal to our PDO connection and then we want to point to a method called prepare which means that now we’re creating a prepared statement and I’m going to pass in my query and send this one in separately because by sending in our query separately from the actual data from the user we now separate the data from the actual query which makes this something that is going to prevent SQL injection which is a good thing so having done this what I can now do is I can actually bind the data to this quy and send that separately so first of all we have to bind the data so we’re going to say we have our statement point to a method called bind param parenthesis and inside of here we have to tell it what is the name of the placeholder in our case it is going to be username so I’m going to paste that in as a string and then I want to to tell it what is the data I want to put in where this placeholder is in this case it is going to be our username and then we simply run a execute statement so we want to take our statement here point to a execute method and this will actually go in and actually Cory our database using this SQL statement up here uh so now that we did that we need to actually check if we did actually grab a row data when we search for a username called whatever the user typed inside the input uh so in order to do do that we are going to write a variable called result and we’re going to set it equal to our statement and refer to a method called Fetch now fetch is only going to grab one piece of data from inside the database so it’s not called Fetch all it’s just called Fetch so in this case we’re just grabbing the first result now the fetch type is going to be a PDO type and I want to refer to fetch uncore asak which means that I want to fetch this as a associative array this basically means that we can refer to the data inside the database using the name of the column inside the database which is a much better thing than using index arrays uh so in this sort of way here we can now take this data and return it so we’re just going to go and return our variable result which means that when we run this function here we grab the data or if the username does not exist inside the database then we get a false statement so now we copy the name of this function we go back inside our controller and we paste that function inside our if condition condition now we do need to remove these type declarations in here so we’re just going to say we don’t want to have those because we don’t need them when we actually call upon the function we do also need to make sure we pass in our connection inside this function here otherwise this is not going to work so we do need to say we want to pass it in and we want to make sure this is a object type so doing this here is basically going to go inside the if condition and then check is the username inside the database if it is then we return this as true if it is not then we return this as false meaning that this is going to be a error if the username is already taken or not an error if the username is not taken so again we can go back inside our sign up the D the phsp go down and copy one of these if conditions paste it below and change the name to what we called it inside our controller so we just copy the name of this uh function here go back inside and paste that inside our if condition of course again remove the type declarations because we don’t actually need those from be used to functions and in this sort of way here we now have something that goes in and actually checks for a username so now I’m going to do one last thing inside my error handlers here and it’s very important to point out that you can do many different types of error handlers you can also check for the length of the username or the password or the email or whatever um I’m just going to go and do a couple of different ones here and then you kind of get the idea that we can just do this and you can come up with any sort of error Handler WR a function for it and then refer to it inside a if condition inside our sign up that in the PHP file uh so it’s the the same process every single time basically uh so what I want to do here is I want to copy paste my if statement because I do want to include one last eror Handler I’m just going to go and delete the function from in here because we don’t have it yet and I’m going to go inside my sign upore controller and I’m going to create the last function so in this case I’m just going to copy paste one of these function here I’m going to change the name so it’s not is username taken but is email registered in this case here we do also need to Cory the database because we have to check for a email so I do also want to make sure I include my database connection inside this function here I do also want to make sure I pass in my email so not the username in this case so the email and inside the if condition here we’re just going to go and delete our function because we want to run a different function now so again because we have to quy the database to see if there is an email inside the database we have to do the exact same thing as we did with the username just using a email instead uh so we do actually need to go back inside our model and create a SE function that is only going to check for a email so in this case if we can say get email and all we have to do is change a couple of different variables in here so right now we’re passing in a email I want to go inside and take my email column I do also want to change the parameter here or the placeholder to email I do also want to change the name that I’m binding inside my bind parameter method down here so it’s going to be the email variable and also the email placeholder and with this this is all we needed to do in here here so we can go and copy this go back inside our controller and paste that inside our if condition and of course do also make sure you remove these different type decorations because we don’t need those inside the function when we call upon the function and with all this we basically now just check for an email being inside the database because it was pretty much the same thing as before uh so it’s very easy to do so going inside our signup we can go ahead and copy the name of this function here and paste that inside our condition and of course remove the type Creations like so and at this point we need to talk about how we can actually create these error messages because now we have a bunch of functions that check for different things and if one of them return as true it means that there is a error so what I can do is I go above my different conditions here and I can create an array which is going to be empty I’m going to call this one errors so we’re going to say we create a errors array which is going to be equal to no data and what we basically do is if there is a error inside one of these conditions down here then we assign that error inside this array up here so we’re going to stack a bunch of data inside this array depending on how many errors we get inside our code and then at the end if we have any sort of Errors inside the array then it means we get a error because there is an error in there and then we’re going to prevent actually signing off the user because if there’s an error then we shouldn’t sign up the user uh so what we can do here is I can actually go ahead and go inside the first condition and say I want to actually assign a piece of data to my array so I can say we have a variable which is called errors and I want to go ah and say brackets is equal to some piece of data which in this case is just going to be a string so right now I have to tell it what is going to be the associative name for this particular piece of data so this is the key this is the value so if I want to grab this particular error message here then I need to refer to this particular key in here that is basically what is happening again if you’re a little bit confused about when it comes to arrays I do have a array episode where I talk about arrays extensively um so this should be something you know by now for now let’s just go and go inside our array and create a key for this particular piece of data I’m going to call this one empty input so _ input and I’m going to create a error message so in this case we can say something like fill in all Fields exclamation mark then I’m going to do the same thing for all these other ones down here so I can go down and paste in my code and I can change this one not to empty input but instead we can say invalid email invalid unor email make sure we actually spell that correctly invalid change the error message to invalid email used then we’re going to go inside the next arrow down here which is if the username is taken and I can go ahead and save we can call this key something else so this is going to be username uncore taken and I’m I’m going to call the error message something else username already taken exclamation mark then we can go inside the last one down here and say this is going to be email uncore used and then we can change the error message to email already registered and at this point here if there was no errors meaning that none of these actually returned as true and insert this data inside our array it means that our array is going to be empty because if there’s no error then we didn’t put any data inside our array so now all we have to do is run a condition and check if this array is empty if it is then it means we had no error messages but if it is not then we need to send the user back to our index page you know what the sign up form is with error messages so I’m going to check if we did have errors this is going to return as true by the way if there is actually data inside this array if there’s no data then it returns as false and this is going to return as true if there is data inside this array and it’s going to return as false if there’s no data inside this array so what I can do is I can go inside this condition here and I’m actually going to go and create a session variable so I’m going to say we have a dollar signore session and I’m going to set this one equal to error signup or at least call this one error signup and I’m just going to go and assign some data to it which is going to be all the error messages that we have stored inside our errors array so I’m going to assign that to it but now at this point if we don’t don’t actually have a session started so we can actually run these error messages because we need to actually have a session started before we can actually store session data inside a session so what I can do right above where we actually assign these errors to our session variable is I can actually link to our config file because that has a session started uh inside that file so I’m going to go up here and just copy paste my require go down below paste it in then I’m going to change this to config uncore session in PHP because like I said inside this file here we do actually have a connection started so we could just run this liner code so I could just take this go back inside my sign up and just replace that with this line of code instead but because we do have a much safer way of doing things when it comes to sessions inside that file so instead we can just link to that file in order to start a much safer session so with this in here we can now actually assign this session variable to a value and have that stored inside our session so now what I can do is I can actually go below here and I can link back to our index page where we have our sign up form because we need to go back to that page and run some error messages so I’m going to run a header function and I’m just going to go ahead and copy paste what we have down here since that is going to be the same thing so we’re going to go back to the index page and because we have all the errors stored inside our session we can actually go ahead and print those out inside our page so let’s actually go and go back inside our index page and do that right now because why not we are at the error messages so why not just show them already so right underneath my sign up form I’m going to run a PHP function that we haven’t created yet so I’m going to say we have our PHP Tags I’m going to close it again and I’m going to refer to a function called check uncore sign upore errors parentheses semicolon and now because we’re actually outputting something now using PHP from the signup system we’re now going to jump inside our view. in the phsp file so our sign upore View uh is going to have a function inside of it which is going to be what we just created inside our index page so we’re going to say we have a function we’re going to call this one check uncore sign upore errors then we want to open up the actual function here and inside this function I first of all want to run a if condition because I want to actually check if we have these errors stored inside the session because if there’s no error stored inside the session it means there’s no error messages so inside the parameters we can run a is set function and actually check one of these session variables so in this case here I’m going to check if we have our erasor signup which is going to be the session variable we have inside our sign of the in the PHP that we did actually create down here and if we have that I want to go inside this condition and I want to create a variable called errors and I want to set it equal to our dollar signore session actually we just go and copy paste from up here which means that now we have a variable inside our PHP code which is equal to this array that has all our errors inside of it uh so this is actually a array now now the reason we’re doing this is because we do actually want to unset our session variables because like we talked about in previous session security episodes as soon as you have data inside your session variables that you don’t need to have anymore you need to make sure you actually delete them uh so at the bottom here I’m going to run a unset function that is going to unset my session variable because once I’m done running this script here I don’t actually need this data inside our session anymore so we’re just going to go ahead and remove it again right afterwards uh so in between here we’re going to go ahead and actually run the error code so first of all I’m going to run a small break just because I want to get some distance from the actual form uh this could also be done using HTML if you wanted to but inside my code here I’m just going to go and create a break and then below here I’m going to run a for each Loop because that is a loop type that is used in order to Loop out a array so I’m going to grab my arrow array and say I want to refer to that one and then I want to say as variable error which means that this is the placeholder for one of these data inside uh this array here and inside for each Loop I’m just going to go and Echo out a paragraph again I’m just going to copy paste from my notes here so I have a paragraph that has a class to it because I have some CSS inside my my website here and in between these paragraphs here I’m just going to go and concatenate my code so I’m going to say I want to concatenate and I want to go ahead and refer to my error and in this order way we now Loop out every error message below each other inside this page here so at this point here we do actually have a error system working now we could also say sign up success once we’re actually done uh but let’s go and wait with that until the end because we do actually have a little bit more code inside our signup in.php file and once we’ve done that then we can return to this in order to actually run our successful message so now in order to test this out we’re going to go back inside our index page and actually link to our file because right now we don’t actually have our sign upore view. interface P linked inside our index page uh so in order to actually access the functions we need to go at the top here create a pair of PHP opening and closing tags and then we’re going to say we want to require underscore once and I want to link to my includes folder and inside the includes folder I have a sign upore view. in.php we do also need to make sure we have a session started otherwise this is not actually going to run this code because we need to have a session available to us to grab the error messages so I’m also going to link to my config file so I’m going to go inside my includes folder link to my config session. in the PHP and doing this we can now go back inside our website and actually test this out we’re going to go and refresh the browser just to reset everything and now if we were to go inside my sign up form and try to sign up without typing something inside my inputs you can see we get fill in all fields and invalid email use because right now uh we didn’t type in a proper email and we did not fill in everything inside the form uh so if we were to type something in so for a username a password a invalid email you can see that oh we get a invalid email use because that was actually wrong if I were to type in a non-existing username from inside my database a password and a correct email so I could just say example at gmail.com and then click sign up then you can see we get something you know it actually puts us to the next page because now we type something valid into our signup form but of course we haven’t yet created something to actually sign us up inside the website so right now it’s not going to do anything now we’re just stuck inside our sign up the thing the phsp page um but just know that now we have something that actually writes out error messages once we do actually create some sort of error inside our code so back inside our sign up the link the PHP file we can actually continue in order to actually sign up the user inside our website uh so what I’ll do is I’ll go below here and I’m going to run a function called create uncore user parenthesis semicolon because at this point here we don’t actually have any errors CAU by the error handlist that we created inside our code uh so we can actually go ahead and run this function here so in order to do that we need to go inside our controller I’m going to copy paste one of the functions and I’m going to call this one create uncore user which is the one that we just created inside the signup page and I’m going to paste in our connection because that is important and then we do also need to paste in all the different data that the user actually submitted so I’m just going to go and copy pasted here so we need to paste in the password the username and the email and then going inside our actual function we can go and delete what we have here and we’re just basically going to run a function from inside our model page so we’re going to say we want to run a function called setor user parenthesis and then we’re just going to go and paste all the same data as we pasted inside this function here so we’re just going to go and paste that in make sure we remove the type declarations just like before we’re going to save this and then go inside our model page and then we’re actually going to to create a new function and we’re going to call this one the same thing as we did inside the last function so setor user and of course paste in all the data including our type declarations uh inside the parameters here curly brackets and then we can actually go inside one of these other functions and just copy paste the query and execute uh so this blocker code right here paste it inside our function and then we’re just going to go and change the statement from a select statement to a insert statement so we can say insert into users we’re going to include the column name so we have a username we also have a password and we have a email then we’re going to say values which is going to be what is inside these parentheses so again we’re going to use placeholders so this is going to be username and we’re going to include a password and we’re also going to include a email and then we just need to bind the parameters down here so we can actually copy paste in the username we can copy this down two more times and paste in the password we can paste into email and this is all we have to do but now we did also talk about hashing in the previous episode because we need to make sure that when we paste in this password that it can’t be read from inside the database so right before we bind the parameters I’m going to create a variable I’m going to call this one options because I want to include a couple of options inside an array and this is going to contain a cost factor which is going to be called cost and we’re going to set this one equal to 12 and this essentially is just going to make it cost quite a bit more in order to actually run this hash and this is going to prevent the Hackers from actually brute forcing the way into your website so this is important uh then we’re going to go below here and actually run a hash so we’re going to say we have something called hashed password and I’m going to set this one equal to a function called password uncore hash parenthesis semicolon and then we need to tell what exactly we’re trying to Hash here so in this case you want to Hash the password that was submitted by user and I’m going to run a hessing algorithm called password undor bpts and I’m also going to go and pass in my options which is the variable we created up there and this is basically going to Hash our password using the bcrypt algorithm and also go and add a cost factor to it so it’s going to slow down the The Brute forcing process if someone were to try and hack their way into your website um so what we can do here is we can actually take our H password and replace that with our password then where we actually B our parameters because now we’re storing the H password and not the real password inside the database we do also need to make sure inside this array here that we don’t set it equal but we actually assign 12 to our cost just so we don’t get that error message there uh so with this we now actually have this function working so we can go back inside our uh sign up the PSP file here and we need to make sure we actually paste in these parameters so we could just go back inside our controller copy all these different parameters here go back inside our sign up the PHP and paste those in of course without all the different uh type declarations that we have here so after running this function we just signed up the user inside our website so what we can do is we can go down a couple of lines and then we just run a header function and a die function in order to actually stop the rest of the script from running just in case and we’re going to send the user back to the front page where we’re actually going to include a sign up success message so we can actually go and say we have a question mark sign up equal to success and before we end off the script here so before the die function I do actually want to close off my connection and my statements so I’m going to say we have our variable PDO I’m going to set it equal to null then I’m going to copy paste this down and I’m going to say I want to set my statement equal to null and in this sort of way we now have a basic signup system working inside our website so now what we could do is we could actually go inside our website to test this out but I do want to have our signup success message if we do actually do so uh so we’re going to go and use this little um URL parameter here in order to do that so right now we have a signup equal to success displayed inside our URL if this is actually successful uh so what I can do is I can go back inside our view function because this is the one that actually has the error messages and I can write a else if condition and then check if we have that inside the URL with the sign up equal to success uh before we do that let’s go and paste in what we actually want to display inside the website so in my case I do want to again just run a break but I’m also going to go below here and Echo out a paragraph that is going to say sign up success inside the condition I’m going to run a iset function that is going to check if we have a certain get method inside the URL so in our case here we are checking for a dollar signore get because that is something we can do whenever we have any sort of data displayed inside the URL for example sign up equal to success so I’m going to check for something called sign up which is going to be the key inside the URL so we have sign up equal to success so key equal to Value okay just like inside arrays and I’m also going to go and check if it is equal to a certain message so I can go right after our is set function here do make sure you do it after the parentheses so in between these two parentheses at the end here and I’m going to say and is my get signup equal to a certain string so in this case success and having done this we need to do one more thing that I actually forgot to do inside our sign up the link to PHP file which is to go down and inside our errors if condition I do need to make sure we exit this script if we do have any sort of Errors inside our code otherwise it is still going to continue running all this code down here even if we do get a error message so we do need to copy this die function here and paste it right below our header because then we do actually exit the scripts and with this we now have a complete signup system or at least a signup system with a error message system so you can actually see any sort of Errors you might have inside your signup form so if were to go back inside our web page I can actually refresh everything just to make sure everything is reset and going inside and typing in a sort of error so if I were to type something wrong uh let’s say I did not fill in my password and I wrote a invalid email if it would to sign up then you can see we get two error messages down below we get fill in all fields and invalid email used so as you can see we have error messages showing and telling us what we did wrong inside the signup form uh what we can also do here is we can actually sign up inside the web page because that is something we have set up as well so if we were to go in here and say I want to sign up as Danny Crossing and I want to type in one 12 three as my password and say I want to type in a email so I can say Crossing at gmail.com which is not a real email that I have but just to come with some kind of example here uh if want to click sign up now you can see sign up success and then if I were to go inside our database we now have a user inside our users table so at this point here the signup system is working but there’s one more thing we need to include inside in order for this to be a complete signup system at least I think this is a feature that is something you should have inside a signup system which is to make sure that if you create any sort of error messages inside the signup form let’s say I went inside my signup form and I wrote in a valid username and I did not type in a password and I did type in a valid email so let’s say we say example at gmail.com um at this point here if I were to get a error message when I try to sign up because I did not fill in my password it should send back the data that I already typed in inside this form so don’t have to retype everything if I get sent back with an error message because that is just really annoying so this is more of a usability feature for people to not have to retype everything inside this form here so in order to create this I’m going to go back inside my code and the first thing we have to do is make sure we actually send the data that the User submitted back to our signup page so we can actually show it inside the inputs and the second thing we have to do is actually show it inside the input so we have to do two things in order to get this working here so the first thing we’re going to do is I’m going to go back inside my errors if statement here and I’m actually going to create an array that is going to contain all the data submitted by the user so we can send it back to our index page so if we have some sort of Errors then I want to go in here before the header function by the way and create a array and in this case I’m going to call this one sign up data and we’re going to set this one equal to an array so we’re going to say brackets and semicolon and then opening this up we can now add some data inside our array here and we’re going to do that as a associative array so we want to have a key and we want to have a value for that key so the first key I’m going to have in here is going to be the user name because I want to send back the username and again this is a name we can come up with ourselves so you can call this whatever you want uh in my case here I do think username makes sense because this is the username then I’m going to assign a piece of data which is going to be the username the user actually submitted when it tried to sign up inside our form which is going to be variable username and the reason I know that is because if I were to scroll up here I can actually show you that we want to grab all these different data and send that back inside the signup form or at least all the data except for the password because I do think the password is something you have to retype every single time in case you get something wrong inside your input and that is just kind of something you see inside websites typically so we’re not going to send back the password but any other kind of data we are going to send back inside the index page so going back down I’m going to assign the second piece of data which is going to be our email or at least the users’s email they tried to sign up with so this is going to be called email and we’re going to copy that and paste it over inside our variable here so now we have the actual data inside an array and now we have to actually send it back by assigning it inside a session variable just like we did up here so I can actually copy this session variable that we have paste it down below and we’re just going to go and change the names in here so we can actually go and say sign upore data and then we can go ahead and say this is going to be equal to our signup data so with this here we can now send the data back to our sign up form so what I can do is I can go inside my index page and what we need to do now is just basically take all these inputs from inside our signup form and we’re going to replace it with a piece of PHP code that is going to check if we did actually have some data sent back to this form here because then I want to show a different version of these inputs here so the way I’m going to do this is I’m going to copy all my inputs here just so I have them and I’m going to delete them and then I’m going to go inside my sign upore view. in.php file since we now have to show something inside our page and like we talked about we have the model view on controller and the view is going to take care of showing something inside the web page so what I’ll do is I’ll create another function so I’m going to go below my declare here and create a function and I’m going to call this one sign upore inputs just to give it some kind of name then I’m going to go inside and I’m just going to paste in my HTML for now so now what we have to do is create a couple of conditions that are going to check if we have this data being sent back to aign up form because of an error message and if that’s the case then I want to include that data inside my inputs here instead of having just the regular inputs with no data so what I need to do is go below here and create a if condition and inside this if condition I want to check if we have a certain session variable existing inside our web page which is going to be the one that has all the data in inside of it so going inside of here what I can do is I can write a is set function which checks if a certain session variable is currently set inside the page so I can check for a session variable so dollar signore session and I’m going to check if we have something called sign upore data but now I do want to check for a specific piece of data inside this sign upore data array uh so what I can do is I can create my brackets afterwards here and refer to a certain P inside this array here so right now I want to check if we have something called a username so if we have this it means that we did not leave any input empty for this particular input so now we’re actually also checking if there was any empty input so we don’t actually have to check for that particular error message but we do need to check for another error message because what if I picked the username that already exists inside the website because if I did that it means that I need to retype the username because it is already taken so in that case I don’t want to type the username that used to submit it because it is wrong and it needs to be changed right so we also want to check for certain error messages in here the way we can do that is going afterwards make sure it’s after the first parenthesis over here and we’re going to write a and condition and we want to check for another is set so what I can do is I can copy paste this session that we have here paste it inside my is set statement and in this case we’re not checking for sign upore data but we’re checking for errors uncore signup and then inside our errors uncore sign up we have a specific error message that we want to check for so in this case here it is going to be username unor tagen taken taken username uncore taken but we do also need to keep in mind here that I want to show the data inside the input if this error message does not exist inside our website so I do need to write a exclamation mark in front of my iset function here so right now we’re checking if we do actually have the data available because the User submitted some data and if we do not have this error message inside the web page then I want to actually show the actual data the User submitted inside an input so we can actually copy paste what we have up here with the username and I can go down and say I want to Echo then I’m going to say single quotes in order to not mess up any HTML here because we are using double quotes inside the HTML and then I’m going to close it off here and now the way we actually show data inside an HTML input and again this is HTML this is not PHP knowledge is by actually going in and adding a value attribute and then I’m simply going to close off the HTML by using single quotes and then I’m going to concatenate some PHP code and I’m going to paste in my data from inside our session so I can actually go and copy that from up here inside our condition and paste that in inside our value then I want to run a else condition because if this is not the case and we did not have any sort of data sent back and we did maybe have an error message then I do actually want to go in and show the Reg input without any sort of value inside of it so I do need to Echo that out as well so I’m going to Echo out single quotes paste it in and semicolon and this is basically all we need to do for these different inputs here so now the second one is going to be our password and in this case here with the password we did already talk about that I did not send the password back because I do want the user to retype it no matter what happens uh so in this case we do actually just need to Echo out our input for the password so we can just go and copy paste a password input here single quotes and paste it in and semicolon but when it comes to the email input we do actually want to copy paste this if else condition up here paste it below and then I want to use my email instead so instead of checking for sign upore data username I want to check for a email I do also want to make sure we’re not checking for a error message that is called username unor taken but instead I want to check for a email used because that is the error message we had inside our sign up. in.php if we were to scroll up here you can see we have email used but now we do also have a second error Mage when it comes to our email which is actually called invalid email so we do need to check for that as well because if you have more than one error message for one particular input then that is important to check for as well so going back inside our view I’m going to copy paste from where we actually check for the ANS and all the way over to the first parentheses copy that and then paste it in right afterwards here because now we can actually check for a second error message do make sure you have all the parentheses correct and all the single quotes and double quotes because that will mess up something inside your web page if you do not have everything said correctly so with that in mind let’s go and change the second error message from email used to invalid email because that is the error message for that particular one so now all we have to do is make sure we replace the actual Echoes down here so I’m going to copy paste my email I’m going to go down below and paste it in instead of these Echoes that we have in here in both places by the way so both inside the if condition and inside the else condition and then we just need to make sure we also add in the value inside the first one up here so I’m just going to go up going to copy the value make sure you copy it exactly like I am here so after the double quote at the end there but also before the angle bracket so copy that go back down and paste it in right after the placeholder so space and paste in and then just go ahead and change the actual data inside of here from username to email go back up to the top here delete these HTML things that we just pasted in just for reference and now what we need to do is just copy paste our sign upore inputs function go inside our index page and actually spit this out inside our form so if we were to go inside the form here where we had the inputs before I can say I want to open up my PHP tag and close it again and just simply write out my function and in this sort of way we should now have our actual data being shown back inside the forms if I to type some sort of error message so if I were to go back inside and refresh everything inside my page here so if I go back inside my form and type a random username so just something jerus write something random inside the password and let’s go and create a invalid email so in this case here when I click the sign up button we should not have any sort of data inside the email field but we should have something inside our username field so we want to click sign up here you can see oh okay invalid email used we still have the data inside our username but it did actually remove the data from inside the email which is what is supposed to happen uh so if I want to go in here and say I want to type in a username that already exists inside the database so Denny Crossing type in a random password and then let’s go and create a valid email so let’s say example at gmail.com so if I would to actually submit this it should send me back without the username and without the password because the username is already taken right so if I were to click submit here you can see that we get sent back without the username without the password so as we can see this is working like intended so with all of that we can now go ahead and sign people up inside our web page and just to double check nothing is being inserted inside the database cuz that’s always a good idea you can see that nothing is getting inserted and with that we now have a signup system with both error messages and we have the data still being inside the forms if the user would submit something wrong you know so they don’t have to retype things the signup is actually working inside the signup system uh what I’m going to do here is I’m actually going to split up this video into two part since this is already pretty long and I don’t want you guys to sit here for like 3 hours or something I don’t know maybe this video is going to be 3 hours long who knows so we’re going to split this up into a signup part and then we’re going to have a login part in the next video so I hope you enjoyed this video and I’ll see you guys in the next [Music] one so in the last video we how to create a signup system inside our website just as an exercise to learn how to use all the different things we learned up until until now inside this course and we still need to create a login system since we you know now we have people signing up inside the website but we also need them to be able to log into the website uh so what we’re going to do to begin with is we’re going to start up inside our login. in.php file because this is the file that we need to start in in order to you know when the user goes inside our login form and submits the user name and password they send that information to this page so we can actually lock them inside our website from within this page here so in the same sense as we did inside our sign up the in to phsp file we’re just going to go ahead and check for a server request method just like last time we’re going to go in and make sure we do that to begin with so we’re going to open up our PHP tags and we’re simply going to check for a request method that is going to be a post method so if the user got to this page legitimately by actually submitting the form post just like with our signup system then we do want to run some code inside this file here so the first thing we’re going to do is actually grab the data so in the same sense as we did in the last one you can see there’s a lot of copy pasting because we did the same things already uh we’re going to go and grab the username and password from within our login form and just to show you if I were to go back inside my index page I do have a login form and I do have a signup form and inside my login form I do have two inputs one for the username and one for the password so not anything for I think a email which we had in the signup system because we don’t need to log in using a email so going back inside our login. in.php file I do also want to make sure that if the user actually got to this page illegitimately so if they did not submit a request method called post then I do want to go down and write a else statement again just like inside our sign up form so we were to go in here scroll down to the bottom you can see that we have a else statement that simply sends them back to the front page and kills off this script here so if we were to go back inside our log in you can see that we just simply paste that in and that is all we need for now at least and then we have a basic structure of you know sending the user back if they did not get here properly so what I want to do now is I want to go below our username and password that we grabbed using the post methods and I want to go in and do a dry catch block just like again in the last episode so if we were to go in here you can see that we do have a try catch block where we go in and we try some code and if it fails then we do want to catch an exception and actually you know write whatever error that might has happened inside the website so we know that an error has happened so again we’re just going to go and copy the catch block at the end here and we’re going to go back in and we’re going to replace the catch block that I autogenerated using the tap functionality we have inside editors typically so I’m just going to go and replace that and now we do have the ability to catch a PDO exception if something were to go wrong so now all we have to do inside this Tri block up here is actually run the code that is going to allow for us to check for error handlers and check you know if the user should be logged into the website if there were no error messages then of course you know we do want to lock them in so what we’re going to do to begin with is first of all I do want to make sure that I create a login controller a lockin model and a lockin view just like we did in the last episode when it came to the sign up because we do need to go in and create these different functions that has something to do with different tasks again we’re going to try and implement this MBC model system uh so you can get a little bit familiar with it when you get into object Orient PHP which I did just upload a crash course on object oriented PHP and I will include that inside this playlist here as the next episode because I do think it’s a very good idea for you to know about object oriented phsp so we’re going to get into objectoriented PHP after this video here and I just want to say don’t don’t freak out because a lot of people do think objectoriented PHP is very difficult but it’s really not you just need to have someone explain it to you in a beginner friendly sort of way so it’s really not difficult to learn object oriented phsp it’s just you need to have it explained properly and that way you can get eased into it and then you’ll you’ll realize that oh okay so this is actually pretty easy um so we’re going to do that in the next episode so please watch that one even though it’s not labeled number 30 or something inside this course here because it is relevant to what we’re going to do in the future inside this course here but for now let’s go ahead and create these different controller model and Views inside our files here so what I’m going to do is I’m going to go inside my includes folder and I’m going to create a new file I’m going to call this one loginor controller or c n. inc. PHP we just going to copy everything here and I’m going to create another file and I’m going to name this one the same thing except for controller we’re going to say model then I’m going to do the same thing but this time we’re going to call it view so linore view. in.php and we’re going to go and link to these files we just created because we do need to use some of the functions inside these files so we do need to have them available to us inside what we have here so what I’m going to do is I’m going to say I want to require underscore ones and I want to require these files one at a time time so the first one is going to be login actually just copy paste here cuz I did actually copy it I’m going to copy this down two more times because we do actually need to get the database connection first that is the first one we need to grab so we’re going to say dbh in.php which is the database connection that we created over here which is just a very basic file that connects to the database and then creates a PDO object which I do explain in that Next Episode by the way because we do go over objects in the next episode and then we can use this PD connection object in order to connect to our database again this is something we learned in the last episode but since I recorded that a while back I thought why not just mention it again so going inside our login. in phsp file we do need to make sure we have this connection and then we’re going to go down and say we want to grab the model and then we want to grab the controller and the order here does matter so you do need to have the connection first then the model and then the controller so now taking a look at what we did in the last episode you can actually see the we immediately started doing error handlers inside this script here and we’re going to do the same thing when it comes to login system so instead of doing things a little bit out of order like we did in the last episode because that might be easier for you to understand now you do know exactly what these error handlers do while we create this empty errors array why we do these if conditions down here why we do need to want to have this config underscore session why we do need to check for if we had any sort of Errors inside the array because then we need to send the user back with an error message so we do do have some things in here that we’re going to repeat inside the other file so we’re going to go and copy everything from when we actually check if the array that is called errors have any sort of Errors inside of it all the way up till the comment where I wrote error handlers then we’re going to go back inside the login file go down and simply paste that in so right now we are creating an empty array called Aros which is going to contain any sort of Errors you might be getting inside the website and in this case because we’re doing a login system and not a signup system of course this are going to change a little bit because you might not want to check for as many things for example why do we check for an email when it’s a login system we don’t have any emails passed from the user so we don’t actually need to have that uh so we don’t need to have all of this inside our code for now we’re just going to go Ahad and delete all of them except for the first one which is going to check for any sort of empty inputs and then we do actually need to go after this one and we do need to actually query the database because we need to actually grab the user from the database that they typed in using the username and we need to check if the passwords match because if this password the user just submitted matches with the user’s password from within the database then we do need to check for that as well and of course there’s many different error handlers you could be doing when it comes to a login system I think for now just because this is a basic example it is just enough just to check for empty inputs and check if the username exists inside the database so does the user actually exist inside our database and if the user exists does the password actually match inside the database as well so we have a couple of things we need to check for here so what I’ll do is I’ll go inside my loginor model file and I’m actually going to quy the database using the username provided by the user to see if the user exists inside the database and if they do then I do want to grab the password and check that up against the password the User submitted just now so what we’re going to do is we’re going to open up our PHP tags just like any other time we go inside a new file and inside of this one I’m going to create a function that simply goes in and gets the user so we can say getor user and I’m also going to go and declare strict types because we did actually talk about that in the last episode so we’re going to declare that we want to use strict types so we’re going to say parentheses strict underscore types and I’m going to set this one equal to one this means that once we do actually get inside this function down here we can also tell it that we want to require a certain data type and not just the variable but the variable has to be a certain data type so inside the parenthesis I want to get the connection so we want to grab the variable PDO which is the one we have inside our database connection here so we can actually connect to the database in order to query it the second thing we’re going to pass in is going to be the username because the username was given to us by the user so if I were to go back inside my login. in.php file you can see that we did actually get it up here so just simply going to quy the database using this username now now we did talk about strict types so what I can do is I can actually say this is a object type and then the second one over here is going to be a string type again we talked about the PDO variable being a object that we created inside our connection so whenever you use PDO in order to connect to the database in this sort of way we do do that by creating a connection object using PDO and we do that using this new keyword so we instantiate a new object that is from the PDO class again we’re going to talk about this in the next episode uh but this one is going to be our connection so we do want to make sure we grab that and refer that to as an object because that is what it is and then we just have the username being a string because that is what the user gave us so now inside this get user we simply going to go in and Cory the database and we can actually go and copy paste because inside our sign upore model we do actually have very similar function so we can actually go in and just copy everything from inside just this first one up here called get username just to grab one of them and we’re going to go back inside the model and simply paste that in now everything is going to be the same except for our select statement up here because right now we want to not just select the username but we do want to select everything from inside this table here so we’re going to grab everything from the users table where a certain username is equal to username so in the same way as we did before then we create a prepared statement we go in and bind the parameters to the placeholder so right now we have this name parameter up here so we just bind the username the user gave us and then we execute it and then we grab all the results from inside our database or at least we’re grabbing one result from inside the database because we’re not fetching all of the data but just fetch which is just one piece of data or one row from inside the database so with this basic function here we can now just go in and cor the database using a particular username which means that we can actually go in and grab our loginor controller and do a couple of other functions in order to check if the username exists inside the database and we can also do want to check if the passwords match inside the database because you know the username has to use the right password so I’m going to go inside my model again and just copy everything go back inside my controller paste it in and just delete everything inside the function and change the function name to something else because in this case here we might call this one is underscore username wrong so underscore wrong and inside the parameters here we’re just simply going to check for variable results which was the one that we returned inside our model here if we do actually have a result but there is a small catch here because if I qu the database and we do actually have a user inside the database with that username then I’m going to get this one as an array however if we do not have a user inside the database with that username then this is going to return as a Boolean so no longer as an array but as a Boolean because it’s going to be f because there’s no user inside the database so how do we do that when it comes to strict types because if we would to go back here and say okay well I want to require variable result to be of a certain data type because if I write array then if I don’t have the user inside the database then we’re going to get an error message because now the strict type is wrong so if we were to type bull instead which is a Boolean then now it’s going to be wrong if we actually do get a result from inside the database so the solution here here is that we can go in and write this pipe symbol and say we also want to accept an array so now we’re saying that if this is either a Boolean or an array then we do want to accept the results so this is how you can combine different data types and say that you want to accept one just one type of data so not just a string but also a string and a Boolean if you wanted to uh so just to show you that this is how we can do that inside the function itself we’re going to write a if condition I’m just going to copy paste for my code here because it is very simple so going in we’re just going to create a if condition and we’re going to check if result is equal to false then return true because if it returns as false it means that we did not find the user inside the database because we don’t have any data inside this array here otherwise return this as false which means that we did not have any sort of error messages I know that the true false May logically seem like it switched around but it’s not really because the function is called isue username wrong and if this one is true it means that it is wrong and this is how we can simply check if the username exists inside the database and I know we haven’t actually use the function inside our login theing the PHP file yet but it will make sense in just a second so what I’ll do is I’ll copy paste this function below here and I’m going to check is password wrong because we do also need to check if the passwords do actually match because we do have a password from the user that just tried to log in and we do have a password inside the database which by the way has been hashed so we need to actually check these two against each other um and then we need to return this as true if they do not match each other or false if they did match each other the simple way to do this is just to go inside our parameters and say we want to get a string which is going to be the password submitted by the user and then we also do want to get another string which is going to be the has password from inside our database so PWD so grabbing these two different passwords we can go inside the if condition and simply run a password underscore verify and then we’re just simply going to check these two different pieces of data up against each other so we can check if password and H password do actually match each other but we do need to keep an eye out here because we are actually right now checking if the passwords do actually match each other which if they do then we’re actually returning a error message and that is the opposite opposite of what we want to do so we do need to make sure we go inside the if condition and do a exclamation mark in front of our password verify because now we’re checking if this is equal to false but now we do also have one last one we need to create because going back inside our login. in. PSP file we do have one more error Handler that we haven’t actually addressed yet which is right now is input empty because right now this is actually the one that matches up with the signup form and not the lockin form because as you can see we have an Emil in here so we can’t just reuse it and it is also just better to separate functionality so you know all the code for the login system in one place and then all the code for the signup system in another place because that kind of goes into the NVC model pattern that we’re going to talk about in a future episode okay so we do need to create a function for checking is input empty inside our linore controller so that is important so going inside the loginor controller I’m just going to copy paste the function here so you can just copy paste it as well uh it’s very basic we just go in and create a function and we call it is input empty and then we just submit a username and a password not an email this time around and we just go inside our function and just do a if condition to check if username and password are empty so with these functions here we now have a very basic example of checking for different types of errors that might occur inside our login form again if you want to add more you can do that uh for this tutorial here we’re just going to do these three for now so going back inside the login form we can actually make some adjustments so right now we do actually have this is input empty but I do want to make sure we delete the email and again this function here is something that we can actually grab because it’s inside our login controller which we did require right above it so we do have access to this function and then below here we do actually want to run our model function because we do want to actually grab any sort of data that might be inside the database where the username is equal to this particular username so what I can actually do here here is I can create a variable and I’m going to call this one result and I’m going to set it equal to getor user which is the function we have inside our model so inside our model file here where we actually go in and we qu the database and grab a user if it does exist so we’re going to grab a user and we do also want to make sure we submit our database connection as well as our username so we can actually go and say we have the username up here which was the second parameter by the way so we do need to go in front and also grab our PDO connection again the PDO connection is inside our database file which is linked up here so we can actually grab this one directly and just like that we now have a variable that has the results from the database query where we go in and actually try to grab the user so now we can use this in order to complete our next two error handlers which we did create inside our controller here so we do want to check if the username is wrong and we do also want to check if our password is wrong so after grabbing the data we can run a simple if condition just like up here when it came to the empty inputs and we can check if our username is wrong by simply running this function that we just created inside our controller and then we pass in our results that we just created in order to check if we did have any results from the database if we did not then we want to return a error called loginor Incorrect and incorrect login info and all this does is that it creates a error message that we can grab once we do actually get back to the login form if there was any sort of error messages and then we can display those errors inside the login form so the next one I’m going to check for here is if the passwords actually do match and again we did create a function for checking that so what I can do here is I can go below and I can run another if condition but this time I do want to go in and check if the username is not wrong so if it is actually a user that exists inside the database but also if the password is incorrect and you’re going to notice inside our is password wrong we just pass in our password which was submitted by the user right up here and we also pass in the password from inside our database query so the one we grabbed inside variable result which has a column name as password so with these error handlers here we basically just go in and check if the username exists and if you do actually have the passwords matching inside our database so with that we can now go back down inside our if condition that checks for any sort of Errors inside the errors array and I’m actually going to go and delete our session variable called sign upore data and also the actual array called sign up data and the reason for that is I do think that when a person types something incorrect inside a login form I don’t think that we should retype what they submitted into the login form I think they have to start completely over with the username and a password so it’s a little bit different than the signup form where if they wrote One Thing incorrect but the email was correct and everything else then we just you know we don’t want them to retype everything again cuz a sign up phone can be lengthy but in this case here I do think that that they should just type everything again and again just to go over what exactly this code does because you may not remember it from the last episode The require once where you grab the config unor session basically just goes in and grabs our session config file which goes in and updates the session ID once in a while inside the cookie inside your browser session security thing so to speak so inside our config session you can see that we you know we set out some parameters and you know we update the cookie every once in a while every 30 minutes so um so so now what we need to do here is a security thing which is that whenever you have any sort of changes happening when you lck in a user inside a website or something else that you know maybe some uh roles have changed inside the the website what you want to do is you want to make sure you always update the session ID cookie again when you make these changes so when you log a user into the website then update the session ID cookie because that is just a good habit to have so you don’t have to wait every 30 minutes you know from inside the config file just do it whenever something changes inside the website but now we’re going to do this in a slightly different way because if I were to go back inside my config file you can see that the way we did it before is by running a session regenerate ID which is how we can take the current session ID that is inside our website and we then regenerate it because if someone were to grab the session ID and stole it from us then we can regenerate it to change it so now it’s no longer usable but something we can actually when it comes to a login system is we can actually grab our users ID and combine that with our session ID from inside our session and this is not something you have to do this is something we’re going to do together in this episode here just so I can show you how to do it uh but essentially there comes a couple of benefits to having the users ID inside the session ID for example because you can associate some data together with the actual user that is using a particular session ID um so there is some benefits to it and again I’m just going to show you how to do it and then you can determine whether or not you want to use it or not again it’s just an exercise to show you some different things so what we’re going to do is we’re going to go back inside our login. in phsp file and right below where we check for these error messages the next thing I want to do is I do want to create a new variable I’m going to call this one new session ID make sure we spell that correctly and I’m going to set it equal to a function that I do think I’ve mentioned before in the previous episode which is called called session uncore creatore ID so this is not a session uncore regenerate ID this is a session _ create ID which is a little bit different so now this will actually create a entirely new ID instead of just regenerating the existing ID we have current inside the website and what we can do then is we can actually append our users ID together with this newly created ID that we just created so if I were to go below here I can go ahead and say I want to create a variable called session ID and I’m going to set it equal to our new session ID that we just created up here and then I’m just simply going to append a ID that we got from our variable results a little bit further up inside our code because we did actually grab the users’s data from inside the database so if we were to grab the variable results go down I can actually append the ID of the user together with our session ID so again we’re creating a new session ID which is just for security just like we regenerate a new session ID we now just create a new one and then we just add our users ID together with our session ID using a underscore just so we can separate those uh the ID from the users ID and now all we have to do is just go below here and say we want to run a session ID function which goes in and actually sets our session ID equal to a ID that we give it inside the parentheses here so this case we can go in and tell it to set our session ID equal to what we just created up here with the users ID so again a small trick here just to you know create a new session ID inside our website using also the users’s ID from the user we tried to log in inside our database here and there is something we have to do here as well in regards to this because right now we do have our users ID together with our session ID but what happens in 30 minutes when I go inside the config session code and it automatically updates the session ID in 30 minutes well when it does that we no longer have the users ID part of our session ID because it is just regenerating the the session ID without appending the users’s ID in 30 minutes so that is something we have to change inside our config file so what we need to do here is we do actually need to check if the user is currently logged in or if they’re not logged into the website because if they are logged into the website side then I do want to make sure that when we regenerate the session ID that we do so using the user’s current ID so inside our if condition at the bottom here where we go in and update this every 30 minutes I do want to create another if condition so again now we’re going to start to have some nesting going on but I think it’s okay for now and I’m simply going to go inside my parentheses and check if we currently have a user locked into the website by checking if we have a current session variable that is equal to user on the _ ID or at least that is named user uncore ID so by going in here we can say we have a variable underscore session which is a super Global we have talked about this one plenty of times by now so we go in and we check if we have a user ID which we haven’t created yet by the way this is something we will create once we actually log the user in instead of login.in phsp file just know for now that we will have a session variable called user ID when the user is logged in okay then I’m going to create a else condition so we’re going to say else and inside the else condition we want to run the code that is going to get run when the user is not logged into the website so that would actually be the code that we have here already so it would to copy paste that inside my else condition this is now getting run if the user is not logged into the website but what if the user is logged into the website because now we need to change things a little bit here all we have to do is we need to go inside the if condition paste in the same code again but instead of running I’ll regenerate on _ session ID which is a function that we created down here we’re going to create a new function that is going to go in and append the users’s ID once you do actually regenerate the ID inside once we’re logged into the website so all we need to do here is create a new function called regenerate unor session idore loged in and the same thing down here for regenerate uncore session ID logged in then we scroll down inside our function here and just copy paste it because we do need to have another function for when we’re logged in so I’m going to change the name of one of these to logged in and we’re going to keep the same code as we have in here because we do still need to use this code uh we do need to make sure we write true inside these parentheses here though inside both functions because we forgot to do that in the last episode so after regenerating the ID we’re going to do the exact same thing as we did inside our login that in the PHP file so I’m just going to go in I’m going to go down here where we actually generated the ID using our ID from the user so I’m going to copy that go back in paste it in but we do need to change one thing here which is that right now we don’t have a result called ID because that is specific to that particular file in there uh but we do have a session variable that does exist called user ID if the user is logged in so we can actually take that one go down here create a new variable we can call this one user ID and set it equal to our session variable called user ID and then we can use that ID instead of our result from the database because like I said it’s inside that other file so we can’t access this variable specifically uh but we can access a user ID from our session variable if we’re logged into the website so again just to recap here we’re going in regenerating the ID which we technically don’t have to we could delete this if we wanted to we’re grabbing the user ID from our session variable if we’re logged in then we’re going down and creating a new session ID by using this session create ID then we’re going in and saying that we want to set a session ID equal to the new session ID we just created and the user ID from the user and then we’re just simply going in and saying that we want to set the session ID equal to this session ID up here and then we update the time for when we last regenerated the session ID because now it needs to wait 30 minutes until it will automatically go in and again regenerate this using the users ID if we’re logged in this may be the most confusing part of this video by the way again just know that we’re going inside the website and updating the session ID by adding the users ID with it as well to create some faint new things we can do potentially if we wanted to do that in the future uh we’re not going to do anything with it in this video here it’s just to show you that you can do it so inside our login. in.php file at this point here we do actually have a user that tried to sign up with a username that exists inside the database and also a password that matches with the password inside the database so what we can do is we can actually sign up the user inside our website the way we’re going to do that is first of all by setting the appropriate session variables so we’re going to say we have a session variable and we’re going to call this one user uncore ID which by the way inside the config uncore session we are checking for if the user locked in into the website and we’re going to set this one equal to the ID from inside our database so we can actually go ahead ahead and set this one equal to our result from our database quy and the ID column from inside the database which is the ID of this particular user here so I can copy paste this down and then we might also include maybe the username so the user undor username just so we have it available to us so we don’t have to quote the database every single time if I just want to graph the username of the user uh so with this we can set it equal to username because that is the name of our database column but now I do want to do something else here because we might actually take this username and print it out in our website somewhere we might try to Echo it out because I want to show the user who they’re logged in as right now inside the website uh so we do need to make sure we do some security so we’re going to use HTML special characters and make sure we run a sanitation of variable result just to make sure everything has been sanitized to avoid any sort of potential crossy scripting that might be happening inside the website here and with that I do want to do one more thing which is to go in and actually reset the timer for when we have to update our session ID because we just did so so why not go in and just reset the timer for that so I’m going to go inside my config unor session and I’m just simply going to go down and grab our session variable called last regeneration which is equal to time copy that entire lineer code go back in and right below here where we actually to create these session variables I’m just going to go and create that one as well by setting it equal to the current time so now we reset the time so that in 30 minutes it’s going to update itself again and just like that we now have a login system so we can actually go below here create a header function to send the user back to the front page with a login equal to success message uh we can also go ahead and close off these statements and our connection because the prepared statement and the connection it does get automatically closed but it is just a good habit best practice so to speak to actually close it manually inside your code uh so we’re going to go and do that as well well so right below the header function I’m just going to say we want to close off the PDO and the prepared statement and the last thing we’re going to do is to create a die function essentially just terminating the script at this point here so now we have a login system that should be working inside our website but let’s actually go back inside our index page and make sure if we have any sort of error messages related to the login form for example submitting the wrong password or a username that doesn’t exist inside the database then we want to Output that error message inside our form or at least below the form inside our front page so going below the login form I’m going to go down and open up my PHP tags and inside here we’re going to refer to a function called check linore errors and this is a function we haven’t created yet because this is going to actually output something inside the website which means that it needs to go inside our view so going inside our loginor view you can see that right now we have nothing so what I’m going to do to begin with here is open up the PHP tags and open up the strict mode and all that U so I’m going to go inside one of the other ones that I have here and just kind of open up what we have here you know so we have the beginning of the PHP tag we have the declare strict types and then we’re going to create the function that we just had inside our index page I’m just going to go and drag this over so we can actually see it and I’m going to copy the function name inside the index page go back inside my loginor view and say I want to create a function that has a name set to check unor linore for errors so inside this function we’re going to run a if condition and I want to check if we have a certain session variable set currently inside the website so if we have a is set parenthesis and we have a session variable that is called error uncore login so errors uncore login and this is something we actually do need to change inside our login. in PSP file so if we would to copy the name here go inside the login the PHP and scroll up to our error messages you can see that right now we’re creating a session variable called errors unor signup because we copy pasted this from our signup form so we do need to make sure we’re go and change that to errors unor login and then if we have any sort of error messages then I want to go inside this if condition and simply create a variable called erros and set it equal to the session variable that has all the errow messages inside of it so we’re just going to set equal to variable uncore session errors uncore lugin because by doing that we can now go below here and we can actually unset the session variable because remember if there’s any sort of information inside our session variables that is no longer needed then we need to make sure we unset it you know to clean it out so in between here I’m just going to go and Echo out a break just to get some distance between our form and the error message that we’re going to print out and then I’m going to run a for each Loop because we do actually want to go in and make sure that we take all the error messages inside our variable errors and print print them out below each other inside our login form or below the login form just like we did when it came to the signup form so inside my for each Loop I’m simply going to Echo out a paragraph that has a class set inside of it which I did style inside my stylesheet and I’m just simply going to print out a error so I’m going to go inside our parameters up here for the for each Loop and I’m going to say that I have a errors array and I want to refer to error whenever I refer to one of these errors inside the array and then because I refer to to error in between the paragraph down here we just simply spit out the error that we might be getting inside our form so with that we now just need to create a success message if we did actually not have any sort of Errors so going below here I can create a else if and I’m just simply going to check if we had any sort of success message inside the URL when we did send the user back with a you know lockin success message so we’re going to use a get method in order to grab a login and we’re going to check if it is equal to success and and again just to show you where this happens if we were to go back inside our login. in. PSP file at the bottom here when we do access send the user back you can see that inside the URL we have lugin equal to success and that is what we’re checking for here and now we need to do one more thing before we can actually test this out because right now inside the index page we are referring to a check unor linore errors which is inside our view file uh but we did not actually link to our view file at the top here so we need to go up here and say we have a lock inore view. in the PHP file so now we do actually have access to this function in here so if we were to go inside our website and let’s go ahead and sign up as a new user because I don’t actually remember the password from the user we created in last episode so let’s just go ahead and go in here and say we have John do and we’re going to say we have a password that is one 12 three which is most likely what I used in the last episode as well so John at gmail.com I’m just going to go and sign up this new user and then you can see oh sign up success and now we can actually go inside our login form and we can test this out so if we were to say John do with capitalized d and capitalized J and then one two three log in then you can see we get login success if I were to try and go in and actually log in with something that does not exist inside the database let’s actually go and leave this one empty you can see oh fill in all Fields incorrect login info uh if we were to pick something in both Fields then you can see we get incorrect login info because saf does not exist inside our database as a user if I were to use John Doe John do but use a incorrect password then you can see we get incorrect login info because this was not the correct password so everything is working exactly like intended but now a question that people may have is okay so we have this login system but how do we change content inside the website once we’re logged in cuz that is important to do too before we do that let’s actually go and create a log out button because I do want to be able to lock out the user as well because right now we’re just logging in as one user and then trying to lock in as another user but we’re not actually locking out at any point so going inside the index page here I’m going to create a new form I’m just going to call this one log out so I’m going to copy paste this one and let’s go ahead and put this one at the bottom so we’re going to say log out like so and we’re going to refer to a log out. in the PHP file and we’re not going to have any sort of inputs in here we’re just going to have a logout button then I’m going to go in and actually create a new file inside my includes folder so I’m going to say new file call it log out. in.php and inside this file here we’re just going to open up our PHP tags go down and say we want to create a session uncore start because we do want to start a session in order to actually destroy it and then below we’re going to go and say session uncore unset and then we’re going to say session uncore destroy and then we can actually send the user back to the front page so we can actually copy paste that from let’s say I’ll login. in.php file so we want to go down to the bottom here we have a header that sends the user back and we have a die uh function so we can copy those and paste those in so if I were to go inside my website refresh everything you can see we have a log out button so if we were to actually log in using John do one two 3 log in then you can see we are logged in as John do well you can’t actually see it cuz you can’t see if we’re logged in or not uh but we do get a login success message and then if I want to I can loog out down here and then I will be locked out again so now the question is how do we change content inside the website when we’re locked in when we’re not logged in you know because we need to change content because that’s the whole point right we create a login system so we can log a user in and then change content inside the website so they might have a profile page or something um so the way we can do that is if I were to go back inside our view for the login system is I’m actually going to go and create a function to print out the username when we’re logged in so we can actually see the username inside the website and it says you are logged in as and then the name of the username so I’m going to create a basic function I’m just going to copy paste it here which is called output username and then inside we have a if condition that simply goes in and checks or we currently logged in by checking if we have a user ID because if that exists that means we’re logged into to the website and if we’re logged in we’re just simply going to go in and output you are logged in as and then we’re going to grab the username from inside our session variable again that’s why we wanted to set that as a session variable when we did actually log in previously and if we’re not logged in we’re just simply going to say you are not logged in and then we can use this function we can copy it go inside our index page and just simply output it somewhere maybe above our login form so we can say we have a let’s create a H3 and we’re going to go and say we want to have a PHP tag opening and closing in here and then we’re just simply going to run this function here so anytime you want to change anything inside the website if you’re logged into the website again all you have to do is run a if condition that checks if currently we have a session variable that is called user ID and that is all you need to check for if that exist then change the content Again by echoing something out or creating some HTML or something um so if I were to go back inside the website you can now see that when I refresh it says you are not logged in cuzz we’re not logged in but if if we were to go down here and log in as John Doe 1 2 3 log in then you can see we get you are logged in as John Doe and again if I were to go down to the bottom here log out then you can see oh you are not logged in cuz we destroyed all the session data with the session variable and now we’re no longer logged into the website and we can do the same thing when it comes to the forms so if we were to go in here and say you know what let’s go inside our view and just copy this if condition go inside our index page and let’s say we only want to see the login form if we are currently not logged into the website because there’s no need to have a login form if we’re already logged in right so if we were to go in here we can go ahe and open up the PHP tags and close it off again we’re going to paste in the if condition here and then we can just go in and actually include the form inside the if condition for when we’re not logged in so what we can do here is we can say okay so if we are not currently logged in and instead of echoing out you are logged in as and then the username we can just go in and we can copy paste the form and paste it inside our condition here so I’m going to copy the form delete it go inside and I’m just going to go and close off my uh PHP tags here just because it makes a little bit easier so again opening and closing the PHP tags wrapped around the closing bracket and also opening and closing it wrapped around the first if condition line of code here because that allow for us to go in and paste in HTML and still have it be part of the PHP again this is PHP syntax good practices 101 so instead of you know putting this in as a string by echoing all of this out can just write HTML code directly Inside by simply opening and closing the closing bracket and the same thing for the opening bracket so if I were to go in here and do this then you can see that if I were to go inside the website refresh it right now we’re not logged into the website so we can see the form but if we were to go in and log in as John do 1 2 3 then you can see that oh okay the login form disappeared cuz we no longer need to see it and that is how you can simply go inside a website and change content based on if you’re logged in or if you’re not logged in and you can do the same thing for the sign up form that could also disappear by the way and the same thing for the log out form maybe that should not be there when you’re not logged into the website because it doesn’t make any sort of sense so with that I hope you enjoyed this little episode on how to create a login system and I’ll see you guys in the next video [Music]

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • Linux Terminal Mastery: Commands, Shells, and File Systems

    Linux Terminal Mastery: Commands, Shells, and File Systems

    This text is a transcript of a Linux crash course aimed at beginners. The course, offered by Amigo’s Code, covers the fundamentals of the Linux operating system, including its history, features, and various distributions. It guides users through setting up a Linux environment on Windows and macOS using tools like UTM and VirtualBox. The curriculum further explores essential Linux concepts like file systems, user management, and commands, including the use of the terminal. The course then introduces Bash scripting, covering variables, conditionals, loops, functions, and the creation of automated scripts. The goal of the course is to equip learners with the skills necessary to effectively use Linux for software development, DevOps, or system administration roles.

    Linux Crash Course Study Guide

    Quiz

    1. What is Linux and who developed it?

    Linux is a powerful and flexible operating system developed by Linus Torvalds in 1991. Unlike operating systems such as Windows and macOS, Linux is open source and allows developers around the world to contribute and customize.

    2. What are the key features of Linux that make it a preferred choice for servers?

    The key features are stability, security, the ability to be customized to specific needs, and performance. Due to these factors, servers worldwide often prefer Linux.

    3. What is a Linux distribution? Name three popular distributions.

    A Linux distribution is a specific version or flavor of the Linux operating system tailored for different purposes. Three popular distributions are Ubuntu, Fedora, and Debian.

    4. Explain what UTM is and why it’s used in the context of the course.

    UTM is an application that allows users to securely run operating systems, including Linux distributions like Ubuntu, on macOS. It’s used in the course to demonstrate how to set up and run Linux on a Mac.

    5. What is VirtualBox and how is it used for Windows users in the course?

    VirtualBox is a virtualization software that allows Windows users to install and run other operating systems, including Linux distributions like Ubuntu, within a virtual environment.

    6. What is the difference between a terminal and a shell?

    A terminal is a text-based interface where users type commands and view output. A shell is a program that interprets and executes those commands, acting as an intermediary between the user and the operating system.

    7. What is Zsh, and why is it used in this course?

    Zsh (Z shell) is an extended version of the Bourne shell, known for its advanced features like auto-completion, spelling correction, and plugin support. It is used in the course to provide a more customizable and efficient command-line experience.

    8. What is Oh My Zsh, and what does it offer?

    Oh My Zsh is an open-source framework for managing Zsh configuration. It includes numerous helpful functions, helpers, plugins, and themes to enhance the Zsh experience.

    9. Explain the command sudo apt update. What does it do?

    sudo apt update updates the package index files on the system. These files contain information about available packages and their versions. The sudo ensures the command is executed with administrative privileges.

    10. What is a Linux command and what are its three main parts?

    A Linux command is a text instruction that tells the operating system what action to perform. The three main parts are the command itself, options (or flags) which modify the command’s behavior, and arguments, which specify the target or input for the command.

    Quiz Answer Key

    1. What is Linux and who developed it?

    Linux is a powerful and flexible operating system developed by Linus Torvalds in 1991. It’s open-source and allows for worldwide contributions.

    2. What are the key features of Linux that make it a preferred choice for servers?

    Key features include stability, security, customizability, and performance, making it ideal for servers.

    3. What is a Linux distribution? Name three popular distributions.

    A Linux distribution is a specific version of Linux. Ubuntu, Fedora, and Debian are examples.

    4. Explain what UTM is and why it’s used in the context of the course.

    UTM lets macOS users run other operating systems, including Ubuntu. The course uses it to set up Linux on a Mac.

    5. What is VirtualBox and how is it used for Windows users in the course?

    VirtualBox is a virtualization software. It allows Windows users to run Linux within a virtual environment.

    6. What is the difference between a terminal and a shell?

    A terminal is the interface for typing commands. The shell interprets and executes these commands.

    7. What is Zsh, and why is it used in this course?

    Zsh is an improved shell with features like auto-completion. The course uses it for a better command-line experience.

    8. What is Oh My Zsh, and what does it offer?

    Oh My Zsh is a framework for managing Zsh configuration. It provides themes and plugins to customize the shell.

    9. Explain the command sudo apt update. What does it do?

    sudo apt update updates package lists, requiring administrative privileges through sudo.

    10. What is a Linux command and what are its three main parts?

    A Linux command is a text instruction to the OS. It consists of the command, options, and arguments.

    Essay Questions

    1. Discuss the advantages of using Linux as a server operating system compared to Windows Server. Consider factors such as cost, security, and customization.
    2. Explain the significance of open-source development in the context of Linux. How does the collaborative nature of its development benefit the Linux community and users?
    3. Compare and contrast the roles of the terminal and the shell in a Linux environment. How do they interact to enable users to control the operating system?
    4. Describe the process of installing Ubuntu on both macOS (using UTM) and Windows (using VirtualBox). What are the key differences and considerations for each platform?
    5. Discuss the importance of Linux file permissions and user management in maintaining a secure and stable system. Provide examples of how incorrect permissions can lead to security vulnerabilities.

    Glossary of Key Terms

    • Linux: A powerful and flexible open-source operating system kernel.
    • Distribution (Distro): A specific version of Linux that includes the kernel and other software.
    • Open Source: Software with source code that is publicly available and can be modified and distributed.
    • Terminal: A text-based interface used to interact with the operating system.
    • Shell: A command-line interpreter that executes commands entered in the terminal.
    • Zsh (Z Shell): An extended version of the Bourne shell with advanced features and plugin support.
    • Oh My Zsh: An open-source framework for managing Zsh configuration.
    • Command: An instruction given to the operating system to perform a specific task.
    • Option (Flag): A modifier that changes the behavior of a command.
    • Argument: Input provided to a command that specifies the target or data to be processed.
    • Sudo: A command that allows users to run programs with the security privileges of another user, typically the superuser (root).
    • UTM: An application that allows you to run operating systems on macOS devices.
    • VirtualBox: Virtualization software that allows you to run different operating systems on your computer.
    • Operating System: The software that manages computer hardware and software resources.
    • Server: A computer or system that provides resources, data, services, or programs to other computers, known as clients, over a network.
    • Root Directory: The top-level directory in a file system, from which all other directories branch.
    • File System: A method of organizing and storing files on a storage device.
    • Directory (Folder): A container in a file system that stores files and other directories.
    • GUI: Graphical User Interface. A user interface that allows users to interact with electronic devices through graphical icons and visual indicators such as secondary notation, as opposed to text-based interfaces, typed command labels or text navigation.

    Linux Crash Course: A Beginner’s Guide

    Okay, here’s a detailed briefing document summarizing the main themes and ideas from the provided text:

    Briefing Document: Linux Crash Course Review

    Overall Theme: This document is a transcript of a video presentation promoting a “Linux Crash Course.” The course aims to take complete beginners to a point of understanding and mastering Linux, particularly in the context of software engineering, DevOps, and related fields. The presenter emphasizes that Linux is a fundamental skill in these areas.

    Key Ideas and Facts:

    • Linux Overview:Linux is described as a “powerful and flexible operating system” developed by Linus Torvalds in 1991.
    • A key feature of Linux is that it’s “open source,” with developers worldwide contributing to its improvement and customization.
    • Linux boasts “stability, security, the ability of changing it to your needs, and performance.” This makes it preferred for servers globally.
    • Linux is used by “internet giants, scientific research companies, financial institutions, government agencies, educations,” and pretty much every single company out there.
    • Amigo’s code is actually deployed on a Linux server
    • Linux is versatile and used on “smartphones to service and also Raspberry Pi.”
    • Linux Distributions:Linux has different “flavors” called distributions.
    • Ubuntu is highlighted as the “most popular flavor of Linux.” It comes in server and desktop versions (with a graphical user interface).
    • Other distributions mentioned include Fedora, Debian, and Linux Mint.
    • Companies often customize Linux distributions to meet their specific needs.
    • Course Promotion:The presenter encourages viewers to subscribe to the channel and like the video.
    • The full 10-hour course is available on their website, with a coupon offered.
    • The course aims to “make sure that you become the best engineer that you can be.”
    • The course has a “Windows users as well as Mac users”
    • Setting up Linux (Ubuntu) on Different Operating Systems:Mac: The presentation details how to install Ubuntu on a Mac using an application called UTM (a virtualization software).
    • Windows: Installation of Ubuntu through VirtualBox.
    • Understanding the Terminal:The terminal allows users to interact with the operating system by entering commands.
    • Understanding the shellshell is a program for interacting with the operating system.
    • Z Shell (zsh)zsh also called the zshell is an extended version of Bor shell with plenty of new features and support for plugins and themes
    • Linux CommandsThey are case sensitive
    • Linux File SystemThe Linux file system which is the hierarchical structure used to organize and manage files and directories in a Linux operating system
    • Files and PermissionsLinux is a multi-user environment where allows us to keep users files separate from other users
    • Shell scriptingIt is essentially a command line interpreter

    Quotes:

    • “If you don’t know Linux and also if you are afraid of the terminal or the black screen then you are in big trouble so this course will make sure that you master Linux”
    • “Linux is a must and don’t you worry because we’ve got you covered”
    • “Linux it’s a powerful and flexible operating system”
    • “Linux is open source developers around the world contribute to improve and customize the operating system”
    • “servers around the world prefer Linux due due to its performance”
    • “Linux is open source but it’s also used on a wide range of devices from smartphones to service and also Raspberry Pi”
    • “Ubuntu is the most popular flavor out there”
    • “At Amigo’s code we want to make sure that you become the best engineer that you can be”
    • “So many original features were added so let’s together in install zsh and as you saw the default shell for Mac OS now is zsh or zshell”
    • “We’ve got Bash as well as chh Dash KS sh T C CH and then zsh”

    Potential Audience:

    • Beginners with little to no Linux experience.
    • Software engineers, DevOps engineers, backend/frontend developers.
    • Individuals seeking to enhance their skills and career prospects in the tech industry.

    In summary: The document outlines a Linux crash course that aims to provide individuals with the necessary skills to confidently navigate and utilize the Linux operating system in various professional tech roles. It covers core concepts, practical setup, and promotes the course as a means to become a proficient engineer.

    Linux and Shell Scripting: A Quick FAQ

    FAQ on Linux

    Here is an 8-question FAQ about Linux and shell scripting, based on the provided source material.

    1. What is Linux and why is it important for aspiring engineers?

    Linux is a powerful and flexible operating system developed by Linus Torvalds in 1991. Its open-source nature allows developers worldwide to contribute to its improvement and customization. Its stability, security, and performance make it a preferred choice for servers and various devices, ranging from smartphones to Raspberry Pi. For aspiring software, DevOps, or backend engineers, understanding Linux is crucial because most companies deploy their software on Linux servers, making it an essential skill.

    2. What are Linux distributions and how do they differ?

    Linux distributions (distros) are different “flavors” of the Linux operating system, each customized to suit specific needs. Popular distributions include Ubuntu, Fedora, Debian, and Linux Mint. Ubuntu, particularly its server and desktop versions, is a popular choice for many, while other distributions cater to specific requirements in different companies. The source material mentions Ubuntu will be used in the course.

    3. How can I install Linux (Ubuntu) on my Mac?

    On a Mac, Ubuntu can be installed using virtualization software like UTM. First, download and install UTM from the Mac App Store. Then, download the Ubuntu server ISO image from the Ubuntu website. Within UTM, create a new virtual machine, selecting the downloaded ISO image as the boot source. Configure memory and disk space as needed, and start the virtual machine to begin the Ubuntu installation process. The source material also highlights the Ubuntu gallery in UTM.

    4. How can I install Linux (Ubuntu) on my Windows machine?

    On Windows, you can use VirtualBox. The steps include downloading and installing VirtualBox. Then download the Ubuntu desktop ISO image from the Ubuntu website. Create a new virtual machine in VirtualBox, selecting the downloaded ISO image. Configure memory and disk space. Install ubuntu to the VM.

    5. What is the difference between the Terminal and the Shell?

    The terminal is a text-based interface that allows you to interact with the operating system by entering commands. It provides the prompt where commands are entered and outputs the results. The shell, on the other hand, is the program that interprets the commands entered in the terminal and executes them against the operating system. Shells include Bash, Zsh, Fish, and others.

    6. What is Zsh and how do I switch from Bash to Zsh?

    Zsh (Z shell) is an extended version of the Bourne shell, known for its advanced features like auto-completion, spelling correction, and a powerful plugin system. To switch from Bash to Zsh, first install Zsh using the command sudo apt install zsh. Then, change the default shell using the command chsh -s /usr/bin/zsh. After rebooting the system, Zsh will be the default shell. Oh My Zsh can be used to configure Zsh.

    7. What are Linux commands, options, and arguments?

    Linux commands are text instructions that tell the operating system what to do. They are case-sensitive. A command can include options and arguments that modify its behavior. For example, in the command ls -a ., ls is the command, -a is an option (for showing hidden files), and . is the argument (specifying the current directory).

    8. What are user types and how do permissions work?

    Linux is a multi-user environment with two main types of users: normal users and the superuser (root). Normal users can modify their own files but cannot make system-wide changes. The superuser (root) can modify any file on the system. Permissions control access to files and directories. The ls -l command displays file permissions, divided into three sets: user, group, and others. Each set includes read (r), write (w), and execute (x) permissions, dictating what actions each user type can perform on the file.

    Understanding Linux: Features, Usage, and Commands

    Linux is a powerful and flexible open-source operating system that was developed by Linus Torvalds in 1991 and has since become a robust platform used worldwide. Here’s an overview of some key aspects of Linux:

    • Open Source Linux is open source, meaning developers can contribute to improving and customizing it.
    • Key Features Stability, security, customizability, and performance are key features. Its flexibility and security make it a preferred choice for companies.
    • Usage Linux is used by internet giants, scientific research companies, financial institutions, government agencies, and educational institutions. Many companies deploy their software on Linux.
    • Distributions Linux has different versions called distributions, with Ubuntu being the most popular. Other distributions include Fedora, Debian, and Linux Mint.
    • Terminal In Linux, the terminal (also known as the command line interface or CLI) is a text-based interface that allows interaction with the computer’s operating system by entering commands. It provides a way to execute commands, navigate the file system, and manage applications without a graphical user interface.
    • Shell A shell is a program that interacts with the operating system. The terminal allows users to input commands to the shell and receive text-based output from the shell operations. The shell is responsible for taking the commands and executing them against the operating system.
    • File System The Linux file system is a hierarchical structure that organizes and manages files and directories. It follows a tree structure with the root directory at the top, and all other directories are organized below it.
    • Commands Linux commands are case-sensitive text instructions that tell the operating system what to do.
    • Shell Scripting Shell scripting automates tasks and performs complex operations by creating a sequence of commands. A shell script is saved with the extension .sh.

    Shell Scripting Fundamentals in Linux

    Shell scripting is a way to automate tasks and perform complex operations in Linux by creating a sequence of commands. It involves writing scripts, typically saved with a .sh extension, that contain a series of commands to be executed.

    Key aspects of shell scripting include:

    • Bash Bash (Born Again Shell) is a command line interpreter used to communicate with a computer using text-based commands.
    • Editor A text editor is needed to write scripts, which could be a simple editor like Vim or a more feature-rich option like Visual Studio Code.
    • Shebang The first line of a shell script typically starts with a “shebang” (#!) followed by the path to the interpreter (e.g., #!/bin/bash). This line tells the operating system which interpreter to use to execute the script.
    • Variables These are containers for storing and manipulating data within a script. In Bash, variables can hold various data types like strings, numbers, or arrays.
    • Conditionals These allow scripts to make decisions based on specific conditions, executing different blocks of code depending on whether a condition is true or false.
    • Loops Loops enable the repetition of instructions. for and while loops can iterate over lists, directories, or continue tasks until a condition is met.
    • Functions Functions group a set of commands into a reusable block, promoting code modularity and organization.
    • Comments Adding comments to scripts is considered a best practice as it helps in understanding the script’s purpose, functionality, and logic. Comments are lines in a script that are not executed as code but serve as informative text.
    • Passing Parameters Bash scripts can receive input values, known as parameters or arguments, from the command line, allowing customization of script behavior. These parameters can be accessed within the script using special variables like $1, $2, $3, etc. The special variable $@ can be used to access all parameters passed to the script.
    • Executable Permissions Scripts are executables that require giving executable permissions using chmod.

    To run a shell script:

    1. Save the script with a .sh extension.
    2. Give the script executable permissions using the chmod +x scriptname.sh command.
    3. Execute the script by using its path. If the script is placed in a directory included in the PATH environment variable, it can be run by simply typing its name.

    Linux File Management: A Command-Line Guide

    File management in Linux involves organizing, creating, modifying, and deleting files and directories. This is primarily done through the command-line interface (CLI) using various commands.

    Key aspects of file management include:

    • Linux File System: The file system is a hierarchical structure with a root directory (/) at the top, under which all other directories are organized.
    • Essential Directories:
    • /bin: Contains essential user commands.
    • /etc: Stores system configuration files.
    • /home: The home directory for users, storing personal files and settings.
    • /tmp: A location for storing temporary data.
    • /usr: Contains read-only application support data and binaries.
    • /var: Stores variable data like logs and caches.
    • Basic Commands
    • ls: Lists files and directories. Options include -a to show hidden files and -l for a long listing format that includes permissions, size, and modification date.
    • cd: Changes the current directory. Using cd .. moves up one directory level. Using cd – flips between the previous and current directory.
    • mkdir: Creates a new directory. The -p option creates nested directories.
    • touch: Creates a new file.
    • rm: Removes files.
    • rmdir: Removes empty directories.
    • cp: Copies files.
    • File Permissions: Linux uses a permission system to control access to files and directories. Permissions are divided into three categories: user, group, and others. Each category has read (r), write (w), and execute (x) permissions. The ls -l command displays file permissions in a long listing format.
    • Working with Files:
    • To create an empty file, use the touch command.
    • To create a file with content, use the echo command to redirect a string into a file.
    • To view the contents of a file, you can use a text editor or command-line tools like cat.
    • Working with Directories:
    • To create directories, use the mkdir command.
    • To remove empty directories, use the rmdir command.
    • To remove directories and their contents, use the rm -rf command.
    • Navigating the File System To navigate, utilize the cd command followed by the directory path.

    It is important to note that commands are case-sensitive.

    Linux User and File Permissions Management

    User permissions in Linux control access to files and directories in a multi-user environment. Here’s an overview:

    • Types of Users There are normal users and superusers (root).
    • Normal users can modify their own files but cannot make system-wide changes or alter other users’ files.
    • Superusers (root) can modify any file on the system and make system-wide changes.
    • Commands for User Managementsudo: Executes a command with elevated privileges.
    • useradd -m username: Adds a new user and creates a home directory.
    • passwd username: Sets the password for a user.
    • su username: Substitutes or switches to another user.
    • userdel username: Deletes a user.
    • File Permissions Permissions determine who can read, write, or execute a file.
    • The ls -l command displays file permissions in a long listing format. The output includes the file type, permissions, number of hard links, owner, group, size, and modification date.
    • The file type is the first character. A d indicates a directory, and a – indicates a regular file.
    • Permissions are divided into three sets of three characters each, representing the permissions for the user (owner), group, and others.
    • r means read, w means write, and x means execute. A – indicates that the permission is not granted.
    • The first three characters belong to the user, the second three to the group, and the last three to everyone else.

    Essential Linux Terminal Commands

    Linux terminal commands are case-sensitive text instructions that tell the operating system what to do. These commands are entered in the terminal (also known as the command line interface or CLI), allowing you to interact with the operating system. The terminal provides a way to execute commands, navigate the file system, and manage applications without a graphical user interface.

    Here are some basic and essential commands:

    • ls: Lists files and directories.
    • ls -a: Includes hidden files.
    • ls -l: Uses a long listing format, displaying permissions, size, and modification date.
    • cd: Changes the current directory.
    • cd ..: Moves up one directory level.
    • cd -: Flips between the previous and current directory.
    • mkdir: Creates a new directory. The -p option creates nested directories.
    • touch: Creates a new file.
    • rm: Removes files.
    • rmdir: Removes empty directories.
    • cp: Copies files.
    • sudo: Executes a command with elevated privileges.

    Each command may have options and arguments to modify its behavior. To understand how to use a command effectively, you can refer to its manual for instructions.

    Linux For Beginners – Full Course [NEW]

    The Original Text

    what’s going guys assalamualaikum welcome to this  Linux crash course where I’m going to take you   from complete beginner to understanding Linux this  is a course that abs and I put together and it’s   currently 10 hours which a bunch of exercises  if you don’t know Linux and also if you are   afraid of the terminal or the black screen then  you are in big trouble so this course will make   sure that you master Linux and whether you want to  become a software engineer devops engineer backend   front end it doesn’t really matter Linux is a  must and don’t you worry because we’ve got you   covered if you’re new to this channel literally  just take 2 seconds and subscribe and also smash   the like button so we can keep on providing you  content like this without further Ado let’s off   this video okie dokie let’s go ahead and kick off  this course with this presentation which I want   to go through so that you have a bit of background  about Linux so Linux it’s a powerful and flexible   operating system that was developed by lonus tals  in 1991 so the name Linux comes from the Creator   Linus and since 1991 Linux has grown into a robust  and reliable platform used by millions worldwide   as you’ll see in a second the cool thing about  Linux unlike operating systems such as Windows Mac   OS is that Linux is open source developers around  the world contribute to improve and customize the   operating system and it has a Vibrant Community  of contributors and I’ll talk to you in a second   about distributions as well because it plays a big  part since Linux is open source the key features   of Linux are stability security the ability of  changing it to your needs and performance so   servers around the world prefer Linux due due to  its performance so who uses Linux well interned   Giants scientific research companies financial  institutions government agencies educations and   the platform that you are using right now so  Amigo’s code is actually deployed on a Linux   server so you look at Google meta AWS NASA  and obviously Amigo’s code and pretty much   like every single company out there majority of  them I can guarantee you that their software is   being deployed on Linux it might be a different  flavor of Linux but it will be Linux and the   reason really is because of the flexibility  and it’s secure so this is why companies opt   to choose Linux and the cool thing about Linux  is that it’s open source as I’ve mentioned but   it’s also used on a wide range of devices from  smartphones to service and also Raspberry Pi so   if you’ve ever used a Raspberry Pi the operating  system on this tiny computer is Linux Linux has   something called distributions and these are  different flavors the most popular flavor of   Linux is Ubuntu and you have the iunu server or  the desktop which comes with a graphical user   interface and this distribution is what we’re  going to use and is the most popular out there   but obviously depending on the company that  you work for the software will be deployed on   a different flavor of Linux to customize their  needs but there are also other distributions   such as Fedora Debian Linux Mint and plenty  of others and this is a quick overview about Linux cool before before we actually proceed  I just want to let you know that the actual   10 hour of course is available on our brand  new website and I’m going to leave a coupon   and a link as well where you can basically go  and check for yourself because many of your   students already have engaged with the course  they’ve been learning a lot and to be honest   the positive has been really really great so far  so we are coming up with something really huge   and we decided that Linux had to be part of this  something and here Amigo’s codee we want to make   sure that you become the best engineer that you  can be details will be under the destion of this video okie dokie for the next two sections  we’re going to focus on Windows users as   well as Mac users and just pick the operating  system that you are using and go straight to   that section because the setup will be the  exact same thing so I’m going to show you   how to get Linux and you bu to up and running  on your operating system if you want to watch   both sections feel free to do so uh but in this  course I just want to make sure that there’s no   issues when it comes to Windows or Mac because  there’s a huge debate which uh is better and   also um after those two sections you’ll see  how to rent a server of the cloud okay so   if you don’t to use nor um yunto or Linux on  your local machine but you prefer to rent it   from the cloud I’m also going to show you how  to do so cool this is pretty much it let’s get started in order for us to install Ubuntu on  a Mac operating system we’re going to use this   application called UTM which allows you to  securely run operating systems on your Mac   whether it’s window Window XP which I really  doubt that you’re going to do windows I think   this is Windows 10 maybe you can also run your  buntu which is the one that we’re going to run   and also like old operating systems in here also  Mac as well so you can virtualize Mac and um I’ll   basically walk you through how to use it and  install yuntu right here which is what we need   in order to get up and running with Linux cool  so in here what we’re going to do is click on   download and you can download from the Mac Store  then pretty much save this anywhere so in my case   I’m going to save it on my desktop and just give  a second to download cool then on my desktop I’m   going to open up this UTM DMG there we go and all  I’m going to do is drag this to applications and   job done now let me close this and also I’m  going to eject UTM and also I’m going to get   rid of this UTM file in here and now I’m going to  press command and then space and we can search for   UTM and then I’m going to open and I’m going to  continue and there we go we successfully installed UTM the next thing that we need is to install  Ubuntu navigate to ubuntu.com and in this page   in here we can download yuntu by clicking on  download and then what I want you to do is   let’s together download the Ubuntu server and  I’ll show you how to get the desktop from the   Ubuntu Server so here you can choose Mac and  windows so I’ve got the arm architecture so   I’m just going to choose arm in here if you  are on regular Mac and windows you can just   basically download your Windows server for  the corresponding architecture and operating   system so here I’m going to click on arm and  you can read more about it in here so this is   the I think this is the long-term support 2204 and  then two and right here you can see that you can   download the long-term support or I think this  is the latest version in here so in my case it   doesn’t really matter which version I download so  I’m just going to download the long-term support   in here so this my bugs who knows so here let’s  just download and I’m going to store this onto my desktop now just give it a minute or so so  my internet is quite slow and you can see the   download still uh in progress but once this  finishes I will um come back to you awesome   so this is done also what I want to show you  is within UTM you can click on on browse UTM   gallery or you can get to it via so in here  if I switch to the UTM official website in   here click on gallery and basically this gives  you a gallery of I think the operating systems   which are currently supported so you can see Arch  Linux Debian Fedora Kali Linux which is quite nice   actually and then you have Mac OS you have Ubuntu  I think this is the older version actually you’ve   got the 20.01 which is the long-term support  Windows 10 11 7 and XP so if you want to go   back to olden days feel free to do so but  we just downloaded yuntu from the official   website which is good and also have a look the  architecture in here so arm 64 x64 right so make   sure to pick the one which is corresponding to  you so if you want to have for example Windows   as well feel free to download an experiment or  a different version of Linux so K Linux which   is quite nice actually feel free to do it but  in my case I’m going to stick with traditional   buntu and next what we’re going to do is to  create a virtual machine and have Linux up and running right we have UTM as well as the iso  image in here for Ubuntu let’s create a brand new   virtual machine and in here we want to virtualize  never emulate so here this is slower but can run   other CPU architectures so in our case we want to  virtualize and the operating system is going to be   Linux leave these and check and in here boot ISO  image open up the iso that we’ve just downloaded   right so here browse and I’ve just opened up  the Ubuntu 22.0 4.2 the next step is going to   be continue and here for memory usually you should  give half of your available memory so in my case   I’m just going to leave four gigs I’ve seen that  it works quite well and I do actually have 32 but   I’m not giving 16 so I’m just going to leave four  in here and CPU course I’m G to leave the default   and here if you want to enable Hardware open  Gil acceleration you can but there are known   issues at the moment so I’m not going to choose  it continue 64 gig so this is the size of the dis   continue and here there’s no shared directory path  continue and for the name in here what I’m going   to do is say YouTu and then the version so 20.0  four dot and then two awesome so you can double   check all of these settings and I think they’re  looking good click on Save and there we go so at   this point you can see that we have the VM in here  so we’re going to start it in a second we can see   the status is stopped the architecture arm the  machine memory 4 gig the size this will increase   in a second and there’s no shared directory but  the cd/ DVD is yuntu which is this one in here so   one more thing that I want to do is so before  we play I want to go to settings so in here   click on settings and you can change the name  if you want to in here and uh all I want really   is within this play I’m going to choose retina  mode and this will give me the best performance   cool so save and I’m good to go next let’s go  ahead and install Ubuntu within our virtual machine oky dokie now the next step for us is to  click on play in here or in here and this should   open this window so in here you can see that  currently so I’m just gonna leave the the screen   like this so currently you can see that it says  press option and um I think it’s enter for us to   release the cursor So currently my cursor is not  visible right and the way that I can interact with   this UI is by using my keyboard so the down arror  in here and the app Arrow right so if you want   your cursor back you just press control and then  option I think control option there we go you can   see that now I have the mouse in here cool let me  just close this in here for a second and I’m going   to Center this like so and now what we’re going  to do is try or install Ubuntu Server so I’m going   to press enter on my keyboard so display output  is not active just where a second and we should   have a second screen there we go you can see that  now we have this other the screen and basically   now we can basically configure the installation  process so in my case I’m going to use English UK   and here so for you whatever country you are just  use the correct country basically so here English   UK for me press enter Then the layout and the  variant so for the keyboard I want to leave as   default and at the bottom you can see that I can  flick between done and back so I’m just going to   say done and I’m going to leave the default  so I want the default installation for you Bo   to server not the minimized so just press enter  and here there’s no need to configure the network   connections continue no need to configure proxy  and also the mirror address just leave as default   enter and in here configure a guided storage so  here I’m going to use the entire disk and leave   as default so just with my errors go all the way  to done enter and here now we have the summary   and you can see the configuration basically 60 gig  and I think the available free space is 30 gig and   you can see there and at this point I you sure  you want to continue I’m going to say continue   now for the name I’m going to say Amigos code the  server name I’m going to say Amigos code the usern   name Amigos code the password I’m going to have  something very short and Easy in here and then   go to done continue and I’m not going to enable  yuntu Pro continue continue there’s no need to   install open SSH server because we don’t need to  remote access this server that we are installing   so here done and also we have a list of available  software that we can install so for example micro   Kates nexcloud Docker you can see AWS CLI in here  so a CLI Google Cloud SDK we don’t need none of   these also postgress which is right here so if  you want to install these by all means feel free   to take but for me I’m going to leave everything  as default done and at this point you can see that   what he doing is installing the system so just  wait for a second and I’m going to fast forward   this step oky doie so you can see that the  installation is now complete and at this point   what it’s doing is downloading and installing  security updates so it’s really up to you whether   you want to wait for this or not but in my case  I think it’s you know the best practice for you   to have everything patched and um updated so I’m  just going to wait and then I’ll tell you what are   the next steps so this might take a while so just  sit back and relax all right so this is now done   and you can see that installation is complete and  we can even say reboot now but don’t don’t click   reboot now what we need to do is so basically we  have to close this so again close this window will   kill the virtual machine which is fine okay now  open UTM once more and you can see that we have   the Ubuntu virtual machine in here and if I open  this up once more so all I want to show you is   that this will take us to the exact same screen  to install yuntu server now we don’t want this so   close this and what we have to do is in here  so CD DVD clear so we have to remove the iso   image and at this point feel free to delete this  so here I’m going to delete this and that’s it   cool so this is pretty much the installation for  Ubuntu next let’s get our Ubuntu Server up been running cool so make sure that this CD for/ DVD  is empty before you press continue or before   you press play so let’s just play this there  we go and I can close this and I’m going to   Center things there we go and at this point we  should see something different there we go now   have a look yuntu the version that we installed  and then it says Amigos code login cool so here   what we need to do is I think we have to add  the username which is Amigos code then press   enter followed by by the password so my password  was I’m not going to tell you basically but it’s   a very simple one so here you don’t see the  password that you type so just make sure that   you have the username and the password press  enter and check this out so now we are inside   and we’ve managed to log in cool so at this point  this is actually yuntu server right so there’s no   graphical user interface and um that’s it right  so later you’ll see that when you SSH into the   servers this is what you get right so this black  screen and that’s it now obviously for us I want   to basically install a graphical user interface  so that basically you see the Ubuntu UI and um   the applications I I’ll show you the terminal  and whatnot but in a shell this is yuntu server   so at this point you can type commands so here  for example if you type LS for example just L   and then s press enter nothing happens if you type  PWD so these are commands you learn about these uh   later but if I press enter you can see that I’m  within home/ Amigos code if I type CD space dot   dot so two dots enter you can see that now if I  type PWD I’m within home okay so this is pretty   much the yuntu server and this is a Linux box  that we can interact with but as I said we want   to install a graphical user interface to simplify  things for now and that’s what we’re going to do next within the official page for UTM navigate  to support in here and I’ll give you this link   so you can follow along but basically they give  you the installation Pro process and things that   you should be aware when working with UTM now  one of the things is if we click on guides or   expand you can see that you have the different  operating systems so Debian 11 Fedora Cali yuntu   Windows 10 and 11 so we installed 2204 so let’s  open that and it doesn’t really matter just click   on your BTU and whatever version here um that  you have installed this will be the exact same   thing okay so just select yuntu anything that says  going to in here cool so if I scroll down in here   so they have a section so we’ve done all of this  creating a new virtual machine and basically here   installing you B to desktop if you install you B  to server then at the end of the installation you   will not have the graphical user interface to  install we need to run these commands in here   so sudu apt and then update and then install and  then reboot awesome let’s go ahead and run these   commands cool so in here within in Yun to server  let me see if I can increase the font size for   this so control and then plus and it doesn’t look  like I can but I’ll show you how to increase the   font size for this in a second but here let’s  type together PSE sudo and then a and then   update press enter and then it’s asking me for  the password for Amigos code so make sure you   add the password for your username press enter  and you can see that it’s basically performing   the update now now the update basically is used  to update the package index files on the system   which contains information about the available  packages and their versions cool so you can see   that 43 packages can be upgraded now if you  want to upgrade the packages we can run PSE   sudo and then AP so let me just remove the mouse  from there ABT space and then up and then grade   and here I’m going to press enter and we could  actually use flags and we could say Dy but for   now let’s just keep it simple and later you learn  about these commands so press enter and you can   see that it says that the following packages will  be upgraded right so you see the list of all the   packages do you want to continue I can say why  why for yes cool now just give it a second and   now it’s actually upgrading these packages to  their latest versions so it’s almost done and   and now it says which Services should be restarted  leave everything as default and say okay so I’m   just going to press the tab and then okay cool  that’s it so now the last thing that we need to   do is to install Yun desktop so this point type  sud sudo a and then install Ubuntu Dash and then   desk and then top press enter and you can see  that it gives us a prompt I’m going to say w   and now we’ve go prompt and it says do you want  to continue I’m going to say y for yes and now   we just have to wait until it installs the Yun  to desktop and this is pretty much the graphical   user interface that will allows us to interact  with our operating system like we are using for   example the Mac OS right so this is the graphical  user interface but equally we do have the terminal   so if I open up the terminal quickly so terminal  so have a look so this is the terminal right so so   what we doing is we are basically installing the  same experience that we have within Mac OS so if   I click on the Apple logo and then basically use  all of the functionalities that this operating   system has to offer right so if I click on about  this Mac and then I can go to more info so on and   so forth so let me just cancel this and just wait  for a second until this finishes oky doie cool so   this is done and if you encounter any errors  or anything whatsoever just restart and then   run the exact same command but here you see that  there were no errors cool at this point there’s   no services to be restarted no containers and  all we have to do is re and then boot now just   wait for it and hopefully now at this point  you should go straight into the desktop okie   dokie you can see that now we managed to get the  desktop app and running cool so at this point just   click on it the password so this is my password  and I’m going to press enter hooray and we’ve   done it cool so if you managed to get this far  congratulations you have successfully installed   yuntu otherwise if you have any questions drop  me a message next let’s go ahead and set up Ubuntu okie dokie so we have yuntu desktop up  and running and from this point onwards let me   just put this as full screen and for some reason  I have to log in again again that’s fine cool so   you can see that the UI looks nice and sharp  and in here let’s just um basically say next   we don’t want to install the btu Pro and in  here whether you want to send information to   developers I don’t really mind to be honest  and location I’m just going to turn it off   and here it says you’re ready to go and let’s  just say done cool we have the home so here I   can just put this on this side and what we’re  going to do here is some customization this is   actually an operating system so you’ve got a  few things in here so you’ve got mail client   you’ve got files so if I click on files you  know this is a file system you know the same   as I have in my Mac so here let me just close  this and what I want to do is I want to go to   show all applications or I could just right  click in here and then I can say a few things   so one is display settings this is what I’m  mostly interested so in here I’m going to   put things a little bit bigger so fractional  scaling and here I’m going to increase this by 175% apply so that things are quite visible to  you so here keep changes and you can see that   now it’s nice and big cool so just move this in  here and it doesn’t look like it lets me right   So eventually it will let me move this but also  I can click on show all applications and I can go   to settings through here so the same thing and um  cool so you can go to keyboards you can you know   change according to your layout so I’m going to  leave my one as English UK which is fine you can   go to displays you can change the resolution if  you want to power configure that whether you want   power saver mode or not and um online accounts  so here I’m not going to connect to anything   privacy go back and I’m just showing you around  so background if you want to change the background   you’re more than welcome to do so here a couple of  different ones but for me I’m going to stick with   the default and appearance as well you can change  this right so here if you want a blue theme for   example which I kind of like to be honest or this  purple right here so let’s just actually choose   this blue for myself and for the desktop size  I’m going to say Lodge in here so that things   are visible to you okay and I can scroll down  and also icon size just as big as this and you   can show Auto Hide dock does that work probably  I don’t know right so I think it hides when yes   when this collides with this right so basically at  this point it just hides cool let me just remove   that I don’t think I need that and notifications  so you can go through and customize this the way   you want it but for us I think this is looking  good one other thing also is if you have a window   opened you can basically pull it all the way to  the left and it will just snap so if I open a   new so let’s just say I have um a new window for  example I can put this right in here and you can   see that it auto arranges for me which is kind  of nice and uh to be honest I think I’m going   to stick with the red so red not not there but I  think it was appearance yes I think this orange   or actually orange I think this orange looks nice  yeah I don’t know it’s very difficult cool so I   think I’ll just stick with this default for now  cool and um yeah so let me just close this and   this and this is pretty much it uh I don’t know  for some reason why this is not um oh actually let   me just click on arrange icons maybe that will  do it no I think it doesn’t do it because it’s   too big it doesn’t want to move but I think if I  restart then it should basically sort itself out   uh the other thing is so in here yes so here I can  basically remove so I’m going to remove this from   favorites same as this so stop and quit and remove  favorites the same with this and no need for help   and I think this is pretty much it awesome this  is my setup and also I think the clock is I think   it’s 1 hour behind so feel free to fix that but to  me it doesn’t really matter so this is pretty much   it if you have any questions drop me a message  but this is the configuration required for yuntu in order for us to install yuntu desktop on  Windows let’s use Virtual box which basically   allows you to install and run a large number  of guest operating systems so here you can   see uh Windows XP which I doubt you’ll ever use  Vista Windows and then Linux in here Solaris so   these are different distributions but basically we  need virtual box in order to install another guest   operating system on top of windows so navigate to  downloads and in here download the Windows host   so just give it a second and then open file there  we go I’m going to say next so the installation   process should be really straightforward and don’t  worry about this warning in here so just say say   yes and then it says missing pice dependencies  do you want to install it yes why not and then   install cool so this should take a while and you  can see that we have the shortcut being created   for us in here and we are good to go so let me  just unake this because we’re going to continue on   the next video say finish and we have successfully  installed virtual box catch me on the next one we do have virtual box installed and before I open  this application in here the next thing that we   need is the Ubuntu desktop itself so that we can  mount on top of virtual box so in here if I open   up my web browser and search for Ubuntu on Google  and basically go to ubuntu.com and you you should   see so if I accept in here you should see that  we can download so we have yunto server in here   and this is the current version as I speak and  whatever version that you see provided that is the   sorry this is not the latest this is the long-term  support but whatever long-term support you see   just download that so here go to developer and you  should see that we have yuntu desktop so click on   that and we can download yuntu desktop so you can  watch this video if you want but I’m not going to   but if I scroll down you can see that it says that  your buntu comes with everything you need to run   your organization School home or Enterprise and  you can see the UI in here so on and so forth so   let’s go ahead and download yuntu cool now if  I scroll down in here you can see that we have   this version so long-term support just download  whatever long-term support you see available so download and it should start very soon there we  go and it should take about 5 minutes or so to   complete or even less now and there we go now  let me open this on my desktop and you can see   that it’s right here awesome now that we have  Ubuntu desktop next let’s go ahead and uh use   Virtual box to install this ISO image in here  this is pretty much it catch me on the next one cool let’s open up virtual box in here  and I’ll walk you through the steps required   to get yuntu desktop up been running so if this  is the first time that you’re using virtual box   this should be completely empty so what we’re  going to do is create new and here we’re going   to name this as yuntu there we go and you can put  the version if you want but I’m going to leave it   as is then for the iso image is the one that we  downloaded so here let’s just select order and   then navigate to desktop and I’ve got my Ubuntu  ISO image open cool and in here you can see that   basically we can’t really select anything else  so let’s just click next and we can actually   have the username and password so in my case I’m  going to say Amigos and then code there we go and   then choose the password so if I click on this  I icon in here you can see that it says change   me right so you can change this or you can leave  it as default so in my case I’m going to leave as   change me but obviously I would never do this  and I want want to leave the host name as you   B to domain as uh what it is right now and then  next then we need to specify the base memory in   here as well as the CPU so for CPU let’s just  choose two cores in here and for memory if you   have more memory on your machine just feel free  to rank this up to maybe four gigs but for me I’m   going to leave as default next and then here it  says either to create a virtual hard disk or use   an existing or do not so in my case I’m going to  basically have 20 gigs so here I’m really saving   memory uh I don’t think there’s much space on  this Windows machine so 20 gigs I think should   be fine and uh yeah create a virtual hard disk  say next and now we have a summary you can read   through it and let’s finish cool so this is pretty  much it now you can see that it says powering VM up so just wait for a second until this is up  and running and you can see that I think it’s   done right so you can see that it’s actually  running now obviously if I click click on it and then we have this window and you can see  that it’s loading yuntu and it says mouse mouse   integration so click on here and then there as  well all right so just give her a second or so   and uh this should install successfully and there  we go you can see that this was really quick and   and here you can see that it’s installing few  things so this is now installing and basically   I’m going to leave this complete and then I’ll  come back to it so that we can proceed our setup   cool now it’s installing the system and I can  click on this button and you can see what it’s   doing on the terminal so let’s just wait until  this finishes and this should take a while for   you so for me I’m going to speed up this video but  uh you should yuntu up and running in a second and   in fact we could actually skip this all together  but I’m going to leave it finish and after a long   time of waiting it seems that it’s almost there  let’s just wait and finally we are done cool so   if you get to this point where you have your  user and then you can click on it and then in   here the password was change and then me right  so I didn’t change the password let me just show   you so change me if I press enter we should be  able to log in if the password is correct there   we go cool this is pretty much it I’m going to  leave it here and we’ll continue on the next video okie dokie so we are almost done  with the configuration so one thing that   I want to do is let’s just click on  Virtual box in here and uh click on settings and then let’s go to Advanced so under  General click on Advanced and then share clipboard   so we’re going to basically say bir directional  and the same for drag and drop so basically we   can basically drag stuff from our Windows to our  yuntu desktop and uh the same with the clipboard   say okay or actually let’s just go to system  and see whether we have to change something so   I don’t think we have to change anything else  and uh under storage so in here so just make   sure that this is empty so make sure that this  is empty that it doesn’t contain the iso image   in here cool audio everything should be fine if  you want to enable AUD the input feel free to   do so serial ports nothing USB shared folders and  user interface we’re going to leave everything as   is okay and in here I can just close this and uh  if I try to put this full screen in here you can   see what happens so to do this what we have to  do is install virtual box guest editions so in   here we’re not going to connect to any online  accounts let me just Skip and also I’m going   to skip the pro yuntu pro next and uh also if  you want to send data feel free but I’m not   going to send any data click on next and uh I’m  going to turn off location and there you go you   you see that it says you’re ready to go you can  use software to install apps like these so press   done and what I want to do is let’s open up the  T terminal so click on this button in here that   shows all applications and then open the terminal  so this is the terminal and with the terminal open   let me just put this full screen like that and  now what we’re going to do is type some commands   and at this point in here I don’t expect you to  know none of this because we’re going to learn   in detail how all of this works cool so the first  thing that that we want to do is is if you type   with me so P sudo and then here we’re going to say  a PT and then up and then date so if this command   in here does not work and now it’s asking me for  the password so change and then me now I’m typing   but you don’t see that I’m typing because this is  done by default because here I’m typing sensitive   information which is the password press enter  and and if it says that Amigo’s code is not in   sudo’s file this incident will be reported that’s  fine so all we have to do is so if this happens   to you type pseudo or actually sorry my bad Su and  then Dash and then here type the password again so   change and then me and or whatever password that  you added and there we go now we can type pseudo   and then add and then user so user and make sure  that add user is all together and then type Amigos   so the user in question so this is Amigos code for  me and then we want to add Amigos code to PSE sudo   just like that press enter and you can see that  this is basically added Amigos code to PSE sudo   and now it means that if I say Su and then Amigos  and then code and by the way Su just allows it to   change users and you will also learn about this  command press enter and now you can see that I’m   back to Amigos code in here and if we type PSE  sudo and then basically the the previous command   I’m just going to press the up aror this one so  P sudo AP and then update and then let’s add the   password once more so change me enter you can see  see that this time this command works so I’m going   to leave these commands that I’ve just did under  description of this video so that you can follow   along as well cool the next command that we need  to run is PSE sudo in here and then AP install   Dash and then Y and then build Dash and then  essential space and then Linux Dash and then   headers Dash and then add dollar sign and then  parenthesis and then you name space Dash and then   R and then close parentheses just like that cool  also you’ll find this command under description   of this video press enter and just give you a  second or so and there we go now navigate to   devices and then insert guest editions CD image  and you can see that we have this dis in here so   let’s just click on it and now what we want to do  is let’s take this file in here autorun Dosh and   then drag it to the terminal in here and let’s  see whether this works so if I so right at the   end if I press enter this doesn’t work and that’s  because I need to remove the quotes there we go so   the quote at the beginning and also the one at  the end and then press enter and it looks like   it doesn’t work so let’s just click on the dis  again and then here I’m going to right click and   then opening terminal so we have a new terminal  let me close the old one so close this terminal   and then we can close this as well and now if  I put this full screen all I want you to do is   to type dot slash and then autorun Dosh press  enter and now it’s asking me for the password   for Amigo’s code and the password was change me so  change me let me show you change me authenticate and it’s installing some modules now we have to  wait until this is complete and the last step   will be to restart our machine and uh it says  press return to close the window it seems to   be done so I’m just pressing return there we go  finished and now let’s together so in here click   on the battery icon and then let’s click on power  off restart restart and now if I restore down so   let’s just restore and and um what I want to do  is I want to put it full screen so if I maximize   now now you saw that the screen went black and uh  what we have to do is so let’s just basically make   this smaller open up virtual box and basically on  this Ubuntu which is running click on settings and   display and what we want to do is to change the  video memory now this is grade out because what   we need to do first is right click on the VM  itself and we want to stop it so stop and then   power off cool let’s switch it off now we can go  to settings and then display and now you can see   that we can change this now I’m going to put this  at 64 somewhere in the middle okay and if we click   on it so you can click here or you can start  if you want through this button just give you a second and very soon we should have so  let me just close this we don’t need this so it should start very soon there we go and  if we try to put this full screen on actually did   that for me but what I want to do is actually put  everything full screen you can see that this time   it works there we go and then if I click on Amigos  code the password was change me enter and we are   inside cool so now what we can do is go to view  and then you can say full screen mode and you   can switch in here and you can see that now all of  this is in full screen mode and we done it awesome   we successfully installed yuntu and if you want to  exit full screen you can see here I could just go   down View and then you have the keyboard shortcuts  as well but if I press on it you can see that I   came out from this and I do have access two in  here my Windows machine cool this is pretty much   it and also if you get software updata just  go and install as always but in my case I’m   going to be naughty and I want to say remind me  later this is pretty much it catch me on the next one cool in this video what I want to walk  you through is how we going to customize our   desktop so in here let’s together just put this  full screen and I’m going to switch there we go   and if you want to customize the look and feel  of yuntu desktop go to show applications at the   bottom and then click on settings cool now that we  have settings in here we are able to change couple   of things so you can change the network specific  information Bluetooths in here background so you   can choose for example if you don’t like this  background just choose this one for example you   can see that it changes but for my case I’m going  to stick with the default in here appearance so   appearance you can change the color theme in  here so maybe you like this color in here so   if I click on it you can see that the icons have  changed have a look right but I’m going to leave   the default in here so everything is consistent  throughout and you can change the icon size if   you want as well so I think the icon size I  think we have one icon in here so the oh icon   so if I increment this no it’s yeah the icon  size is basically this one right here on the   left right so I’m going to leave that as 64 you  can change this according to whatever you prefer   so for me it’s more about making sure that you  see everything visible in here notifications so   there’s nothing here search multitasking so you  can basically configure this uh I’m not going   to touch none of these applications so there’s  no configuration on any of these applications   in here let me just go back privacy same nothing  I’m going to change here and um online accounts   you can connect your Google account Microsoft and  whatnot sharing so there’s nothing here you can   change the the computer name if you want sound as  well power so basically you can have power saver   or not screen blank after whatever minutes screen  display and in here let’s basically scale this so   let’s say that we want 200 so apply and you can  see that things are now so big so I’m going to   keep these changes 200 and um let’s have a look  if I put this full screen what what do I get yeah   this looks nice right so 200 and then let me go  to I think it was background or sorry appearance   and then the icon size we can make a little bit  smaller now just like this you can leave it like   that uh but as as I said you could basically do  whatever you want okay so screen display and again   you can make this 100% I’m just making things  big so you can see sharply and then Mouse and   touchpad you can change the speed if you want the  keyboard so my one is so so let me just add United   Kingdom so this is my one English UK and add and  then delete this guy so remove there we go and   um printers nothing there removable media nothing  and device color profiles and obviously here I can   scroll down and you can see a bunch more right so  language region so here you can change the region   the language accessibility date and time so on and  so forth all right so also the same with users so   here we only have one user and uh you can change  the password if I’m not mistaken in here right   cool so my password is changed me I could change  for uh something better but I’ll show you how to   do all of this through the terminal which is uh  what we are here to learn how to use Linux andd   terminal let me cancel and then close this so  let’s just get rid of this from favorites I’m   going to get rid of this as well office as well  ubun to sofware as well help as well I want to C   I want to keep it clean eject there and I think  this is it awesome this is pretty much it if you   have any questions drop me a message but from now  on if you you followed the Mac installation this   is the exact same point and vice versa so from  now on both Mac and windows uses everything should   be the same because we are using Ubuntu desktop  this is pretty much it I’ll see you on the next one okayy doie so with Linux it’s all about the  terminal and really the reason why I installed the   desktop is so that you basically get an operating  system but what we’re going to focus throughout   this course is on the terminal so Linux it’s all  about the terminal and as you’ll see later when   we SS into a remote server we never have the  graphical user interface so it’s all about the   terminal cool so what is a terminal really  right so terminal also known as the command   line interface or CLI so in here if I go to show  applications and we have terminal so let’s just   take terminal and I think if we put it there  does it takes it from here so hold on so let   me just put it back in here right click add to  favorites oh yes it doesn’t really matter cool   so the terminal now it’s within the favorites and  now I can just click on it and open cool so what   is this terminal in here right so we have Amigos  code and then add Amigos code so the terminal   is a text based interface that allows you to  interact with a computer operating system by   entering commands so in here let me just type  one command and you’ll see how it works so if   I say date for example press enter so this  is giving me the current date so this was   a command and we’ll let learn more about this  um commands and what not in a second but this   is a command which allows me to interact with the  operating system so similarly if I want to create   a folder in here on my desktop I’m going to type  mkd and then here just type Tilda for a second so   tilder for SL desktop and then say for Slash and  here I’m going to say f for example press enter   and now have a look there’s a new folder that  was created for us full right so the terminal   allows us to interact with the computer operating  system by entering commands it provides a way to   execute commands navigate the file system manage  applications without the need of the graphical   user interface so to be honest we don’t even need  this UI right so usually you would right click   and then uh move to trash for example so this so  This basically deletes the file so this is with   the graphical user interface but in reality we  don’t need this right so here if I just say for   example RM and we’ll go through these commands in  a second so RM and then tiller for Slash and then   desktop and then F and actually so here I need  to say RM dasr and then F so you learn this in   a second if I press enter you can see that now  the folder has disappeared okay so this is the   terminal so the terminal allows us to interact  with the operating system the time not provides   a prompt so this is the prompt where we can  enter the commands and receive the output so   when we say date we get an output right so some  commands we don’t get an output but I’ll show   you um other other things that we can do right so  with this we can per perform a wide range of tasks   such as navigating directories creating modifying  files running programs accessing system resources   and whatnot so the terminal is commonly used by  developers and systems administrators to perform   a bunch of tasks including software development  server Administration and Automation and this is   a very powerful and efficient way to work with a  computer operating system and it’s an essential   tool for everyone working with programming and  development so knowing how to use the terminal   it’s a must for you right so this is the reason  why I’ve got this course for you because you   should be doing pretty much everything through  your terminal okay I don’t want to see you know   if I want to create a folder right click on your  uh graphical user interface new folder and then   say the folder name blah blah blah so this is  bad Okay so by the end of this course you oh   you see I’m actually deleting the folder using  uh the UI this is wrong but let me just do it   there we go but at the end of this course you  will familiarize yourself quite a lot with the   terminal so that you have all the required skills  in order to use the terminal and as you’ll see   a bunch of tools such as git Docker kubernetes  all of them you actually have to interact with   them through the CLI or The Terminal cool  this is pretty much it catch me on the next one within my Mac OS what I want to show you is  that I also have a terminal available within Mac   OS so here if I search for terminal so this right  here is the default terminal that comes with Mac   OS so here I can type any command and basically  this will be executed against my operating system   so if I say for example LS in here and you’re  going to learn about LS later but just type   this command press enter and in here this is just  listing all the contents that I have within home   right here so if I type clear for example so  this is another command so this actually clears   the terminal and here I can type for example  PWD in here you’ve seen this one so this is   users and then Amigos code so similarly there’s  also another ter available and this is not part   of the Mac OS operating system but it’s the one  that I use actually on my machine and that is   the iter so in here this is item so yet another  terminal this is way fancier than the other one   you can see the look is actually all black and  it has lots of customizations for example if I   want to split the screen into two for example  I could just do it like that and maybe three   times right here you can see that I’ve got one  two three and in this I can type LS in here I   can type PWD and in here I can type for example  Cal for example and you can see that basically   I’m executing commands in three different shells  and I’m going to talk about shells in a second   but basically you can see that this terminal  right here is way more powerful than the default   that comes with Mac OS so here let me just close  this and yeah so I just wanted to show different   terminals available for Windows what you have  is the command line or simply CMD and it kind   of looks like this and probably you’ve seen  this if you’re on Windows and again this is a   terminal so you can run commands and those will be  executed against your operating system and perform   whatever tasks that you tell it to do and this is  pretty much for this video catch me on the next one also what I’m going to show you is within  text editors and idees there will always be an   integrated terminal so you don’t necessarily  have have to use a terminal that ships with   your operating system or you don’t have to  install a ter for example so here I’ve got   VSS code so visual studio code open and within  Visual Studio code if I click on Terminal and   then here new terminal and in here you see  that I do have the terminal so here I can   type the exact same commands that you saw  so for example if we type who and then am   and then I so just type this command here if you  have Visual Studio code or any other text editor   so in here let me just type who and then um I so  don’t you worry about this uh we’ll cover all of   these commands but for now I’m just showing you  other the terminals so if I press enter you can   see that this gives me a MH code also so I think  so this is one is quite cool so within terminal   I can split the terminal in here so have a look  so the same way that you saw with item which is   quite nice right and here you actually have two  different shells so this is zsh and we’ll cover   uh shells in a second but here I can delete this  delete this as well and it’s gone also one of my   favorite ID is intellig so in here intell has an  integrated terminal if I open this you can see   that we have the terminal in here and I can type  again the same command so who am I press enter   and you can see that this basically gives you the  exact same output awesome so this is pretty much   about terminals if you have any questions drop  me a message otherwise catch me on the next one all right so you know what the terminal is now  let’s focus on understanding exactly what the   shell because often people use these two words  so terminal and shell they’re kind of the same   thing and if you do it that’s fine but it’s  very important that you understand what is   the actual difference between terminal and  shell and that’s what we’re going to focus   in this section and also you’ll see how we’re  going to switch from bash to zsh and you also   see different shells available for the Linux  environment so without further Ado let’s kick off in this section let’s focus on understanding  what the shell is and basically we’ll also   customize the default shell that we have to a  better one but inet shell a shell is a program   for interacting with the operating system right  so you’ve seen that uh we have the terminal in   here and the terminal is just an application  that allows users to input commands to the   shell and receive text based outputs from the  shell operations right now the shell is was   actually taking the commands themselves and then  executing those against the operating system let   me give you a quick demo so in here let me  just open the terminal and the terminal in   here is responsible for taking the inputs right  so the terminal basically allows you to create   uh multiple tabs allows you to expand uh allows  you to here new tab so this is a terminal right   but now whenever I type a command so if I type  for example touch and this is the command that   you’ve seen before so on the slide so touch  and here I’m want to say desktop and then   full bar.txt so if I press enter and don’t worry  too much about this command so you learn how this   works but basically this command in here right  so I’m passing this command through the terminal   so the terminal is responsible for taking the  commands and also outputting the results from   commands executed by the shell so the shell now  is responsible to interact against the operating   system so if I press enter you can see that  we have the file in here full bar.txt right   so the same if I say RM and basically the same  Command right so here let me just go back and   if I say RM right press enter you can see that  the file is gone and again don’t worry too much   about this you learn all of these commands  later but this is pretty much the concept of   terminal and shells now I’ve said shells because  there’s a bunch of different shells that you can   use with Linux you have bash in here so bash for  Born Again shell this is one of the most widely   used shells in the default and is a default  on many Linux distributions we have zsh so   this is the one that we’re going to to switch  to in a second and this is highly customizable   and offers Advanced features like autoc completion  spelling correction and a powerful plug-in system   and then you have fish and many others cool this  is pretty much the gist of shells next let’s go   ahead and understand and customize and change  and basically learn what you need to know about shells cool so you know that the shell is basically  what takes the commands and then basically   execute them and executes them and the terminal  is just the graphical user interface in here so   you saw item you saw the terminal for Mac OS  command line for Windows and the the shell   itself is basically the command line interpreter  right shell or command line interpreter they are   both the exact same thing so what I want to show  you here is how do you view the available shells   that you have installed but also how are we able  to change the current shell so let’s together   type in here so basically if you have Tilda and  then desktop in here or if you don’t have this I   think we did run the CD command before but what  I want to do is so that you have the exact same   screen as mine just type CD yeah so so you’ll  have something like the server name plus the   user in here so my one is just Amigos code at  Amigos code cool at this point let’s together   type we’re going to say cat so you’re going to  learn about the cat command later but here say   for SL and remember tab so I’m going to press  tab have a look so if I go back e and press tab   have a look I just get Auto competetion okay now  type SE e now type shells so sh and then tab so   if I tap tab again you see that we do have Shadow  Shadow Dash and then shells so shells like that   and and in here let me just contrl L and then run  this command all right cool so now have a look so   these are the available shells that we can use  so I think these are the defaults that come with   yonto so if I take this exact same command so CD  so cat Etsy and then shells and run it on my Mac   OS so here the same command but it just looks  a little bit different but it’s going to be the   exact same thing press enter and have a look so we  have bash we have chh Dash KS sh T C CH and then   zsh so I’m going to show you how to use this one  later but if you want to know the current shell   so the current shell that you are using so here  we could just type this command so I’m going to   basically say Echo and then dollar sign and then  shell so basically all caps and um we’ll go over   the echo command as well as dollar sign in here  but for now this is the command I need to run and   it will tell you the current shell that you are  using so in my case I’m using zsh if we take this   exact same command and running within Ubunto so  here Echo and then dollar sign and then shell run   it you can see that the default shell for yuntu  is Bash cool next let’s go ahead and install zsh zsh also called the zshell is an extended  version of Bor shell with plenty of new features   and support for plugins and themes and since  it’s based of the same shell as bash Zs has   many of the same features and switching over it  it’s a Nob brainer so in here you can see that   they say many original features were added  so let’s together in install zsh and as you   saw the default shell for Mac OS now is zsh or  zshell so let’s actually install this as well   in our Ubuntu desktop so in here you saw the  list of available shells so you saw that we   have bash in here which is a default right so  bin and then bash and when you run Echo shell   bin bash is a default so we want to change  this to zsh because it’s an improvement on   top of bash so here what we need to do first is  contrl L to clear the screen and to install zsh   we say pseudo and then AP and then space install  Zs so we’ll come back to AP or apt and this is the   pack manager basically that allows us to install  software okay so here let’s just press enter and   we need to enter the password for Amigo’s code  and in fact your password so here I’m going to   type and you might think that I’m not typing  anything but I’m actually typing so this input   right here doesn’t show the password for security  reasons so press enter and you can see that now   it went off and it’s installing and it’s just  waiting for us to confirm so in here just say Y and just wait for a second you can see that  we have the progress and boom so this is done   now to make sure that this was installed  correctly just type zsh and then Dash Dash   and then version press enter if you have  this output in here it means that you have   installed zsh so if I clear the screen control  l in here and then press the up Arrow a couple   of times and if we list the available shells  under ET C cat now you should see that we have   user bin and then sh right as well as bin dsh  and we’ll cover the difference between bin and   u or actually user or USR later on when  we discuss the Linux file structure cool   this point we just installed zsh but what  about using zsh let’s continue on the next video oky dokie now for us to use zsh what we need  to do is just simply type on the terminal Z red   s and then H press enter and now you can see that  the output is a little bit different and basically   instead of having this colid Amigos code at Amigos  code we just have Amigos code which is just a user   okay and at this point nothing else changes  because as I said zsh is built on top of bash   so all the commands that we execute for example in  here you saw that we run this this command before   LS so this command if I press enter this will work  so the output right here is not call it as before   but I’ll show you what we need to install later  so that we can improve the experience when using   zsh and to be honest this is it now if you want to  switch back to bash just type bash in here and now   we are back to bash and in fact let’s just press Z  SSH once more more and now if I search so here I’m   going to say dollar and then s basically and oh  actually sorry this will not even work because now   we are within a different shell so I was trying  to search for Echo and then shell so let’s just   type and not be lazy so Echo and then dollar sign  and then shell and I was expecting to say zsh but   the reason why is because zsh currently is not  the default one which means that if I open a new   tab in here and you can see that if I make this  smaller actually bigger and here I can type Echo   and then dollar sign and then shell just like that  and you can see that this is Bash in here cool so   let me just close this and you’ve just seen that  if you want to go back to bash you just say bash   in here right but also if I say cat for slash  etc for Slash and then shells press enter we   have all the shells so we have dash sh so let’s  just type sh for example in here so now we’re   going to switch from bash to sh boom you can see  that now this is sh so this is yet another shell   if I want to use for example dash dash this is  a another shell R bash R and then bash there we   go bash and zsh and this is pretty much how you  switch between shells but really what I want to   do is switch my defa shell to zsh and the way to  do it is by using this command in here so CH h s   and then Dash and then s and what we’re going  to do is point to the Shell itself so this one   user bin zsh so say for slash USR not user my bad  USR for slash bin SL Zs press enter let’s add the   password cool now if I show you something if I  open a new shell so contrl shift T have a look   this still Bash and I know because if I typee Echo  so let’s just type Echo and then dollar sign and   then shell and if I put this smaller press enter  you can see that it still says b bash so let me   just come out of this controll and then D and  now let’s just reboot so re and then boot press enter now let me loog in enter and if I open the terminal you can see that the first thing  that we are prompted with is to configure   zsh so in here let me just press control and  then minus so you see everything in here there   we go and you can see that this is the zshell  configuration function for new users you are   seeing this message because you have no zsh  startup files so basically this is the files   that it needs for configuring zsh and it says  you can quit or do nothing exit create in the   file continue to the main menu or populate your  zsh with the configuration recommended so this   is exactly what we’re going to do okay so type  one of the keys in parenthesis so we want two   and there we go so basically this has now created  a file called zshrc and U I’ll show you this in   a second right so from this point onwards we  have successfully installed zsh and now it’s   a default shell so if I clear the screen control  and then Z zero to increase the font and now if I   open a new shell control shift T have a look so  this is no longer bash so here let’s just type   Echo and then dollar sign shell press enter  have a look zsh in our previous one as well   and then type the same command Echo Dash and  then shell and you can see that now now it’s   zsh awesome we have successfully switched  to zsh and we have a better shell from now on cool now let’s switch our default shell  to zsh and the way to do it is by using this   command in here so CH H sh and then Dash and  then s and what we’re going to do is point   to the Shell itself so this one user bin zsh  so say for slash USR not user my bad USR for   slash bin for slash zsh press enter let’s add  the password cool now if I show you something   if I open a new shell so control shift T have  a look this still bash and I know because if   I type Echo so let’s just type Echo and  then dollar sign and then shell and if I   put this smaller press enter you can see  that it still says b bash so let me just   come out of this controll and then D and now  let’s just reboot so re and then boot press enter now let me loog in enter and if I open the terminal you can see that the first thing  that we are prompted with is to configure   zsh so in here let me just press control and  then minus so you see everything in here there   we go and you can see that this is the zshell  configuration function for new users you are   seeing this message because you have no zsh  startup files so basically this is the files   that it needs for configuring zsh and it says  you can quit or do nothing exit creating the   file continue to the main menu or populate your  Zs AG with the configuration recommended so this   is exactly what we’re going to do okay so type  one of the keys in parenthesis so we want two   and there we go so basically this has now created  a file called zshrc and um I’ll show you this in   a second right so from this point onwards we  have successfully installed zsh and now it’s   the default shell so if I clear the screen  control and then zero to increase the font   and now if I open a new shell control shift T  have a look so this is no longer bash so here   let’s just type Echo and then dollar sign shell  press enter have a look zsh in our previous one   as well and then type the same command Echo Dash  and then shell and you can see that now now it’s   zsh awesome we have successfully switched  to zsh and we have a better shell from now on the last thing that I want to do in this  section is to unleash the terminal like never   before with oh my zsh which is a delightful  open- Source Community Driven framework for   managing your zsh configuration it comes bundled  with thousands of helpful function helpers plugins   themes and basically you’ve got all the batteries  included and you can see here on the left you can   customize your theme and make it so powerful and  beautiful and uh yeah just a bunch of things that   will make you look like a professional so if I  scroll down you can read more about it in here   and they’ve got many plugins and you can see  that on GitHub so this is where this is hosted   and in fact if I click on this link in here so  let’s just give you a star I think I have done   it before but if not this is the right time  because it’s awesome so here we can see all   the staggers and let’s give it a star in here so  if you don’t have GitHub don’t worry so there we   go one more star and let’s click on this repo  in here or you can actually click on the code   Tab and here if I scroll down you can see some  description of what it is how to get started the   installation process in here have a look at this  method sh so this is a shell remember you saw sh   and you just pass this command with curl we’ll  look into curl as well and if I scroll down you   can see they talk about how to configure so this  is is zshrc so this is where the configuration   file is and also plugins g.m Mac OS and basically  you can install a bunch of plugins and also themes   they have a section on themes so you can choose a  theme and here I’ll show you this in a second how   to configure zshrc and um it might look like this  if you choose for example I think it’s this theme   in here but you can do a lot with this and also  you can choose a random theme for example which   is nice awesome so let’s install oh my zsh and  I can actually go back to the previous website   and in here they have a section on install oh  mysh now so what we’re going to do is let’s just   take this command and I’m going to copy this go  to yuntu desktop and here I’m logged out let me   just add the password there we go and just paste  the command so control shift and then V and let   me just put this smaller so you see what this  looks like whoops there we go you can see the   entire command in one line if I press enter  so have a look it’s doing few things so it’s   just cloning oh my that issh and basically it’s  just running some script and tada this is now   installed so oh my Zs is now installed before  you scream oh my Zs I actually screamed look   over the zshrc file to select plugins themes and  options also if you look closely so if I press   control 0 in here the so in here have a look so  so now the prompt has changed so you have this   arrow in here and you have Tia so Tia basically  means that you are in the home folder and we’ll   talk about home later but to be honest this is  pretty much it nice if I open up a new tab you   can see that this is already configured and zsh  is installed next let’s look how to configure zsh cool you saw that they said before you scream  oh my zsh look over the zshrc file to select   plugins and themes and other options so in order  for us to achieve this what we have to do is the   following I’m going to clear my screen crl L and  make sure to type CD just to make sure that we   are within the same folder so just type CD there  we go and what this does basically is if I say   for example CD and then desktop press enter so for  example maybe you are inside of a different folder   desktop so if you type CD it just takes you to the  home folder in here and again we’ll come back to   all of this commands in a second so type CD if I  claim my screen contrl l type VI space do zsh R   and then C you can just type tab so here if I type  zsh or Dot zsh and then tab have a look we’ve got   zsh history zsh RC and rc. pm. preo my zsh so  the one I want is our C right and if I click   the screen and then press enter and there we go  so this is the configuration for zsh and here if   we scroll down so just scroll down in here and  you can see that a few things are commented out   and scroll down in here you can see that we have  some stuff plugins so at the moment there’s only   one plug-in which is get but I’ll leave this up  to you to configure this the way you want it you   can explore themes and whatnot and also you can  configure alyses and a bunch of other things but   basically this is pretty much it if I go back to  the giab repository so here remember if I scroll   down I think they have a section on themes have a  look selecting a theme so once you find the theme   that you like you’ll see an environment variable  all caps looking like this right and to use a   different theme just change to agnos for example  so let’s try this and actually I think the themes   are available so I think there’s a link right  so yes in case you did not find a suitable theme   please have a look at the wiki so here if I click  on this link it takes me to external themes and   have a look so this one looks actually quite good  oh even this one wow so you can see that there’s   a oh you can see that there’s oh I’m getting  excited here you can see that there’s a bunch of   themes that you can use and basically just follow  the instructions in here on how to install them   but let’s just go back to the terminal and what  we’re going to do is so here if I scroll all the   way up to the top in here and have a look the zsh  theme is Robbie Russell so what I want to do is   the following so here we need to be really careful  and just follow exactly as I say because this is   VI and we will learn about this text editor so  here type J just type J and make sure that you   select the terminal type J and you can see that  the cursor is moving down so stop right here and   what I want to do is to type on your keyboard  the letter Y twice so y y and followed by the   letter P there we go so this basically duplicates  the line for us now I want you to type the letter   I and you can see that now it says insert and this  means that we can basically type on the text edit   editor itself so I want you to use the app arror  and we’re going to comment this line so here let’s   just comment this with the pound sign and then go  down and here I’m just using the arrow but I’ll   show you a better way later so let’s just remove  so delete anything within double quotes and let’s   use the AG Noster EG Noster and now I want you to  type the scape key on your keyboard and you can   see that insert is no longer here and then type  colon so colon in here W and then Q so write and   quit so this allows us to come out of this editor  in here press enter and that’s it awesome now   what we going to do is open a new tab you can see  that the theme looks slightly different and here   is actually missing some fonts which we have to  install but I’m going to leave this up to you in   terms of how you’re going to customize your IDE so  I’m not spending time on this okay so usually my   one is just black so here let me just close this  and let me go back to VI so I’m going to press the   app eror so here crl L and you can see the command  once more enter and what we’re going to do is the   following so here I’m going to press D and then D  so twice and make sure that the cursor is in this   line so DD twice so that is gone so basically that  deletes the line I’m going to press I for insert   and let’s just get rid of that and esape colon WQ  esape colon WQ I’ll leave instructions on how to   work with Vim but I’ll teach you Vim later on so  here press enter and now if I open a new tab you   can see that we have the default theme cool so  here control 0 to have the default font size crl   L and this is pretty much it I’ll leave some  links under the description of this video so   you can go and explore and Adventure yourself on  how to customize your ID e but if I show you my   one quickly on Mac OS it just looks like this so  it’s plain black and there’s no themes whatsoever   so let me just say uh in here VI and then zsh  zshrc so this is the exact same configuration if   I put this full screen in here have a look so the  exact same thing I didn’t change nothing and you   can add plugins and whatnot so I’ll leave this  up to you cool so here Escape W colon and then   Q this time I didn’t change this file and press  enter this is pretty much it catch me on the next video let us now focus on Linux commands because  moving forward we’re going to learn a bunch of   commands which essentially is what Linux is all  about right so it’s about learning a bunch of   commands that allows us to interact with the  operating system so a Linux command is a text   instruction that tells the operating system  what to do these commands can be entered in   the terminal or command Lin or basically CLI and  by now you should be familiar with the terminal   and um we basically pass those commands and then  an instruction is sent to the operating system   maybe you want to create a file you want to delete  a file you want to check the time or you want to   connect to a remote server so there’s a bunch  of commands that allows us to interact with the   underline operating system the Linux command  the commands themselves are case sensitive so   for example LS and LS in capital these are  two different commands Linux commands are   often various in options and arguments that can  modify their behavior allowing for a wide range   of functionality so in this example in here so  we have the command option and argument so this   is a command so LS is the command then we can  pass an optional argument so this is Dash and   then a and then an argument so here we are saying  dot which means the current directory so here are   some basic commands LS for listing files CD for  changing directories make di for creating a new   directory RM for removing files CP for copying  files and many more each of these commands they   have an instruction via the manual so if you  don’t know how to use a command you can see   the instructions or some guide on how to use  it effectively let’s go ahead and learn about commands in here I do have the terminal open and I  want to give you a quick introduction of commands   so throughout this course you actually seen some  of the commands that I’ve been using for example   LS so you saw that I did the type LS couple of  times on the terminal you also seen M KD iir or   make there you also seen I think it was sleep  so all of these are commands that allows us to   interact with the underlying operating system  so let me quickly just show you the ls command   and then we’ll go over the command itself the  options and the arguments and also on to show   you the list of all available commands as well  as alyses and the manual so the man page so in   here if I type LS you can see that this is a  command and literally just type LS anywhere   so if you are within a different folder or maybe  let’s just make sure that we are within the same   folder together so here type CD so CD this is a  command so press CD and and this will take you to   the home folder okay now we type CD so CD stands  for change directory so this is one command now   change directory means that you change in the  directory where the subsequent commands will be   run from so let’s just type LS so basically the  ls command will be run under this home folder   in here and come back to the tilder and home  folder as well so press enter and you can see   that we have desktop music templates documents  pictures videos downloads and public so these   right here these are folders currently okay but  I know that within this folder so in here if we   type PWD so this is another command and we’ll  come back to this in a second but this stands   for present working directory press enter and it  tells you that I’m under for slome for/ Amigos   code so this is the folder that I’m currently in  so we just typed LS under this folder and we have   these contents in here right now I know for a  fact that there are more stuff under the home   folder okay so this is home okay so home meaning  that if I say Echo so this is another command so   Echo and Echo takes an argument right so here  I want to pass the argument as the home so this   is actually an invironment variable and we’ll  cover environment variables later but this is   the command Echo and this is the argument in  our case for PWD we just executed the command   without no arguments nor options the same with  ls the same with CD so here if I press enter so   this will give me the home location which is  basically for slome and then the user itself   in here cool so LS in here so let me just clear  the screen so contrl L and here if I typ LS you   can see that we have desktop music templates blah  blah blah right now I know for a fact that there’s   more content inside of the home folder so here  let’s type LS and then we’re going to say Dash   and then a so a in here so this is an option  this is an option if I press enter now have   a look so what we have we have more stuff so if  I scroll up in here so we basically typed ls- a   and have a look so these are all the files bash  history we have the cache we have config then   we see so oops let me scroll down here so then we  see the desktop documents downloads as before but   here we are actually including as well as hidden  files so all of these are hidden now what do I   mean by hidden right so if I open files and in  here this is home right have a look under home   I see documents downloads music picture public  templates and videos so this is what I see so in   here let me just put this on this side like so and  then this guy right here and if I put the font a   little bit smaller and then crl L and if I type  LS without the option- a what we see is desktop   music templates so basically everything that you  see in here right but through the terminal if I   say ls- a now we have a bunch of more stuff so in  here what I can do is I can click on these three   lines at the top click on it and here show hidden  files click on it now can you see bash history profile Vim info zshrc so remember this file in  here so these are hidden files right so you saw   that by default it doesn’t come up in here but we  can toggle the hidden files so here this is the   Das a so – a means hidden files now before we move  on to the next video so one thing that I want to   show you also so LS in in here we could say LS and  then so let me just go back here say LS and then   dot so dot means the current directory and this is  actually optional with the ls command because we   are so here if I type again PWD present working  directory we are within Amigos code this folder   this is the home folder which is this one that you  see right so if I time LS and then dot this is the   exact same thing as LS okay so contrl C there let  me just type LS and then Dot and you can see that   is the exact same thing so what we’ve done before  was LS and then Dash and then a and then dot okay   so this is the command itself so LS the option and  this is the argument so here if I press enter you   can see that we get the exact same output now you  might be saying right so here the ls so if I press   the up error so ls- a and then dot so here this  is the argument well we are printing or well we   are listing the contents of the present working  directory which is home but let’s say that within   documents so let’s just go to documents in here  so documents and let’s just right click in here   new folder I’m going to say f in here okay press  enter let’s create another folder and then call   it bar create so now within documents we have  F and bar so we have two directories cool so   here let’s just press contrl + C I’m going to  type LS so you can see that we are able to see   desktop and here documents right so what we can  do is we can say LS and then the argument so we   want to list the contents of the folder called  documents so make sure that this is capital D   so the exact same name here I can press tab to  autocomplete press enter and have a look we see   F and bar so these are two folders that we are  seeing within documents so you can see that this   is the command and this is the argument we could  also say LS in here and if I go back and I can   say Dash and then a space enter and basically  we just see bar and then Fu okay so there’s no   hidden files Within the documents folder so this  is pretty much what a command is obviously there   are plenty of other commands which I’m going to  go through with you in this course but you should   know what a command is what are options and also  what are arguments in here so here there’s just   one argument but some commands might have multiple  arguments and also I actually forgot so remember   I said that commands they are case sensitive so  LS in here so if I type this command basically   command not found so this command is not the same  as LS in lowercase cool now that you know about   commands options and arguments next let me walk  you through the manual pages or simply the man page in this section let’s focus our attention  in Le in the Linux file system which is the   hierarchical structure used to organize and manage  files and directories in a Linux operating system   it follows the tree structure with the root  directory so here you can see this is the   root at the very top and all other directories  are organized below it so here we have bin is a   directory Etc another directory sbin USR VAR dev  then we have have home lib Mount opt proc root   so on and so forth so in this section basically  I want to give you the overview so that we can   start exploring and start using the CD command  PWD on all that good stuff so basically you have   the root in here and then after root you have all  the directories in here so sbin which is used for   essential user commands binaries so here bash gut  CP date Echo LS uh less kill and then basically   all of this commands are used before the USR so  here is mounted because within this USR so here   you can see that there’s also a for slash bin in  here right so these is where you find the programs   right so binaries are programs then you have Etc  so here it’s mainly used to store configuration   files for the system so here you can see fonts  Chown tabs in it and profile uh shells time zone   and whatnot so these are mainly for configuration  files then we have the sbin so sbin is similar to   bin but only for the super user then we have  USR or you can say user so here it’s read only   application support data and binary so you can  see binaries in here for SL include in here lib   right so here basically some code and packages and  also uh you can see some local software which is   stored as well under for SL looc you also have  the for/ share which is static data across all   architectures then we have the VAR so this was  initially uh named as variable because it was   used to store data that change frequently so here  you can see uh youve got cache so application   cache data lib data modified as program runs  lock for lock files to track resources in use   then log files are stored in here variable data  for installed packages and opt es poool tasks   waiting to be processed here you’ve got es poool  and then cron cups and mail and basically here   is where you store temporary data so once the  system reboots then the data is gone you have   Dev in here so this is for device files then we  have for slome so this is the home directory and   we’ll come back to this in a second you have lib  so here for libraries and carel modules Mount so   here Mount files for temporary file systems  such as USB then we have opt for optional   software applications proc for process and kernel  information files for/ root so this is the Home D   for the root user and this is pretty much it now  obviously here I’ve schemed through it and um as   you go through your journey in terms of learning  Linux and um using the command and navigating your   way around and even you know building software  then you start to familiarize yourself with all   all of these folders in here that I’ve just  talked about so this actually is from the   Linux Foundation org I’ll leave a link where  you can basically go and read more in detail   about what each of these folders and subfolders  do but this is pretty much the Linux file system   in a nutshell next let me go ahead and show you  how we can navigate around within the Linux file system all right so in here I’m with in my  terminal and let’s together explore the Linux   file system together so I want you to type this  command in here so CD in here literally just type   CD and then for Slash and then space and then  for slash so this whatever you are just type   CD and then for SL now CD in here means change  directory and basically allows us to change from   one location to another So currently I’m within  the home directory and I want to see I want to   change directory into forth slash so for slash  is the root so press enter now we are within root   if I type PWD it just gives us forth slash which  means root nice if I type LS so list directories   and basically so list the contents within this  directory press enter in here so anytime that   you see something which looks you know something  like bin lib proc serar boot Dev ety Mount up   temp user this is basically the Linux file system  from root so remember I’ve showed you so in here   we have root and then we have ban at C SB user  VAR Dev home lib so if I go back so have a look   bin lib VAR temp user in here so on and so forth  media Mount opt home as well in here have a look   home right so this is pretty much it now what I  want to do with you is so let me just clear the   screen crl L and in here let’s together type this  command we’re going to say PSE sudo and we’ll come   back to P sudo and a also apt we’ll come back to  this in a second and then say install and then   tree so this is basically a way of us installing  extra binaries into our operating system so press   enter Then adding the password and I’m typing  trust me but you can’t see press enter and now   this is installing the tree binary and there we  go so now if I type in here so I just clear the   screen I’m going to type tree or actually let’s  just say which and then tree press enter you can   see that this is under user bin and then tree  okay so it means that we have this binary that   we can use now this binary here so tree so here  I’m going to pass an option so the option will be   Dash and then capital l in here and then I have  to pass an argument into this option and press   enter and literally what this basically gives  me is this nicely formatted LS so basically we   are lising the directories within the root folder  but this is nicely formatted for us so here you   can see we have bin we have boot we have Dev we  have ety we have home lib and also these arrows   in here I’ll come back to them in a second but  in here so temp as well V are so this is pretty   much the Linux file structure from root and you  can see currently there’s 20 directories and   one file so the file is this swap. IMG awesome  next let’s go ahead and learn how to use the CD command all right so in order for us to navigate  around the Linux file system we need to use the   CD command so here let me just put this full  screen and clear the screen crl l so we need to   use the CD and then command so CD and if I press  tab let’s just press tab in here so this now is   giving me the list of all available option right  so here if I want to now move into the directory   called let’s say temp for example so this is where  temporary files are stored I can just say DM press   enter and now you can see that this reflects so  this is all my zsh and it’s telling me that I’m   within the temp folder and now if I press LS  and you can see that there are some files in   here so these are temporary files so if I say  ls- a and um yes so you can also see the dot so   file started with Dot in here and if you want more  information about it ls- and in here you can see   that basically anything that starts with d in here  and I’ll come back to what all of this means in a   second but these are directories in here and these  are files in here okay which means that we can you   know navigate into the snap and then private temp  or system d right so I’m not going to do it this   is p myit now I’m inside of so let me just press  control Z and then clear the screen I’m inside   of temp folder right here so let’s just type  this command and I want to go back to the root   again so how do I do it well I’ve got couple of  options I can say CD and then for slash root or   I can basically go back one folder right so here  if I say CD dot dot so this goes back a folder   so you see from temp it went back to root so if I  type CD TMP in here press enter again I can type   CD for slash so this is actually going directly  to the location instead of going back a folder   press enter and we get the same thing what about  if you want to switch between these two folders   for example right so you don’t want to say CD and  then temp or CD dot dot well you could just say   CD and then Dash and basically this flips between  the previous and the current folder and this goes   back to the previous folder whatever it is within  the file system so if I press enter I go back to   Temp if I press CD and then Dash again I should  go back to root have a look I went back to root   in here cool so I’ll show you more examples of  this in a second and this is pretty much how   you navigate around the Linux file system so  if I type LS once more clear the screen enter   you should see a bunch of folders if you want to  navigate into a particular folder you just say   CD let’s go into bin for example CD and then bin  this and then press enter and now I’m within bin   in here if you want to go for example within  media you don’t necessarily have to go back a   folder you could just say CD for Slash and then  media right so because media is within the root   right here press enter and you can see that now I  went back to Media if I type CD Dash This should   take me back to where think for a second so this  goes back to the previous location which was Bin   press enter you can see that now I’m within bin if  I press up arror and then CD Dash I should go back   to Media enter and you can see that I’m within  media this is pretty much it catch me on the next one all right in this section let’s focus our  attention in terms of working with files and   also in the next section I will show you file  permission in this section let’s focus our   attention in terms of working with files and  later I’ll show you um also directories and   then we’ll learn about permissions so in Linux  in here so you’ve seen that if I open the so   this folder files so in here remember if I click  on these three lines I can basically show hidden   files right how do we create files manually  with Linux so one we have two options so we   could use the UI and we could open so let’s  just open any of these so zshrc and this will   bring the text editor so here what we could do  is we could create a new document and here I   could say hello and then Amigos and then I can  save this I can give the destination so let’s   let’s just save it into documents I’m going  to say hello.txt and there we go close the   file close this let’s navigate to documents  so CD and then documents so you’ve learned   about the CD command LS and you can see that we  have our file in here right so obviously that   is the wrong way of doing that so hopefully  in this section we’ll go through in terms of   how to work with files creating files deleting  them and moving them to a different directory   I’ll show you how to print them as well and also  how to zip any file cool let’s begin in the next video cool in order for us to create a file with  Linux we have this command called touch so this   command allows us to create a file so here let’s  just say buy so buy. txt now obviously here if I   don’t specify the location and just give the  name so this is the name of the file so this   will be saved under the current working directory  which currently is documents right so home and   then documents so if I press enter now let’s type  LS and you can see that we have the file in here   called by. txt so this is how to create files  now obviously this file in here is empty let me   show you so before I actually show you the Linux  command in order for us to print this file if I   open up files in here and then let’s navigate  to documents we have buy. txt let’s open that   up and you can see that it’s absolutely empty so  this is to much how to create an empty file now   obviously it’s not useful because you know most  of the times what we want to do is to create a   file with some content so there are a couple ways  that we can do that and one way is for us to use   the echo command so here I’m going to say Echo  and here we have to pass a string and here I’m   going to say for example by by and then Maria for  example right so this is just a random string now   if I press enter this command just prints back  by Maria now what I can do is I can take this   command and then redirect to the file so here  I can give an existing file name or I can give   it a brand new file so let’s just overwrite the  file that we have which is b.txt so here by. txt   press enter and we get nothing so here we know  that basically if you don’t see anything on the   console and the command just run and executed  you know that it works so let me just clear the   screen crl L LS we have our buy. txt now if we  want to view the contents let’s just again just   open files and here let’s go to documents buy.  txt and sure enough we have buy and then Maria   so this is pretty much how to create a file both  an empty file as well as passing some string or   some output into the file so basically we use use  the echo command in here and then we pass a string   and then we say by. txt or if you want an empty  file you could just say basically so here you can   use the touch command okay so this is touch and  then you can say whatever right so lol and you   don’t even need the extension so here if I say  enter and then LS you can see that we have buy.   txt we have F we have low. txt actually these  are folders so I think we did these before we   created these folders before and um yeah so this  is pretty much it so if I open of files again once   more go to documents you can see that we have  three files in here both with extension and uh   without extension cool there’s another way that  we can create files which is so basically let’s   say that you want to type a couple of things  uh before you actually uh submit the content so   here you see that I’m just saying Echo and then  by Maria I’m redirecting the output from this   command into this file but maybe you want to type  a document or a piece of code right so this is not   feasible and I’ll show you later with Vim how to  do it but for now these are the basics of creating files cool in this section let’s learn how to work  with folders or directories so you saw that we   can basically create files we can delete files  through the terminal using commands and so far   I’ve been creating folders by right clicking and  then new folder and also the same with deleting   folders right click and then basically I think  it’s moved to trash in here right so there’s   better ways of doing it and through the terminal  we can use the mkdir so this right here allows   us to create folders or directories so in here  let’s just CD into and then add documents and let   me put my font a little bit smaller just like  that clear the screen now if I want to create   a folder in here I can say mkd I bar and then  hello bar for example so this now is the name   of my folder press enter and you can see that  we have a folder in here called hello and then   bar if I want to delete a folder which is empty I  can say rmd iir so this actually will remove the   folder only if it’s empty right so here if I press  enter you can see that the folder is no longer in   here if you want to create a folder or basically  nested folders you say mkd I Dash and then P so   Dash p in here and then you can say f for slash  in here and then the bar press enter and in here   actually uh I think we had a folder called Fu  which was here so it didn’t actually create a   new folder but basically inside of Fu now you can  see that we have a new folder called bar so let   me just go back in here and what I’m going to  do is I’m going to run the exact same command   but I’m going to say for example here test and  then bar now you can see that we have a folder   called test and inside of test we have a folder  called bar now if we try to delete so let’s just   say rmdir and then the folder called test in here  press enter you can see that RM failed to remove   test because it’s empty right so rmd just deletes  the folder if it’s empty remember how to delete   the files so we can use the RM command in here so  RM dashr in here and then I’m going to say f to   basically Force delete and accept the prompt so R  for recursive and then here I can say the name of   the folder which is test now this is the key so  if I say in here for Slash and instore right so   pretty much just delete anything under test and if  I open up test you can see that we have bar so if   I press enter here this is still going to prompt  me yes or no so because we have the force here so   let’s just press n for a second so what we want to  do is just add a trailing for slash so this will   basically remove without prompting it’s just going  to remove every single folder and subfolder so if   I press enter you can see that now the folder is  gone and we kept the parent folder in here so if   you want to keep let’s say you want to keep the  parent in here so let’s just again create a new   folder so make the- p test bar let’s also say bar  and then two or three doesn’t really matter and   let’s just have two in here right so here inside  we have three folders if you want to delete them   all all you do is you say rm-rf the name of the  folder for slashstar for slash so here you could   also do a pattern right so let’s just say you  want to delete anything that ends with three for   example so three in here press enter and you can  see that only the folder that ended with three was   gone right so star means pretty much any folder  right so also if for example here so you have   bar so let’s just create a new folder inside of  bar two for example so here I’m going to say FU   press enter now within bar two we have Fu okay  so I’ve just said- P to create subfolders so if   I was to reun the command in here so this will  pretty much just delete all subfolders including   folders within folders right so if I press enter  you can see that it’s gone and we can’t go back   right because the folder doesn’t exist so the  parent which was bar two doesn’t exist so here   let me just say okay and go to documents and test  and you can see that all folders are gone if you   want to delete basically everything including  the parent all you do is so let’s just create   a new folder here so basically bar two inside  with f so this is the command and you want to   delete everything including the parent folder  which is test all you do is mkd and then Dash   oh actually sorry rm-rf so D RF or f r is the  same thing but I’ve just switch the options   and then the name of the folder test then press  enter and you can see that the folder is now gone   and this is pretty much how you create folders  but also delete contents within your folders Linux is a multi-user environment where allows  us to keep users files separate from other users   we can add a new user by using the pseudo and  then user ad- M so this is a flag that allows   you to create the home directory and then you  pass the name we can also set the password for   the particular user by using the pass WD and  then the user in question and if we want to   switch between users we use the Su command I.E  substitute user if you also want to delete the   user you can say user Dell and then here we can  pass some flags and then the user in question   but I’ll show you the flags in question as well  so and with this we have two types of user we   have a normal user that can modify their own  files this user cannot make systemwide changes   install software update system files and also  cannot change other users file so You’ seen the   pseudo command I think throughout this course but  I didn’t cover it but I’ll show you in a second   when we try to install for example a package then  we are not allowed to do that unless we use the   pseudo command and then we have the super user  in here I.E root and this user can modify any   file on the system it can make systemwide changes  such as install software and even change files on   the operating system so in this section let’s  understand basically how all of this works and   then we also touch on files and permissions  which is very important and this is actually   very important that you must understand how it  works because it’s key towards your journey in   terms of becoming a Linux administrator  if you want to follow that path but for   a regular software engineer still crucial for  you to know how this works because it’s key to Linux cool you’ve seen that if I was to type this  command and we’ll learn about package managers   later but here let’s say that we want to install  a piece of software in our machine so basically a   binary so here I think you’ve seen this APK or  I think no it’s apt and then install and here   let’s just say tree so here just say tree and we  did this before but let’s just understand exactly   what we had to do to install this software  if I press enter in here it says could not   open lock file permission denied have a look  permission denied and then it says enable to   acquire the front end log blah blah blah are  you roote well so in order for us to execute   this command successfully we need to execute  this as root I.E with the pseudo command so   the way we do it is we can type in here pseudo  so PSE sudo this is the command that we need to   use and then here I’m going to say exclamation  mark exclamation mark twice and then press Tab   and basically this just adds in the previous  command that I had in my terminal and now if   I press enter now it’s actually asking me for the  password you’ve seen this before so here I’m going   to add the password so it looks like I’m not  typing but trust me it’s hiding the password   for security reasons so just type your password  and then press enter and in fact if I basically   have a wrong password press enter it will say that  the password was incorrect so now I need to type   the password again so here I’m going to type the  correct password press enter and you can see that   basically it tries to install but this is already  installed so this dependency is already installed   as we did before similarly if we try so in here  if I try to navigate to CD and then the root so   for slash LS so in here we have couple of folders  in here but one is root so let’s just try and say   LS and then root for example press enter you  can see that it says LS cannot open directory   root permission denied so if we want to execute  this command on this particular folder we need to   execute the exact same command as root so here  we can say pseudo LS and then root or if I add   exclamation mark exclamation mark twice tab it  just brings in the previous command so this is   a nice trick that I use all the time so if I press  enter now you can see that now we are able to list   the contents inside of the root directory so for  you this might say snap or it might say something   different or maybe nothing right but you can see  that with this command we have super powers now   obviously this here you have to be really careful  how you use this command so remember I said never   do this so sud sudo rm-rf in here and then root  right because if you do this basically you are   getting rid of your entire operating system and  you don’t want to do this so obviously you need   to be careful who you choose to allow to have  the super powers and I’ll will show you this   later in a second but this is the main idea  and basically this is the pseudo command in   NHL pseudo executes a given command with elevated  Privileges and these privileges are required to   perform certain tasks which are required by admins  let’s explore pseudo even further in the next video if you remember correctly when we  do an LS so if we type LS in here so LS   and then Dash a l you can see that we have  some output in here that contains a bunch   of information so in here have a look so we’ve  got that we’ve got this we’ve got all of this   and basically we have some information and  then this is the actual file itself right   so file or directory so in this section we’re  going to focus on understanding the files and   permissions in here and also I’ll explain the  uh output from the ls command so in here if   you remember correctly so if I type in here  ls- Dash and then help and then scroll up in   here so remember the dash so Dash and then l  in here use a long listing format so that’s   why you see all of the information and then  – A as well for Eden file in here so do not   ignore entry that start with DOT right which is  basically all of this right so this dot in here   so the dot files are for the- a and then the  L is for long listing which is for all of this   information in here cool let’s go ahead and uh  start learning about Linux files and permissions next in here I do have this awesome diagram where it  teaches about the output of the command ls- L and   more specific we’ve got the permissions here  which is the core of this section but let me   actually start from here and explain the output  for uh ls- L now in here you can see that we have   the folder name or the file basically the name of  the file that you list within that directory so in   our case we got food. txt as well as di so this  is the name of a folder in here and this could   be literally anything then we have the date and  time and this more specific is the last modified   date and time okay so if you create the file  so that will basically be the creation time and   if you change or modify the file then this will  reflect then we have the size so for a file this   is 4 kilobytes then for a directory this is 4,000  kilobytes and basically the total of whatever is   inside of the folder last section you’ve learned  about groups so this is the group name so to which   group the file belongs to so in this case Amigos  code so both files and then we have the owner so   the owner is the user so in my case Amigos code  earli on you saw that we created a user called   Jamal so this also will reflect then here we have  the number of hard links so two and one and we’ll   come back to hard links later then we have in here  the permissions and the very first character in   here so basically this so excluding D basically I  can’t select it but basically the first character   of this sequence in here it’s always the file  type and then we have the set of permissions   now for the file type in this case d stands for  for directory and then Dash stands for basically   a regular file now when it comes to permissions  this is divided into three sections as I said the   first one is the file type and then and then rwx  rwx r-x in here so basically what this means is   read write and execute R for read W for write and  X for execute the first three characters belongs   to the user so this means that a user can perform  a set of actions on the file type the second set   of characters so the first three for the user  the second three for the group so these are group   permissions and the last three are for everyone  else or others so if it doesn’t belong to the   user nor the group then the rest of of the world  and here’s an example so for example for this file   in here called f.txt so you can see that the file  type in here Dash so it’s a file read W and then   Dash so this means that Amigos code user can only  read and write it cannot execute and we’ll come   back to execute in a second so once we create a  Bash script but also for folders execute Works   a little bit different then the next three set  of characters read write and then Dash so when   it’s a dash it means that there’s no permissions  in there so here Amigos code group so the group   can read and write and then the last three are  dash dash it means that anyone can literally   read so we’ll go into details uh in a second in  terms of the actual permissions but this is the   general overview of the Linux file permissions  and they more specific when you perform ls- L   this is basically the output but as I said in  this section we want to focus on the permissions themselves we’re done with Linux and that’s not  Myer feat you’ve learned about some key commands   and you’re already on your way to becoming  an expert but how do we group those commands   together well that’s where shell scripting  comes in is shell scripting like a programming   language such as python or goang exactly  so you learn about conditions and Loops you   learn about functions how to do effective error  handling and that’s not all we have challenging   exercises waiting for you to put your skills  to the test I’m looking forward for it so am I scripting is where Linux comes in really handy  let’s dive into shell scripting a game changer   for anyone who wants to automate tasks in Linux  first things first what is Bash Bash stands for   Born Again shell a bit of a fun name isn’t it  it’s essentially a command line interpreter   which in simple terms means it’s your gateway  to communicate with your computer using text   based commands with bash you boost efficiency  Skyrocket productivity and can effortlessly   streamline tasks that might otherwise be tedious  think of bash as a way to create a sequence of   commands automating tasks and Performing complex  operations without breaking a sweat now how do   you write these magical scripts all you need to  start is an editor it could be as simple as Vim   which we’ve covered in this course or a feature  editor like Visual Studio code your choice once   you’ve penned down your script save it with  the extension Dosh which tells your system   hey this is a bash script now let’s explore  some fundamental elements of bash scripting   as we talk remember the true understanding  comes from practical application which we’ll   delve into shortly first up variables think of  them as containers they store and manipulate   data for you typically denoted by something like  dollar Vore name variables can hold a variety of   data be it strings numbers or even arrays  moving on to conditionals they are scripts   decision makers allowing it to make choices  based on specific conditions based on whether   something is true or false different blocks of  code will run making your scripts Dynamic and   responsive next up loops loops let you repeat  instructions over and over as needed with for   loops and while Loops you can iterate over  lists sift through directories or continue   a task until a specific condition is met last  but not least functions imagine grouping a set   of commands into one block you can call upon this  block or function multiple times throughout your   script they’re the essence of code reusability  modularity and organization in your script which   is a very key component when it comes to script  writing and there you have it an introduction to   Shell scripting with bash while this is just the  tip of the iceberg armed with these fundamentals   you’re well in your way to master the art of  scripting Linux so without further Ado let’s get started let’s write a simple script to get  a taste of B scripting in this example we’ll   create a simple script to greet the user first  let’s create our script we can use the touch   command followed by the name of our script let’s  call it my first script and make sure you use the   extension Dosh which indicates that these are  bad scripts let’s now open our file using Vim   my first script.sh now the first line of every  file starts with a shebang line don’t worry too   much about this line at the moment we’ll cover  this in a future video now we Echo hello world   in our script and then we can escape and then  we can save our file using coal WQ exclamation   mark now because scripts are executables we  have to also CH mod our script using CH mod   and we can use the symbolic notation plus X  followed by the script name my first script   and now we can run our script using the dot for/  prefix and my first script and there you have it   H world now this is just a basic example but  B scripting allows you to do so much more you   can manipulate files process data automate  backups and perform complex operations all   through the power of scripting so to become  proficient in B scripting it’s essential to   understand the fundamental concepts that form  the building blocks of scripting let’s briefly   cover some of these Concepts and that’s  all for this video I’ll see you in the next one in this video we’ll delve into an important  concept called shibang the shebang also known as a   hashbang or interpreted directive plays a crucial  role in the execution of bash scripts so let’s   first create a file we can just touch greet Dosh  for example and then press enter now we briefly   touched upon shebang line in the previous video  and that’s the first line that you find in any   bash script where you have followed by bin bash  this line is a she and it serves as a directive   to the operating system on how to interpret the  script in this case we’re asking the system to   interpret the script using the binary bash so the  path after the exclamation mark is essentially   pointing to the specific interpreter or shell that  should handle the script the shebang line provides   flexibility by allowing you to specify different  interpreters or different types of scripts for   example if you’re writing a python script you can  use a shebang line that instead has user being   Python and then you can decide if you want Python  3 or python 2 to ensure the script is executed   using the python interpreter and similar for  scripts written in Ruby for example you’ll just   change this binary to Ruby and so on now let’s  see the impact of the shebang connection suppose   in this bad script we want to print hello world  for example we want to write a greeting message   so first let’s write our she bang with bin bash  and then we do Echo hello world and then we escape   and then colon WQ to save this now remember B  scripts are executables which means we need to   give it the executable permission so to do this  we use a CH mode command followed by the symbolic   notation to give it executable permission so we do  plus X followed by the name of the file so greet   Dosh and then we press enter now this file is an  executable so we can check that this is the case   by running LS followed by the long form option  and as as you can see our greet Dosh file now has   executable permissions which is the X here okay  let’s clear our screen now to run this we can use   a for/ prefix followed by the script name and then  we press enter and as you can see it prints hello   world now this is only one way to run this bash  script we can also use the command sh to run the   bash script so greet Dosh and that gives you the  same thing and we can also use Bash read.sh and   we press enter this is for when you don’t specify  The Interpreter within the bash script so if we   remove our bin bash line or or a shebang line in  the bash script we can use these two commands to   interpret this script as bash great now the She  Bang is not limited to just the bash shell you   can use different interpreters depending on your  needs and by specifying the correct interpreter   in the shebang you ensure that your scripts are  executed consistently regardless of which sh or   environment they’re running so a quick summary the  shebang line starts with the hash followed by an   exclamation mark it specifies The Interpreter or  shell that should handle the script it enables   consistent execution of scripts across different  environments regardless of whatever shell you’re   using even though we’re using the zsh Shell here  it was still able to interpret the GRE Dosh file   as a bash script you can specify different  interpreters for different types of scripts   and the she bang line should be placed as the  first line of the script without any leading   spaces or characters before it and that’s it  thanks for watching and I’ll see you in the next one in a previous video we learned how to run  scripts using slsh and Bash so let’s recall our   simple script greet Dosh so if I do a cat greet  Dosh we can see that this script prints hello   world right now we can run it from its current  directory using for/ greet Dosh but what if we   want to run it from anywhere without specifying  its path well the trick is to place our script   in one of the directories that’s in our path  environment variable the path is an environment   variable that tells the shell which directories  to search for executable files in response to   commands so let’s clear our screen and if I do an  echo of the path environment variable we can see   that there are several directories separated  by colons any executable file placed in one   of these directories can be run from anywhere in  the terminal now a common directory to place user   scripts is user local bin that’s this directory  over here so let’s move our greet Dosh file into   this directory and give it executable permissions  now for this we are going to use pseudo because it   requires super user permissions to move scripts  into this directory so we run PSE sudo and then   move and then our script greet Dosh and we’re  going to move this to user local bin and we’re   also going to change the name to greet so it  becomes easy to run later on so now we can press   enter it will ask you for your password so enter  your password so that’s moved greet Dosh into the   user local bin directory now remember you also  have to CH mod since this is a script so once   again pseudo CH mod with the plus X symbolic  notation followed by user local bin and then   greet so we press enter now the reason we changed  the name to greet is so that for Simplicity this   is how we will call it now let’s clear our screen  now if I has to run the command greet just like   this it will give me hello world without using sh  without using the current directory and if I was   to also change it directory and call greet it will  still work so if I change directory to let’s say   desktop for example I can also run it from here as  GRE so you can see we were able to run our script   using just its name without needing to specify  any path or use for/ sh or bash so to recap by   adding our script to one of the directories in  a path environment variable we can conveniently   run it from anywhere in our terminal this can be  incredibly useful as you build up a library of   custom script just be cautious though and ensure  the scripts you add to Global paths are safe and   intended for Global use and that’s all for this  video Happy scripting and I’ll see you in the next one in this video we’ll explore the concept of  comments and how they can enhance the clarity   and understandability of your script comments  are lines in a script that are not executed as   part of the code instead they serve as informative  text for for us reading the script adding comments   to your scripts is considered a best practice  because it helps you and others understand the   purpose functionality and logic of the script so  let’s take a look at how comments are Written In A   bash script in bash there’s two types of comments  you have a single line comment and a multi-line   comment so let’s first go into our greet Dosh  file VM greet Dosh and then press enter now we   know what the script does it prints hello world  to the console when we run the script so first we   can press I to insert and to write a single line  comment simply start the line with the hash symbol   anything following the hash symbol on that line  will be treated as a comment so print greeting   to the console for muline comments you can enclose  the comment text between colon with single quotes   and then we can have our comments within the lines  enclosed between the single quotation marks so   anything between 6 and 9 will now be considered  a comment this is a multi-line comment and we can   just get rid of this line as well so Escape great  now if I was to exit and save this file and rerun   GRE Dosh you’ll notice that it only prints hello  world even though that in our GRE Dosh file we   have these two lines but because they are being  taken as comments they are therefore not executed   now let’s see the Practical benefits of comments  in action consider a bash script that renames all   txt files in a directory to have a Bak extension  so what we do here is VI extensions. sh file and   then press enter and here we have a for Loop  without comments the script may appear cryptic   especially for someone unfamiliar with the purpose  and inner workings of this for Loop especially for   someone who’s new to B scripting who doesn’t  really know how to write for Loops so in our   case it’s very important for us to write comments  here to improve the understandability so we start   with our hash and then we add our comment so what  we’re doing in this for Loop is renaming all txt   files Tob so we’re changing the extension of the  file now we can use multi line comments to add   more detail as to what the script is doing so to  do this we start with a colon and then the single   quotation mark and also close this with a single  quotation mark So now anything inclosed between   these two quotation marks would be considered  a comment so we can write explanation and then   what we’re doing is looping through all. txt  files in the current directory we are using   the move command as you can see move command to  rename each. txt file to do B and finally the   this part of the code is the syntax so the and  then we can paste that here is the syntax that   removes the txt extension and the pens B okay  let’s save the script WQ and exit let’s just   now cut this file and let’s zoom out a little  bit now notice by adding comments throughout   the script we can provide explanations and context  as to what the script is actually doing making it   easier for others and ourselves to understand the  script’s intention so comments not only help with   the script comprehension but also enable you to  temporarily disable or exclude specific sections   of code without deleting them let’s say we did  want the script to run these three lines or we   we can actually prevent those lines from running  by turning them into comments so let’s go back   into our file and what we do is let’s first do an  i and then add a hash in front of this so now it   turns into a comment and same for the remaining  two lines now you can see this script essentially   won’t run anything because now we’ve turned all  our commands into comments we can exit and we can   save this if we tried running the script we do  for/ extension. sh oops wrong file okay we get   permission denied because it’s not executable so  let’s make it executable sh and then rerun as you   can see nothing happens because all our commands  have now been commented okay and that’s all you   need to know about comments and how useful they  are within our scripts so by adding comments to   your scripts you improve the readability you  can you know Foster collaboration within your   team and you can ensure that the scripts purpose  remains evident throughout the life cycle of the   script so other people can read what the script  is doing and so later if changes need to be made   you know where those changes need to happen okay  thanks for watching and I’ll see you in the next one in this video we’ll delve into the world of  variables variables are an essential component   of bash scripting as they allow you to store and  manipulate data it makes your script Dynamic and   flexible in bash variables are like containers  that hold data such as text strings numbers or   even arrays they provide a way to store values  that can be accessed and modified throughout the   script so let’s look at how variables are created  and used in bash script to create a variable you   simply assign a value to it using the assignment  operator so let’s first create a file and call   this file. SH now first in this file let’s begin  with our shebang b bash and then let’s also assign   a variable called greeting and we can assign it  to the string hello world to access the value of   this variable you prepend the variable name with a  dollar sign so we start with dollar greeting let’s   say we want to use the echo command to Output  the value stored in greeting we just start with   Echo followed by Dollar greeting and then we can  escape and save our file make sure you CH mod your   script to give it executable permission v.sh and  then the/ prefix to run the script and there you   have it hello world now variables in bash are not  constrained to a specific data type they can hold   different types of data such as strings numbers  and arrays let’s create a variable that we can   assign a number so let’s reopen our v.sh and let’s  assign another variable I use all my keyboard to   go to the next line and we can assign the count  variable to the number 42 for example so as you   can see I’m not enclosing the number 42 within a  string because I want this bad script to interpret   this as a number and not a string right and then  we can call this variable using the same format   Echo count then let’s exit save our file and run  our bash script v.sh and there you have it it   prints the number 42 as well as our hello world  now variables can also hold an array so let’s   create another variable called fruits and assign  it to the values apple banana and orange so we do   that using parentheses first element will be apple  second element banana and the third element orange   and then you close your parenthesis and there you  have it the fruits variable assigned to this array   now you can also use variables within strings to  create Dynamic output this is known as variable   interpolation let’s see how we can do that let’s  assign a variable name to the name let’s say armid   for example we can now Echo and then within our  string we can use variable interpolation to say   hello to this variable name and Let’s Escape and  WQ to save and let’s call a.sh and there you have   it hello armid so it’s taken the name variable and  assigned it with within our string so essentially   we’re doing variable interpolation in this case  so the value stored in name is inserted into   the string using the dollar name syntax great  let’s summarize what we’ve learned variables   are created using the assignment operator  equals to access the value of a variable   we prend the name of the variable with a dollar  sign variables can hold different types of data   such as strings numbers and arrays and variable  interpolation allows you to use variables within   strings to create Dynamic output and that’s  all for variables I’ll see you in the next one in this video we’ll dive into the topic of  passing parameters to bash scripts by allowing   inputs from the command line you can make  your script more versatile and interactive   bash scripts can receive input values known  as parameters or arguments from the command   line when they are executed these parameters  allow you to customize the behavior of your   script and make it more flexible let’s look  at how to pass parameters to a b script when   running a script you provide parameters after  the script name so for example let’s say we   had a script.sh file we pass parameters just  like this parameter 1 parameter 2 and so on so   when running a script you provide the parameters  after the script name separated by spaces so the   parameters are all separated by spaces so in  this example we’re executing a script called   script.sh and passing two parameters parameter  1 and parameter 2 inside the B script you can   access these parameters using special variables  dollar one doll two and dollar three let’s look   at an example let’s create the script.sh file and  let’s start with our Shang bin bash and let’s say   we wanted to echo three parameters let’s say  the first parameter parameter one and we use   use a special variable so dollar one which  basically grabs the value of the parameter   passed into the script when we run the script  let’s say we have these lines three more times   so let’s just copy this line here copy and then  paste let’s say now parameter two we have two   and then for parameter three we have three so in  this script snippet we’re using the echo command   to display the value of these three parameters so  Let’s Escape and save this file now when I call   the script.sh I can pass in a parameter so let’s  say the first parameter let’s call it hello and   second parameter hi then press enter as you can  see because we’ve only passed in two parameters   it only prints the first two hello and hi because  this is taken as dollar one and this is taken as   dollar two if I was to pass in a third parameter  let’s call it hey and press enter now we have a   third parameter and it is printed in this third  line excellent so when executing the script with   parameters the values passed on the command line  will be substituted into the scripts parameter   variables dollar one doll two and doll 3 now what  if we wanted to access all the parameters passed   into a script we can do this using a special  variable so let’s go into our script.sh let’s   add another line and let’s say we want to Echo  all parameters right we use a special variable   followed by the at symbol and then quotation  marks and then now let’s save the script and   now when we run it we get all parameters and then  the parameters that we’ve passed into the script   in other words the echo command in that line  will output all the parameters passed to the   script great let’s summarize what we’ve learned  parameters are provided after the script name when   executing a script inside the script parameters  can be accessed using dollar one do two doll three   and so on based on their position and the special  variable dollar at can be used to access all the   parameters pass to the script so by allowing  inputs through parameters you can make your   script more interactive and versatile great that’s  all for this video and I’ll see you in the next one phew well done for reaching  the end of this course but your   journey doesn’t stop here whether  you’re taking the devil’s path or   the software engineering path well it’s  only the beginning we have courses to   help you on this journey it was a pleasure  teaching you and we’ll see you in the next one Assalamualaikum

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • Full Stack Learning Management Application Development

    Full Stack Learning Management Application Development

    The text details the creation of a full-stack learning management application using Next.js, Node.js, and AWS. It covers the development process step-by-step, including front-end UI construction with ShadCN components and Tailwind CSS, back-end API design with database interaction, authentication via Clerk, and payment integration with Stripe. The tutorial extensively explains the use of Redux Toolkit Query for efficient data fetching and management. Finally, it addresses features like course creation, editing, and user progress tracking.

    Learning Management Application Study Guide

    Quiz

    1. What is the primary function of Node.js in the context of this application? Node.js is a server-side JavaScript runtime that allows JavaScript code to be executed on the server. In this application, it enables the creation of a backend that can handle requests and data management.
    2. Explain the purpose of npx create-next-app in the project setup. npx create-next-app is used to create a new Next.js application with a default configuration. This provides a quick start for building the frontend of the application.
    3. What are two essential VS Code extensions recommended in the source, and what are their purposes? The two essential extensions are ES7+ React/Redux/React-Native snippets, which helps create React components, and Prettier, which formats code automatically upon saving, ensuring consistent formatting.
    4. Describe the role of Clerk in the application. Clerk is an authentication service that is used to handle user sign-up, sign-in, and profile management within the learning management system. It simplifies the process of managing user accounts.
    5. What is Tailwind CSS, and how is it used in the project? Tailwind CSS is a utility-first CSS framework. In this application, it is used to style components by applying predefined classes, which are imported in a global CSS file, avoiding the need to write custom CSS from scratch.
    6. Why is DynamoDB chosen as the database for this application, and what type of database is it? DynamoDB is chosen for its scalability, performance, and suitability for applications with fewer tables and relationships. It is a NoSQL database and allows you to store data, in this application, such as courses, transactions, and user progress.
    7. What is the significance of the “non-dashboard” layout in the application? The “non-dashboard” layout is used for pages that do not require user authentication or are not part of a user dashboard. This includes the landing page, course search, and authentication pages.
    8. Explain the difference between the course object and the user course progress. The course object stores core course information such as the title, description, and teacher ID. The user course progress tracks how much progress a single user has made in a specific course, including how much they’ve completed. This is a separate object to avoid a massive object in the case of multiple users.
    9. What is the purpose of Shadcn UI libraries in this application? Shadcn UI libraries provide pre-built, accessible, and customizable React components. In this project, they are used to quickly build UI elements such as buttons, forms, and dropdowns with consistent styling.
    10. What is a payment intent in the context of Stripe, and how does it relate to the backend? A payment intent is a Stripe object that represents a customer’s intent to pay. The backend of the application creates a payment intent, and then the frontend uses this to process payments.

    Essay Questions

    1. Discuss the architectural choices made in the development of this full-stack learning management system, considering the trade-offs between different technologies and approaches. How do these decisions contribute to the scalability and maintainability of the application?
    2. Analyze the data modeling approach used in this application. Why were separate data structures used for course information and user course progress, and how do these choices impact the performance and complexity of the system?
    3. Evaluate the use of serverless functions (AWS Lambda) in this project. What are the benefits and challenges of using this technology, and how does it align with the overall goals of the learning management application?
    4. Explain the role of third-party services, such as Clerk and Stripe, in this learning management application. How do these services simplify development, and what are the potential drawbacks of relying on external providers?
    5. Describe the process of deploying and managing this application on AWS and Vercel. What steps were taken to ensure the security, performance, and reliability of the deployed system?

    Glossary of Key Terms

    AWS (Amazon Web Services): A cloud computing platform providing various services, including storage, computing power, and databases.

    API Gateway: An AWS service that acts as a front door for applications to access backend services. It helps in securing and managing APIs.

    CORS (Cross-Origin Resource Sharing): A browser security mechanism that restricts web applications from making requests to a domain different from the one that served the web application.

    Clerk: A third-party service for managing user authentication and authorization in web applications.

    CloudFront: AWS’s content delivery network (CDN) service. It stores content and delivers it from edge locations closer to the user, improving loading times.

    Container: A lightweight, standalone executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries, and settings. Docker is an example of container technology.

    Docker: A platform for developing, shipping, and running applications in containers.

    DynamoDB: A fully managed, serverless NoSQL database offered by AWS. It is designed for scalability and high performance.

    ECR (Elastic Container Registry): A managed Docker container registry that allows developers to store and retrieve Docker container images.

    Framer Motion: A library used for adding animations to React components.

    IM (Identity and Access Management): A service provided by AWS that helps in managing access to resources. It is used to create roles and manage permissions.

    Lambda: A serverless compute service by AWS that allows running code without provisioning or managing servers.

    Middleware: Software that provides services and capabilities that can be applied across different parts of an application.

    Molter: Middleware for handling multipart/form-data, which is primarily used for uploading files.

    Next.js: A React framework for building full-stack web applications. It provides features such as server-side rendering and routing.

    Node.js: A JavaScript runtime that allows JavaScript code to run on the server.

    NoSQL: A type of database that is not based on the traditional relational model (SQL). It is suitable for handling unstructured or semi-structured data.

    npm: The package manager for Node.js. It is used for installing and managing packages needed in a project.

    npx: A tool that executes npm packages.

    Redux Toolkit Query: A data fetching and caching solution built on top of Redux.

    Shadcn UI: A library of pre-built and customizable UI components for React applications.

    SQL: Structured Query Language is a language for managing and querying data in relational databases.

    S3 (Simple Storage Service): A scalable object storage service by AWS.

    Serverless: A cloud computing execution model where the cloud provider manages the infrastructure, and developers only focus on writing and deploying code.

    Stripe: A third-party service that provides payment processing infrastructure for applications.

    Tailwind CSS: A utility-first CSS framework that provides low-level utility classes to style HTML elements.

    TypeScript: A strongly typed superset of JavaScript that adds static typing to the language.

    Vercel: A platform for deploying and hosting frontend web applications, with a focus on performance and ease of use.

    VPC (Virtual Private Cloud): A virtual network in AWS that allows users to launch AWS resources in a logically isolated network environment.

    Full-Stack LMS Application Development

    Okay, here is a detailed briefing document summarizing the provided text, including key themes, ideas, and quotes:

    Briefing Document: Full Stack Learning Management Application

    Overall Theme: This document details the step-by-step construction of a complete, production-ready Learning Management Application (LMS). The application utilizes a Next.js frontend, a Node.js backend, and AWS for deployment, aiming to be a comprehensive portfolio piece. It stresses beginner accessibility by explaining concepts in simple terms, and the creator encourages the audience to use parts or the whole project in their own portfolios.

    Key Ideas and Facts:

    • Application Overview:The LMS features a landing page with animations, course listings, user signup/login (Clerk authentication), user profiles, billing, and course creation capabilities.
    • The application is intended to be production-ready with its own set of use cases.
    • “This application is probably one of the most extensive applications I’ve ever built on YouTube and I might even use this for my own purposes of creating a course.”
    • Frontend Technologies (Next.js):Utilizes Next.js for the frontend framework, building components with React.
    • Leverages Tailwind CSS for styling, with many classes pre-defined for rapid development, instead of spending time styling.
    • Imports Google Fonts (DM Sans) for styling.
    • Uses Shadcn for pre-built UI components and theming, enhancing the overall development process.
    • Implements framer-motion for animations, primarily for transitions and loading states.
    • Redux Toolkit Query is used for efficient data fetching and state management.
    • “We’re just going to be using those classes for our Styles they are already using Tailwind classes we’re going to be using those and we’re just going to apply those classes directly onto Those comp components”.
    • Backend Technologies (Node.js):Employs Node.js as the server-side JavaScript runtime.
    • Uses Express.js for creating the API endpoints.
    • DynamoDB (NoSQL) is selected as the database with data being persisted locally during development.
    • Dynamus provides schema validation and database interaction for DynamoDB
    • “Dynamo DB excels more so than mongod DB if you have less tables ideally you have less tables”
    • The app utilizes AWS SDK for direct database access.
    • Includes an environment variable configuration system with .env files.
    • Utilizes Multer to handle file uploads on the backend.
    • Database Design (DynamoDB):Data is modeled using three core schemas: course, transaction, and user course progress.
    • A key point is the separation of user course progress from the main course object to manage large amounts of data efficiently and prevent single object bloat.
    • “we do not store the progress of the user because you know how the user watches a video they are progressing through and we need to save information on how far they have gotten in that course whether they completed a certain section or a chapter that is where the user course progress is aligned.”
    • The project uses DynamoDB local for development, with persistence using dbPath config.
    • DynamoDB was chosen as it is well suited to the project’s data needs, as it has relatively few tables and is highly scalable.
    • “Dynamo DB is much more fast and performant and skills but it is even worse than mongod DB and document DB of complex filtering and sorting.”
    • Authentication (Clerk):Clerk is used for handling user authentication.
    • Middleware routes are created to protect specific pages (user/teacher dashboards) based on user roles.
    • Uses Clerk Provider to wrap the application for state and data management, and middleware to determine which routes require authentication.
    • User roles are stored in Clerk metadata as either “student” or “teacher”.
    • The project creates a separate “auth” folder for auth related pages.
    • Payment System (Stripe):Integrates with Stripe for handling payments.
    • The backend creates Stripe payment intents that connect directly to the front end.
    • The project integrates a Stripe Provider to wrap around payment content pages.
    • The project uses react-stripe-js to handle stripe functionality on the frontend.
    • UI Components & Styling:Emphasizes the usage of existing styles (Tailwind) and pre-built components (Shadcn) to avoid spending too much time doing styling.
    • Utilizes the Sunner library for creating toast notifications for user feedback.
    • Custom UI components are built to reuse common functionalities.
    • Loading screens and animations enhance the UI and user experience.
    1. Course Creation and Management:
    • Allows users with teacher roles to create courses by populating a course form.
    • Chapters and Sections can be added to courses via modals.
    • The application supports editing and deleting of courses, sections and chapters, and the ability for teachers to edit and upload videos, though this is implemented later in the series with S3 bucket.
    • State Management (Redux Toolkit):Uses Redux Toolkit and RTK query for handling client state and making API requests.
    • Custom base query is configured to show toast notifications from the API response.
    • Redux is used to manage the application’s state, like whether modals are open.
    • The project uses Redux toolkit query to handle API requests.
    • AWS Deployment:Application is deployed to AWS using Lambda, API Gateway, and S3.
    • Docker is used to containerize the backend application and deploy it to ECR.
    • IAM roles are configured to grant necessary permissions for Lambda to access other AWS services.
    • CloudFront is used for CDN to make loading video fast for users.
    • Vercel is used to host the front end application because the creator faced issues using AWS Amplify.
    • A basic budget system is recommended using AWS billing so that developers are not charged extra.
    • “. The Lambda is going to take some time to load it’s not that much but there is a little bit of delay if someone H if you don’t have assistant users constantly using your application”
    • Code Organization and Setup:The project is broken into several major directories, including client, server, and source.
    • The server has different folders for utils, seed, models, routes and controllers.
    • The client has different folders for components, app, lib, state and types.
    • The project uses typescript for both the client and the server and has necessary types installed for various libraries.
    • The project uses a custom base query to have consistent error handling across different API requests.

    Important Quotes (reiterated for emphasis):

    • “This application is probably one of the most extensive applications I’ve ever built on YouTube and I might even use this for my own purposes of creating a course.” (Emphasis on scope and usability)
    • “We’re just going to be using those classes for our Styles they are already using Tailwind classes we’re going to be using those and we’re just going to apply those classes directly onto Those comp components.” (Emphasis on rapid development with pre-defined styling.)
    • “Dynamo DB excels more so than mongod DB if you have less tables ideally you have less tables” (Reasoning behind database choice.)
    • “we do not store the progress of the user because you know how the user watches a video they are progressing through and we need to save information on how far they have gotten in that course whether they completed a certain section or a chapter that is where the user course progress is aligned.” (Emphasis on data modeling best practice)
    • “Dynamo DB is much more fast and performant and skills but it is even worse than mongod DB and document DB of complex filtering and sorting.” (Discussion about pros and cons of the chosen database)
    • “The Lambda is going to take some time to load it’s not that much but there is a little bit of delay if someone H if you don’t have assistant users constantly using your application” (Emphasis on cold start)

    Conclusion: This source provides a thorough walkthrough of building a modern web application from start to finish. It covers a broad range of technologies and best practices, making it a valuable resource for developers interested in full-stack development, cloud deployment, and understanding the interplay between various web components and services. The emphasis on production readiness and beginner accessibility makes it suitable for developers of all skill levels.

    Full-Stack LMS Application Development

    Frequently Asked Questions: Full-Stack Learning Management Application

    • What is the purpose of this application being developed? This project aims to create a comprehensive, production-ready Learning Management System (LMS) with a Next.js frontend, Node.js backend, and deployment on AWS. It’s designed to be a full-stack application that could be used for course creation and delivery. The application provides features for user authentication, course browsing, user settings management, and billing. The creator of this project also mentions that it can be used as a reference or portfolio project for other developers.
    • What technologies and tools are used in this project? The project utilizes several key technologies:
    • Frontend: Next.js for the user interface and React components, along with styling using Tailwind CSS and Shadcn UI components. Additional libraries like Framer Motion are used for animations and React Player is used for video playback.
    • Backend: Node.js and Express.js for the server-side logic, with AWS SDK for interacting with AWS services like DynamoDB. Data validation is done with ‘Dynamus’ and unique IDs are created using uuid.
    • Authentication: Clerk is used to manage user authentication and authorization including sign-up, sign-in, profile management, and session handling.
    • Database: DynamoDB (local for development and cloud-based on AWS for production) is chosen as the NoSQL database.
    • Cloud: AWS is used for hosting the application, including ECR for storing Docker images, Lambda for the backend server, S3 for storage, and CloudFront for content delivery. Vercel is used for hosting the front-end application. Other tools include npx, prettier, Visual Studio Code, pesticide, redux dev tools.
    • How is the user authentication handled in this application? User authentication is managed by Clerk, a third-party service that provides a comprehensive authentication platform. Clerk handles user registration, email verification, sign-in, and profile management. It also manages sessions and provides necessary components for easy integration with the frontend. The application also stores user types (student or teacher) in Clerk metadata. The application also uses a middleware that protects certain routes that can only be accessed through authentication using Clerk.
    • Why was DynamoDB chosen for the database? What are its advantages and disadvantages in this context? DynamoDB, an AWS NoSQL database, was chosen for its scalability, performance, and cost-effectiveness. Its advantages include:
    • Scalability and performance: DynamoDB is well-suited for handling large amounts of data and high-traffic applications with fast reads and writes.
    • Cost-effectiveness: It provides a generous free tier for developers and is generally cost-effective when scaled.
    • No complex relationships: This project’s schema is simple with only 3 tables, making DynamoDB a viable option. However, DynamoDB has disadvantages:
    • Not ideal for relationships: It is not ideal for complex relational data structures, hence not best practice to store nested data.
    • Filtering and sorting: It is not as strong at complex filtering and sorting of data compared to other NoSQL databases like MongoDB.
    • Data Nesting: DynamoDB isn’t well suited for nested data and can lead to dense data structures if not handled properly.
    • How is the data structured in this application (data modeling)? The data is structured with three main entities:
    • Course: Stores all details of a course, including teacher ID, title, description, price, and category.
    • Transaction: Contains details for each transaction or payment made including information about payment providers.
    • User Course Progress: Stores a user’s progress in a specific course, including completed sections and overall progress. This is separated from the main course object to avoid a large and dense data structure. This design decision prevents excessive data in the main course object when there are multiple users associated with the same course.
    • How is the backend API built and how can you test it? The backend API is built using Node.js, Express.js, and AWS SDK. It is structured with controllers containing the logic, models for the schema of our data, and routes to connect the endpoints. The setup is done by importing necessary modules and then the app is set up to use middleware such as express.json(), helmet(), and morgan() to handle and log request and security. The routes are then set up to handle different endpoints.
    • Testing the backend API can be done through tools like curl (directly in the terminal) or through a UI tool like Postman for making API calls and inspecting responses. Locally, the server is run through npm run dev, while building for production runs with npm run build.
    • How are payments integrated into the application? Payments are integrated using Stripe. The application utilizes the Stripe JavaScript library (stripe.js) along with @stripe/react-stripe-js. This setup is used to create payment intents on the backend, and to process payments through the client side. React context is used to manage payment information. The checkout flow involves steps to get course information, handle payment details and the creation of a client secret key, and finally the rendering of payment information before completion. This is all done with a Stripe provider.
    • How is the application deployed and how is a serverless function used? The application is deployed using several AWS services and Vercel. Here’s how it works:
    • Frontend Deployment: The frontend is deployed using Vercel, a platform that simplifies the deployment of front-end applications.
    • Backend Deployment: The backend is packaged into a Docker container and deployed on AWS Lambda. The Docker image is stored in AWS ECR (Elastic Container Registry) and is used by the Lambda function. Lambda provides a serverless compute service that runs the application code.
    • API Gateway: An API Gateway is used as a front-end for the Lambda function, providing a secure endpoint for the frontend to interact with the backend logic and routes.
    • Serverless Logic: The server uses the serverless-http library for compatibility with the serverless environment. The Lambda function has permissions granted using IAM roles that are assigned for different AWS services, allowing access to DynamoDB and S3.
    • S3 and CloudFront: AWS S3 is used to store static assets or files. AWS CloudFront is set up as a CDN (Content Delivery Network) to distribute the content to users for faster loading times.
    • The serverless function is used by exporting the Lambda handler. The Lambda handler handles seed functions in the database and defaults to the serverless app function otherwise.

    Full-Stack Learning Management Application Architecture

    The sources describe a full-stack learning management application built with a Next.js frontend, Node.js backend, and deployed on AWS. Here’s a breakdown of the key components and technologies used:

    Application Overview

    • The application includes a landing page with animations, a course catalog, user authentication, user profiles, billing information, and course progress tracking.
    • It is designed to be a production-ready application with a focus on scalability and customizability.
    • The application is also responsive, adapting to different screen sizes.

    Frontend Technologies

    • Next.js: Used as the primary framework for building the user interface.
    • Redux Toolkit: Manages the application state.
    • Redux Toolkit Query: Handles API interactions with the backend.
    • Tailwind CSS: Provides styling along with the Shadcn component library.
    • TypeScript: Used for type checking.
    • Framer Motion: Implements animations.
    • React Hook Form: Handles form management and Zod for form validation.

    Backend Technologies

    • Node.js and Express: Used to create the backend API, separate from the Next.js frontend, to enhance scalability.
    • Docker: The backend is containerized using Docker for consistent environment packaging.
    • AWS Lambda: Hosts the backend, using the Docker image from ECR.
    • API Gateway: Securely routes requests to Lambda functions.
    • DynamoDB: Serves as the NoSQL database.
    • S3: Handles storage of video content.
    • CloudFront: Used as a content delivery network for videos to ensure low latency and high availability.

    Authentication

    • Clerk: A third-party service is used for user authentication, offering pre-built components for sign-in, sign-up, and user management. It is used instead of AWS Cognito due to its easier setup.

    Deployment

    • AWS: The application utilizes a serverless containerized architecture on AWS.
    • Vercel: Hosts the Next.js frontend, integrating with other AWS services.

    Key Features

    • Course Management: Users can browse courses, view course details, and track their progress. Teachers can create and edit courses.
    • User Authentication and Management: The application uses Clerk for user authentication, profiles, and roles.
    • Billing: The application uses Stripe for payment processing.
    • Responsive Design: The application is designed to adapt to different screen sizes.

    Development Process

    • The development process includes setting up Node.js, NPX, and Visual Studio Code.
    • The project utilizes various libraries and extensions for React development and code formatting.
    • The application also uses a custom base query to format API responses, handling data and error messages.
    • The application is deployed on AWS using services such as Lambda, API Gateway, DynamoDB, S3, and CloudFront.
    • The deployment also includes setting up IM roles to manage permissions for Lambda to access other AWS services.

    Data Modeling

    • The application uses a NoSQL database, DynamoDB, due to the nature of the data and relationships.
    • The data model includes courses, sections, chapters, user progress, and transactions.
    • User progress is stored separately from course data to prevent overly large data objects.

    Additional Points

    • The application emphasizes learning backend and deployment skills, not just frontend.
    • The use of a custom base query in Redux Toolkit Query provides a way to format API responses and display toast notifications for successful mutations.
    • The application also utilizes custom form fields for managing user settings.
    • The application uses Shaden UI components for styling.

    This detailed overview should give you a solid understanding of this full-stack learning management application.

    Full-Stack Learning Management Application

    The sources detail a full-stack learning management application with a variety of features and technologies. Here’s a breakdown of the key aspects:

    Core Functionality

    • Course Catalog: The application allows users to browse courses, view course details, and enroll in courses.
    • User Authentication: Clerk is used for user authentication, offering features such as sign-in, sign-up, profile management, and user roles. User roles determine access to different parts of the application.
    • Course Creation: Teachers can create and edit courses, including course titles, descriptions, categories, and prices. Courses can be organized into sections and chapters, with video content for each chapter.
    • Billing: Stripe is used for handling payments and transactions.
    • Course Progress: The application tracks user progress through courses, including marking chapters and sections as complete.

    Key Features

    • User Roles: There are distinct roles for users and teachers, each with specific access and functionalities. Teachers can create and manage courses, while users can enroll and track their progress.
    • Responsive Design: The application is designed to be responsive, adapting to different screen sizes.
    • Scalability: The application is built with a focus on scalability, using a separate backend to avoid tight coupling.
    • Data Modeling: The application uses a NoSQL database, DynamoDB, due to the nature of the data and relationships. The data model includes courses, sections, chapters, user progress, and transactions.

    Technology Stack

    • Frontend:Next.js: The primary framework for building the user interface.
    • Redux Toolkit: Used for state management and API interactions.
    • Tailwind CSS and Shadcn: Used for styling and component library.
    • TypeScript: Used for type checking.
    • Framer Motion: Implements animations.
    • React Hook Form and Zod: Handles form management and validation.
    • Backend:Node.js and Express: Used to create the backend API.
    • Docker: Used to containerize the backend.
    • AWS Lambda: Hosts the backend using the Docker container.
    • API Gateway: Securely routes requests to Lambda functions.
    • DynamoDB: Serves as the NoSQL database.
    • S3: Handles the storage of video content.
    • CloudFront: A content delivery network (CDN) used to deliver videos with low latency.
    • Authentication:Clerk: A third-party service for user authentication.
    • Deployment:AWS: The application uses a serverless containerized architecture on AWS.
    • Vercel: Hosts the Next.js frontend.

    Development Highlights

    • Custom Base Query: The application uses a custom base query in Redux Toolkit Query to format API responses, handle data, and display toast notifications for successful mutations.
    • Form Management: Custom form fields are used for managing user settings, and react hook forms for form management and validation.
    • Backend Security: The backend API endpoints are secured using Clerk middleware, which requires authentication for certain routes.
    • Video Upload: Videos are uploaded to S3 using pre-signed URLs.
    • IM Roles: IM roles are created for Lambda to access AWS services such as DynamoDB, S3, and API Gateway.

    Additional Information

    • The application prioritizes backend and deployment skills alongside frontend development.
    • The choice of DynamoDB is due to the data structure, scalability, and performance requirements.
    • User progress is stored separately from course data to prevent overly large data objects and improve performance.

    In summary, this learning management system is a complex full-stack application with a variety of features, utilizing a modern tech stack and cloud infrastructure. It demonstrates a strong emphasis on scalability, customization, and user experience.

    Serverless Learning Management System on AWS

    The sources describe the deployment of a full-stack learning management application on AWS using a serverless, containerized architecture. The application leverages multiple AWS services to achieve scalability, performance, and cost-effectiveness. Here’s a detailed breakdown of the AWS deployment process:

    Core AWS Services

    • ECR (Elastic Container Registry): Docker images of the backend are stored in ECR.
    • Lambda: The backend is hosted using AWS Lambda, running the Docker image stored in ECR. Lambda is configured with a five-minute timeout and environment variables for production use.
    • API Gateway: Serves as a secure entry point for the application, routing requests to the Lambda function. It provides HTTPS endpoints without managing TLS certificates. A proxy resource is used in API Gateway to handle all requests, which are then routed to the Express server in the Lambda function.
    • DynamoDB: A NoSQL database used to store application data. The data model includes courses, sections, chapters, user progress, and transactions.
    • S3 (Simple Storage Service): Handles storage for video content.
    • CloudFront: A content delivery network (CDN) that delivers video content from S3 with low latency and high availability.

    Deployment Steps

    • Dockerization: The Node.js and Express backend is packaged into a Docker container. The Dockerfile includes instructions for building, installing dependencies, and setting up the production environment.
    • ECR Setup: A repository is created in ECR to store the Docker image. The Docker image is then pushed to the ECR repository using the AWS CLI.
    • Lambda Configuration: A Lambda function is created using the Docker image from ECR. The Lambda function is given an IAM role with the necessary permissions to access other AWS services.
    • IAM Roles: IAM (Identity and Access Management) roles are created to manage permissions for AWS services. The Lambda function is granted access to DynamoDB, S3, and API Gateway through a custom role. The IAM role includes a trust policy that allows both Lambda and API Gateway to assume the role.
    • API Gateway Setup: API Gateway is configured to route requests to the Lambda function. A proxy resource is used to forward all requests to the Lambda backend, allowing the Express server to handle routing.
    • S3 Configuration: S3 is set up with blocked public access, using a bucket policy to allow CloudFront read access. CORS (Cross-Origin Resource Sharing) settings are configured to allow different services to access S3.
    • CloudFront Configuration: CloudFront is set up to deliver video content from S3. It uses an origin access control setting, which requires a policy to be set on the S3 bucket. CloudFront is configured to redirect HTTP to HTTPS and allow various HTTP methods.
    • Environment Variables: Lambda environment variables are configured for production, including AWS region, S3 bucket name, CloudFront domain, Stripe keys, and Clerk keys.
    • Seeding the Database: A seed function is included in the Lambda code, triggered by an action parameter, allowing the database to be seeded directly from Lambda.

    Key Deployment Concepts

    • Serverless Architecture: The application uses serverless services like Lambda and DynamoDB, which reduces operational overhead and allows for automatic scaling.
    • Containerization: The backend is containerized using Docker, ensuring a consistent and portable environment for the application.
    • Pre-signed URLs: S3 pre-signed URLs are used to allow the client to upload videos directly to S3, bypassing the 10MB limit on API Gateway.
    • Cold Starts: Lambda functions may experience cold starts, where the first request after a period of inactivity can take longer to process.

    Additional Points

    • The deployment process prioritizes cost-effectiveness by utilizing free tier services on AWS, and budgets are created to monitor usage and prevent unexpected charges.
    • The application is deployed using a combination of the AWS Management Console, AWS CLI, and third-party services, like Vercel for the frontend.
    • The deployment emphasizes understanding the security and access requirements for each service, especially when dealing with data and video content.
    • The application’s architecture on AWS uses managed services to minimize the need for complex networking configurations.

    In summary, the application’s AWS deployment is a comprehensive process involving multiple services working together to create a scalable, secure, and performant learning management system. The deployment utilizes best practices for security, cost management, and efficiency, while leveraging serverless technology and containerization.

    Next.js Learning Management System Frontend

    The sources provide a detailed look at the Next.js frontend of a learning management application, highlighting its features, technologies, and development practices. Here’s a comprehensive overview:

    Core Functionality

    • User Interface: Next.js is the primary framework for building the application’s user interface. It handles routing, page rendering, and overall structure.
    • Dynamic Pages: Next.js is used to create dynamic pages for course listings, search, user profiles, and course editing.
    • Component-Based Architecture: The frontend uses a component-based architecture, making it easier to manage, reuse, and update the user interface.
    • Server-Side Rendering (SSR): Although the application uses client-side data fetching with Redux Toolkit Query, Next.js provides SSR capabilities, which can improve performance and SEO in some cases. This is a key feature of the framework.

    Key Technologies & Libraries

    • Redux Toolkit: Used for managing application state and handling API interactions. It includes features like Redux Toolkit Query for fetching data.
    • Tailwind CSS and Shadcn: Used for styling and UI components. Tailwind provides utility classes for styling, and Shadcn provides a library of pre-built, customizable components. The application uses a customized Tailwind configuration with its own color palette.
    • TypeScript: Used for static typing, making the code more robust and easier to maintain.
    • Framer Motion: Used for adding animations and transitions to the user interface.
    • React Hook Form and Zod: Used for handling form management and validation.
    • Clerk: Handles user authentication, including sign-in, sign-up, and user profile management. It integrates well with Next.js.
    • Stripe: Used for payment processing.

    Development Practices

    • Custom Hooks: The application uses custom React hooks to encapsulate and reuse logic, for example, useCarousel for image carousels and useCheckoutNavigation for managing navigation steps within the checkout flow.
    • Component Libraries: The use of Shadcn component library allows for consistent UI elements across the application, and components can be installed individually as needed.
    • Code Organization: The project is structured with clear separation of concerns, including components, utilities, styles, and state management. The src directory contains components, lib, state, types, and app directories. The app directory is for Next.js pages and routes.
    • Styling: The application emphasizes functionality and logic over extensive custom styling, using pre-defined Tailwind classes to quickly style components.
    • API Integration: Redux Toolkit Query is used to make API calls to the backend. The application uses a custom base query to handle responses and add authentication tokens to each request.
    • Environment Variables: Environment variables are used to manage configuration settings, API keys, and URLs.
    • Client-Side Data Fetching: The application fetches data on the client-side using Redux Toolkit Query. Although Next.js provides server-side rendering capabilities, this application primarily uses client-side data fetching.
    • State Management: Redux Toolkit is used for state management, providing a central store for application data.
    • Form Management: React Hook Form is used with Zod for form validation and management. The application also makes use of a custom form field for creating forms faster.

    Key Features in the Frontend

    • Landing Page: Includes a loading screen, animated elements, and a course search feature. It features a carousel of course images.
    • Search Page: Displays a list of available courses with filtering options, along with a detailed view of selected courses.
    • User Profile and Settings: Includes settings for notifications, email alerts, SMS alerts, and notification frequency, which are stored in Clerk’s user data.
    • Checkout Process: The checkout process is a multi-step wizard, including details, payment, and completion pages.
    • Course Editor: Provides a WYSIWYG editor for creating and modifying course content, structured into sections and chapters. It supports uploading video content.
    • Billing Page: Allows users to view their transaction history.
    • Navigation: The application has a navigation bar and a sidebar, which adapts to different screen sizes and contexts. The sidebar provides links to various parts of the application.
    • Loading Indicators: A shared loading component is used in various parts of the application.

    Additional Notes

    • The application uses a ‘non-dashboard layout’ for pages that don’t require user authentication and a ‘dashboard layout’ for pages that are behind the authentication wall.
    • The application emphasizes a balance between UI/UX and functionality, with styling applied efficiently using Tailwind CSS and pre-built components.

    In summary, the Next.js frontend of this learning management application is a well-structured and feature-rich component, utilizing a modern tech stack and best practices for frontend development. It’s built for scalability, maintainability, and a smooth user experience.

    Node.js Learning Management System Backend

    The sources describe the backend of a learning management application built with Node.js and the Express framework, emphasizing its scalability, customizability, and independence from the frontend. Here’s a detailed breakdown of the backend:

    Core Technologies & Architecture

    • Node.js and Express: The backend is built using Node.js as the runtime environment and Express as the web framework. This combination allows for handling server-side logic and routing API requests.
    • Separate Backend: The backend is designed to be a separate application, not part of the Next.js frontend. This separation allows the backend to scale independently and prevents tight coupling between the frontend and backend, which enhances maintainability.
    • Docker: The backend is containerized using Docker, ensuring a consistent and portable environment across different stages of development and deployment.
    • Serverless Architecture: The backend is designed to run in a serverless environment using AWS Lambda, allowing for automatic scaling and reduced operational overhead.

    Key Features and Functionality

    • API Endpoints: The backend provides a variety of API endpoints for managing courses, users, transactions, and video uploads.
    • Data Modeling: The backend uses a data modeling approach where the data is structured into courses, sections, chapters, comments, transactions, and user course progress.
    • Database Interaction: The backend uses DynamoDB as its NoSQL database for storing data. It’s chosen for its scalability and speed, as well as its low cost. The backend interacts with DynamoDB using the dynamus library which is similar to mongoose for MongoDB.
    • Authentication: The backend is integrated with Clerk for user authentication and authorization. Clerk is used to handle user sign-in, sign-up, and user roles.
    • File Uploads: The backend handles video uploads to S3 using pre-signed URLs for better scalability.
    • Payment Processing: The backend integrates with Stripe for payment processing and transaction management.
    • Middleware: The backend uses various middleware to add functionality like parsing request bodies, setting security headers, logging API calls, and managing CORS.
    • Route Management: Express Router is used to handle routes for different resources such as users, courses and transactions.
    • CORS: The backend is configured to handle cross origin requests with the CORS middleware so the frontend can communicate with the backend.
    • Environment Variables: The backend uses environment variables for configuration, like port numbers, database connection details, and authentication secrets.
    • Data Validation: The backend uses dynamus to validate data types, similar to mongoose.

    Backend Development Practices

    • Controllers: The backend uses controllers to manage the core logic, where each controller is focused on a specific resource like courses or user accounts.
    • Routes: Routes are organized to handle API endpoints for different resources.
    • Data Models: Data models are created to define the structure and validation of the data stored in DynamoDB. The data models are stored in a separate folder.
    • Middleware: Middleware functions are used to add extra functionality to the request handling, such as authentication, logging, and parsing.
    • Asynchronous Operations: Asynchronous operations are used for database interactions and other I/O bound operations.
    • Security: The backend uses helmet middleware for securing the application with proper HTTP headers and uses requireAuth middleware to protect API endpoints.
    • Error Handling: The backend uses try-catch blocks for error handling to send appropriate responses to the frontend.
    • Code Organization: The backend uses a structured folder approach to separate controllers, models, and routes.
    • Database Seeding: The backend has a seed script that inserts mock data into the DynamoDB database, which is useful for development.

    Key Components

    • Course Controller: Manages the API endpoints for courses, including listing, getting, creating, updating, and deleting courses.
    • User Clerk Controller: Manages the API endpoints for user settings, including updating user profile information in Clerk, using Clerk SDK.
    • Transaction Controller: Manages transactions for payment processing.
    • API Routes: The API endpoints are grouped into routes, making it easier to manage different resources.
    • Seed Script: Used for seeding the database with initial data.

    Deployment Preparation

    • Serverless HTTP: The backend is prepared for serverless deployment with serverless-http, which allows it to run as an AWS Lambda function.
    • Dockerization: The backend is packaged into a Docker image, which is stored in a container registry.
    • Lambda Handler: The application uses a custom handler that is compatible with AWS Lambda.
    • Environment Variables: Environment variables are set up in the Lambda environment for authentication and configuration.

    Important Points

    • The backend design emphasizes the importance of backend skills and knowledge for software engineers and discourages a sole focus on frontend development, emphasizing backend and DevOps skills as essential.
    • The backend is designed to be scalable and maintainable by separating concerns and using modern software engineering practices.
    • The backend utilizes a serverless, containerized architecture, taking advantage of AWS services to minimize infrastructure concerns and reduce operational overhead.
    • The backend is built to interact with a variety of services, including Clerk, Stripe, AWS Lambda, API Gateway, DynamoDB, and S3.

    In summary, the Node.js and Express backend of the learning management application is a robust and well-structured system that leverages modern software engineering practices and cloud-based services to provide a scalable, secure, and performant API for the frontend. It emphasizes customizability and the separation of backend logic from the frontend.

    Build a Nextjs Learning Management App | AWS, Docker, Lambda, Clerk, DynamoDB, ECR, S3, Shadcn, Node

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • Why Kindness Makes People Disrespect You Modern Stoicism: Stoic Secrets: Kindness, Boundaries, and Respect

    Why Kindness Makes People Disrespect You Modern Stoicism: Stoic Secrets: Kindness, Boundaries, and Respect

    The sources examine the potential downsides of unchecked kindness, highlighting how it can lead to disrespect, exploitation, and burnout. They discuss how an excess of kindness without proper boundaries or wisdom can invite others to take advantage and disregard personal priorities. Drawing upon Stoic philosophy, the sources encourage practicing self-respect, setting clear boundaries, and discerning who genuinely appreciates kindness from those who seek to exploit it. They advocate for emotional regulation, purposeful action, and distancing oneself from those who deplete energy. Ultimately, the sources emphasize that true kindness stems from a place of strength and inner balance, benefiting both the giver and receiver.

    The Stoic Path to Kind and Respected

    Study Guide Contents:

    I. Quiz: Knowledge Review (Short Answer)

    II. Essay Questions: Critical Thinking & Application

    III. Glossary: Key Terms and Definitions

    I. Quiz: Knowledge Review (Short Answer)

    Answer each question in 2-3 sentences based on the provided source material.

    1. Why does excessive kindness, when given without boundaries, sometimes lead to disrespect according to the source?
    2. How do people generally value things that are difficult to obtain versus those that are easily accessible?
    3. What is the relationship between strength and kindness, according to the source? Are they mutually exclusive?
    4. According to the source, what message are you sending when you consistently allow people to push your limits?
    5. How does unchecked kindness contribute to an imbalance in relationships, according to the source?
    6. What does it mean to “reward appreciation, not entitlement,” and why is this important?
    7. Why might people see someone who is excessively kind as emotionally dependent?
    8. Explain the stoic view on the relationship between kindness and approval, describing what motivates “true kindness”.
    9. Why is protecting your energy considered as important as protecting your time, according to the source?
    10. According to the source, how does walking away from toxic situations command respect?

    Quiz Answer Key:

    1. Excessive kindness, when given without boundaries, can lead to disrespect because people tend to devalue what is easily accessible and unearned. This can transform kindness from a virtue into an expectation, leading others to feel entitled and not appreciate or reciprocate.
    2. People tend to value what they have to earn and respect those whose kindness must be earned. Anything easily obtained is often overlooked, while that which requires effort is cherished.
    3. The source suggests that strength and kindness are not opposites but go hand in hand. True kindness is not about being a doormat, but about balancing giving with self-protection, and understanding that saying no when necessary is a sign of self-worth.
    4. When you consistently allow people to push your limits, you are teaching them how to treat you. If you don’t set limits, you are silently approving of mistreatment and indicating that you don’t value yourself enough to stand firm.
    5. Unchecked kindness creates an imbalance in relationships because one person is always giving while the other is taking, leading to dependency and entitlement rather than mutual respect. This occurs when generosity is excessive or poorly placed.
    6. Rewarding appreciation, not entitlement, means acknowledging and valuing gratitude while refusing to enable demanding or expectant behavior. This is important because it reinforces a mindset of respect and gratitude rather than one of obligation.
    7. People might see someone who is excessively kind as emotionally dependent because their kindness may stem from a fear of rejection or a need for approval, indicating that their self-worth depends on the approval of others.
    8. The stoic view suggests that true kindness comes from strength, not a need for approval. It is motivated by a genuine desire to do good because it aligns with one’s values, rather than a strategic attempt to gain favor or validation.
    9. Protecting your energy is as important as protecting your time because your energy is a limited resource that needs to be carefully managed. Giving it away too freely leaves little left for what truly matters and can lead to burnout and resentment.
    10. Walking away from toxic situations commands respect because it demonstrates an unwavering commitment to self-respect and sets a standard for how you expect to be treated. It shows that you value your well-being and will not tolerate mistreatment.

    II. Essay Questions: Critical Thinking & Application

    Choose one of the questions below and develop an essay response based on the ideas presented in the source material.

    1. Discuss the potential dangers of unlimited self-sacrifice and how modern stoicism offers a balanced approach to generosity and self-preservation. Provide real-world examples to support your arguments.
    2. Analyze the relationship between kindness, boundaries, and respect. How can one practice kindness without becoming a “doormat”? Explore the stoic principles that support this balance.
    3. Examine the concept of “emotional dependence” as it relates to acts of kindness. How can one ensure that their generosity stems from a place of inner strength rather than a need for approval?
    4. Explain the stoic perspective on the role of expectations in relationships. How can letting go of unrealistic expectations lead to more authentic and fulfilling connections?
    5. Discuss how setting and enforcing personal boundaries protects your time and energy and communicates your worth to others.

    III. Glossary: Key Terms and Definitions

    TermDefinitionStoicismAn ancient Greek philosophy emphasizing virtue, reason, and living in accordance with nature. Focuses on what can be controlled (inner thoughts and actions) vs. what cannot (external events).Modern StoicismContemporary application of stoic principles to everyday challenges, focusing on self-improvement, resilience, and living a meaningful life.KindnessThe quality of being friendly, generous, and considerate; showing concern and compassion for others.BoundariesPersonal limits that define what behaviors a person will accept from others. Essential for maintaining healthy relationships and protecting one’s well-being.RespectA feeling of deep admiration for someone or something elicited by their abilities, qualities, or achievements.Self-RespectHaving pride and confidence in oneself; valuing one’s own well-being and dignity.EntitlementThe belief that one is inherently deserving of privileges or special treatment.Emotional DependenceA state of relying excessively on others for emotional support, validation, or a sense of self-worth.Self-SacrificeGiving up one’s own needs or interests for the sake of others; can be positive when balanced, but detrimental when excessive.VirtueMoral excellence; behavior showing high moral standards. In Stoicism, primary virtues include wisdom, justice, courage, and temperance.DiscernmentThe ability to judge well; having keen insight and good judgment, especially regarding moral or ethical matters.Emotional DetachmentThe ability to separate one’s emotions from a situation, allowing for a more objective and rational response.

    Okay, here’s a briefing document summarizing the key themes and ideas from the provided source, with relevant quotes:

    Briefing Document: Navigating Kindness with Stoic Wisdom

    Main Theme: The sources explore the nuanced relationship between kindness and respect, arguing that unchecked kindness can lead to disrespect, exploitation, and personal burnout. It advocates for a balanced approach, integrating stoic principles of self-respect, boundary setting, and emotional awareness to ensure kindness remains a virtue rather than a liability.

    Key Ideas and Facts:

    • Kindness Without Boundaries Breeds Disrespect: The fundamental premise is that excessive, freely given kindness can be devalued. People tend to value what they have to earn. “People value what they have to earn. Kindness is often seen as a virtue, yet paradoxically in the modern world it can lead to disrespect when given too freely and without boundaries.” The more available and accommodating you are, the less others may appreciate your efforts.
    • The Paradox of Kindness: Kindness can paradoxically lead to disrespect in the modern world when given too freely and without boundaries. “This is one of the great paradoxes of human nature: people tend to devalue what is easily accessible.” When kindness becomes expected, it’s no longer seen as a gift.
    • Self-Respect is Paramount: The foundation for healthy kindness is self-respect. “Respect starts with self-respect. If you respect yourself enough to set limits, others will follow suit.” Stoicism emphasizes controlling what’s within your power, and that begins with valuing your own time and energy. Epic tetus asked, “How long will you wait before you demand the best for yourself?”
    • Saying “No” is Essential: The ability to say “no” is a critical tool for setting boundaries and protecting personal well-being. “Practice saying no. When you are always agreeable, people take you for granted, but when you establish clear limits…your kindness retains its value.” Saying no is not unkind; it’s a sign of self-worth. “A truly kind person is not someone who always says yes, but someone who knows how to balance giving with self- protection…”
    • People Test Limits: Human nature tends to test boundaries. If you consistently allow things to slide, you’re teaching people how to treat you. Epictus wisely said “you are not to blame for being uneducated, but you are to blame for refusing to learn and one of the most crucial lessons in life is this people will only respect the boundaries that you enforce. “
    • Imbalance in Relationships: Unchecked kindness creates an imbalance where one person carries the burden. “When you are always the one offering help, making sacrifices, or accommodating others, you unconsciously set a precedent…where you are expected to give and others feel entitled to receive.” This can lead to resentment and feeling unappreciated. Seneca reminds us that “he who gives when he is asked has waited too long”
    • Vulnerability to Manipulation: Excessive kindness can make you a target for manipulators who seek to exploit those who are easily swayed. “You might believe that being kind will earn you respect, but to the wrong people, it signals weakness.” True kindness, when paired with wisdom, is a strength. “Marcus Aurelius one of the greatest stoic philosophers wrote the best revenge is to be unlike him who performed the injury”
    • Emotional Dependence: Kindness stemming from emotional dependence (fear of rejection, need for approval) is a silent invitation for disrespect. “People instinctively admire those who are emotionally independent, those who do not seek validation through their acts of kindness but rather offer it from a place of inner abundance. ” If your kindness is a bargaining tool, it backfires.
    • Intentional vs. Automatic Kindness: Kindness must be intentional, not automatic or reactive. “Commanding respect while maintaining kindness is a delicate balance, but it is not about people-pleasing or seeking approval; it is about acting with intention.” Stoicism emphasizes deliberate action based on values, not fear.
    • Reward Appreciation, Not Entitlement: It’s crucial to reward those who appreciate your kindness, rather than those who feel entitled to it. “The happiness of your life depends upon the quality of your thoughts and this applies to how you allow others to treat you if you continue to give kindness to those who feel entitled to it you reinforce the wrong mindset.”
    • Respect Over Approval: It’s more important to be respected than liked. Kindness rooted in a need for approval can backfire. “When you live with Integrity when your kindness is rooted in genuine goodwill rather than a desperate need to be liked people notice they might not always agree with you but they will respect you and more importantly you will respect yourself. “
    • Protect Your Energy: Energy is a finite resource. “Protect your energy as fiercely as your time.” Don’t allow yourself to be an emotional dumping ground. Associate with those who uplift you. If you invest your energy in things that don’t serve you, you lose a piece of yourself. “Marcus Aurelius advised the tranquility that comes when you stop caring what they say or think or do, only what you do when you stop allowing outside distractions to consume your inner peace you gain power.”
    • Know When to Walk Away: Walking away from toxic dynamics demonstrates self-respect. “The more we value things outside our control the less control we have your time energy and peace of mind are among your most valuable assets and not everyone deserves access to them. ” Seneca stated “associate with people who are likely to improve you. “
    • Don’t Set Yourself On Fire To Warm Others We must remember not to set ourselves on fire to warm others. This stoic principle speaks to the importance of maintaining boundaries and not sacrificing our own well-being in the name of helping others
    • Balance Generosity With Self-Care: Stoicism encourages us to live in accordance with reason and virtue, which includes making thoughtful decisions rather than acting impulsively or out of an emotional desire to please others. There is a fine line between offering assistance and overextending ourselves to the point of exhaustion.

    Stoic Solutions:

    • Emotional Detachment: Practicing emotional detachment can help manage reactions to others’ actions. It’s about consciously choosing how to respond, not becoming numb.
    • Forgiveness: Letting go of past hurts is essential for emotional freedom. It doesn’t mean excusing actions, but rather freeing yourself from the emotional weight. “Marcus Aurelius said ‘the best revenge is to be unlike him who performed the injury.’”
    • Reciprocity has an Expiration Date: The true value of generosity lies not in what we receive but in what we offer to others
    • Discernment: This includes not only understanding our emotions but setting boundaries and protecting our energy

    Overall Message: True kindness isn’t about unlimited self-sacrifice; it’s about acting with virtue, wisdom, and self-respect. By integrating stoic principles, individuals can ensure their kindness is a source of strength, enriching their lives and the lives of others. It’s about living a life rooted in clarity, resilience, and balance.

    I hope this is helpful!

    FAQ: Kindness, Respect, and Stoicism

    Here are some frequently asked questions that best capture the main themes and ideas from the provided sources.

    1. Why does being too kind sometimes lead to disrespect from others?

    Kindness, when given without boundaries, is often devalued. People tend to value what they have to earn or work for. When kindness becomes a constant, easily accessible presence, it transforms from a virtue into an expectation. Others may feel entitled to your generosity, no longer seeing it as a gift to appreciate or reciprocate. This can lead them to take advantage of your kindness and disregard your needs.

    2. How does unchecked kindness make me appear weak?

    In society, strength is often associated with assertiveness and the ability to set clear boundaries. Unchecked kindness can be mistaken for weakness because you may always say yes, always yield, and never push back. While kindness is not inherently a flaw, it can lead to disrespect when not balanced with self-respect. People may overlook or take advantage of someone who is endlessly accommodating.

    3. Why do people test my limits when I am consistently kind?

    Human nature tends to test limits. If you consistently let things slide and don’t enforce boundaries, people will push to see how far they can go. It’s not always malicious, but a way of understanding what is acceptable. By setting clear expectations, you show that you value yourself and your boundaries, commanding respect.

    4. How does unlimited kindness create an imbalance in relationships?

    When you are always the one offering help, making sacrifices, or accommodating others, you unconsciously set a precedent where you are expected to give and others feel entitled to receive. This creates an imbalance where one person carries the burden of maintaining the relationship, leading to feelings of being drained, used, and unappreciated. It’s crucial to establish fairness and reciprocity in relationships to avoid this imbalance.

    5. How does being kind make me a target for manipulators?

    Manipulators seek out people who are easy to sway. Being kind can signal weakness to them, making you an easy target to exploit. They may see it as an open invitation to push boundaries, take without giving, and bend you to their will. Balancing kindness with wisdom is essential to avoid being taken advantage of.

    6. How can kindness be rooted in emotional dependence, and why does this lead to disrespect?

    When kindness stems from a place of emotional dependence, such as fear of rejection or a need for approval, it becomes a silent invitation for disrespect. People instinctively admire those who are emotionally independent. If your kindness is driven by the need for validation, it ceases to be an act of virtue and instead becomes a bargaining tool, signaling that your worth depends on their approval. People are wired to value what is scarce to admire what is self-sufficient

    7. What is the difference between true kindness and people-pleasing?

    True kindness stems from strength, not from a need for approval. People-pleasing is often driven by a desire to be liked, gain validation, or secure affection. It comes across has neediness rather than generosity. When kindness is transactional it can come across has a form of emotional bribery. True kindness is an act of virtue that comes from Inner Strength, not the fear of rejection. Being a good person, does not mean being a doormat.

    8. How can I maintain kindness while commanding respect, according to stoicism?

    To command respect without losing your kindness, you must practice kindness with wisdom and boundaries. Make your kindness intentional, say no without explaining yourself, reward appreciation, and protect your energy. Stoicism emphasizes finding a balance between generosity and self-preservation. Setting limits, giving intentionally, and ensuring your kindness is valued (not exploited) is very important. Remember respect starts with self-respect.

    The Pitfalls of Excessive Kindness

    When overused, kindness can lead to several negative outcomes, including disrespect from others, the appearance of weakness, and the creation of imbalanced relationships. Here’s a breakdown of how excessive kindness can be detrimental, according to the sources:

    • Disrespect Kindness, when given too freely, can be devalued. People tend to value what they have to earn, so if kindness is a constant, unearned presence, it becomes an expectation rather than a virtue. This can lead to others feeling entitled to one’s generosity, making them less appreciative and less likely to reciprocate.
    • Appearing weak Unchecked kindness can be mistaken for weakness because society often associates strength with assertiveness and the ability to set boundaries. People who always say yes and never push back may be overlooked or taken advantage of.
    • Testing limits Human nature tends to test limits, and if someone is consistently kind without boundaries, others may push to see how far they can go. This isn’t necessarily malicious but rather a way of understanding what is acceptable.
    • Imbalance in relationships Excessive kindness can create an imbalance where one person is always giving and the other is always receiving. This can lead to the giver feeling drained, used, and unappreciated. People may begin to see the giver’s generosity as an obligation.
    • Target for manipulators Overly kind people can become targets for manipulators, who seek out those who are easy to sway and take advantage of. To those with bad intentions, kindness can signal weakness and an open invitation to push boundaries.
    • Emotional dependence Kindness that stems from a place of emotional dependence, such as a fear of rejection or a need for approval, can invite disrespect. People instinctively admire those who are emotionally independent and offer kindness from a place of inner abundance.
    • Sacrificing self-respect: True kindness comes from strength, not a need for approval. When actions are motivated by a desire to be liked or to gain validation, they lose their authenticity, and people sense when kindness is transactional.
    • Ignoring priorities: Overdoing kindness makes you the go-to person for everyone, but you begin to notice the important things are slipping. True kindness doesn’t require you to abandon your personal goals, it comes from balance where you have taken care of your own needs first.
    • Attracting opportunists: Although admirable, excessive kindness attracts opportunists who see your generosity as an endless resource to exploit.
    • Habit Forming: You create a dangerous imbalance when you overextend kindness because it leads to stress and triggers harmful coping mechanisms.

    To avoid these pitfalls, the sources suggest practicing kindness with wisdom and setting boundaries. This involves making kindness intentional rather than automatic, saying no when necessary, and ensuring that your generosity is valued and reciprocated. The key is to balance generosity with self-respect, ensuring that your kindness is a conscious choice and not a self-imposed burden.

    The Art of Setting Healthy Boundaries

    Setting boundaries is essential for maintaining healthy relationships and protecting one’s well-being. The sources emphasize that boundaries are not about withholding kindness but about ensuring that kindness is meaningful and does not lead to disrespect, exploitation, or burnout.

    Here’s a breakdown of key aspects related to setting boundaries, based on the sources:

    • Purpose of Boundaries:
    • Protecting Self-Respect: Setting limits indicates self-respect, which encourages others to follow suit.
    • Preserving Value: Establishing boundaries ensures that kindness remains a conscious act of virtue rather than an unconscious obligation.
    • Preventing Exploitation: Boundaries prevent others from taking advantage of one’s generosity.
    • Maintaining Balance: Setting limits ensures a balance between generosity and self-preservation, preventing exhaustion and bitterness.
    • How to Set Boundaries:
    • Saying No: Practice saying no without over-explaining or feeling guilty. A firm, clear “no” is enough.
    • Being Intentional: Make kindness a conscious choice rather than an automatic reaction.
    • Defining Limits: Clearly communicate your limits to others, teaching them how to respect your time and energy.
    • Enforcing Boundaries: Consistently uphold your boundaries and take action when they are crossed.
    • Protecting Energy: Guard your emotional and mental energy by limiting exposure to negativity and setting boundaries with your emotions.
    • Walking Away: Be willing to distance yourself from toxic dynamics or relationships where respect is absent.
    • Benefits of Setting Boundaries:
    • Earning Respect: Setting clear expectations and refusing to be taken advantage of often leads to greater respect from others.
    • Healthier Relationships: Boundaries foster relationships built on mutual respect rather than silent sacrifice.
    • Preventing Burnout: Establishing limits prevents overextension and burnout, ensuring that kindness is sustainable.
    • Promoting Self-Worth: Setting boundaries demonstrates self-worth, which encourages others to value your time and energy.
    • Avoiding Manipulation: Clear boundaries discourage manipulators and those who seek to exploit kindness.
    • Fostering Independence: Boundaries prevent you from over-helping, which allows other to discover their own strength.
    • Qualities of Effective Boundaries:
    • Firmness: Boundaries should be firm and unwavering.
    • Fairness: Boundaries should be fair and not cross over into being cruel.
    • Generosity: Boundaries should leave space for generosity, but not enable the other person to diminish your worth.
    • Mindfulness: Boundaries should be applied mindfully, and not used to punish someone.
    • Challenges and Misconceptions:
    • Fear of Disappointing Others: Overcome the fear of disappointing others or being seen as unkind.
    • Guilt: Recognize that saying no is not selfish but an act of self-respect.
    • Societal Pressure: Resist societal pressure to be endlessly accommodating.
    • Stoic Principles:
    • Self-Control: Exercise self-control and emotional regulation when setting and maintaining boundaries.
    • Wisdom: Use wisdom to discern when to say yes and when to say no.
    • Justice: Act with justice, ensuring fairness both to yourself and to others.
    • Virtue: Align your actions with virtue, making kindness a deliberate choice rather than an obligation.

    In essence, setting boundaries is about creating a framework that allows kindness to thrive without undermining one’s well-being. By setting limits, individuals can ensure that their generosity is valued, reciprocated, and sustainable, leading to healthier and more respectful relationships.

    Modern Stoicism: A Guide to Resilience, Regulation, and Virtue

    Modern Stoicism emphasizes the practical application of ancient Stoic philosophy to contemporary life. It focuses on cultivating inner resilience, emotional regulation, and ethical behavior to navigate the complexities of the modern world. Modern Stoicism adapts the core tenets of Stoicism—virtue, reason, and living in accordance with nature—to address the challenges and opportunities of today’s society.

    Here’s a breakdown of key aspects of Modern Stoicism, according to the sources:

    • Core Principles:
    • Virtue as the Only Good: Modern Stoicism, like its ancient counterpart, emphasizes that virtue (wisdom, justice, courage, and temperance) is the sole good and the foundation for a fulfilling life.
    • Control and Acceptance: A central tenet is differentiating between what one can control (thoughts, actions, and responses) and what one cannot (external events, others’ opinions). Modern Stoicism encourages focusing efforts on what is within one’s power and accepting what is not.
    • Living in Accordance with Nature: This involves understanding the natural order of the world and living in harmony with it, embracing reason and virtue in daily life.
    • Mindfulness: Modern Stoicism emphasizes being present in the moment, rather than dwelling on the past or worrying about the future.
    • Practical Applications:
    • Emotional Regulation: Modern Stoicism provides tools for managing emotions, helping individuals respond to challenges with reason rather than impulse. This involves recognizing emotions, understanding their triggers, and choosing thoughtful responses.
    • Setting Boundaries: Modern Stoicism underscores the importance of setting boundaries to protect one’s well-being and prevent exploitation. This includes learning to say no, defining limits, and enforcing those limits consistently.
    • Goal Setting: Stoicism encourages setting clear goals aligned with one’s values to give life direction and purpose, acting as a compass.
    • Cultivating Self-Awareness: Modern Stoicism emphasizes the importance of self-reflection and self-compassion, building self-worth from within and not relying on external validation.
    • Practicing Empathy and Compassion: While setting boundaries is vital, Modern Stoicism also promotes empathy and compassion, understanding others’ struggles and responding with kindness while maintaining one’s own emotional health.
    • Detachment: A key teaching involves detaching from the need to control external factors, and learning to give without expectation.
    • Recognizing relationships: It is key to recognize which relationships are opportunistic and which will help you grow. It’s also important to preserve energy by focusing on relationships that uplift you.
    • Habit Forming: Stoicism consistently encourages us to avoid extremes by embracing balance in our actions and protects us from chaos.
    • Benefits of Modern Stoicism:
    • Increased Resilience: Modern Stoicism equips individuals with the tools to bounce back from setbacks and navigate challenges with greater emotional stability.
    • Improved Relationships: By setting healthy boundaries and practicing empathy, Modern Stoicism promotes more balanced and respectful relationships.
    • Enhanced Self-Worth: Cultivating self-awareness and self-compassion leads to a stronger sense of self-worth, reducing dependence on external validation.
    • Greater Emotional Regulation: Learning to manage emotions and respond with reason promotes inner peace and reduces unnecessary conflict.
    • Purposeful Living: Aligning actions with values and setting clear goals fosters a sense of purpose and fulfillment.
    • Finding Peace: By letting go of past hurts and practicing forgiveness, Modern Stoicism unlocks freedom and creates room for joy.

    In essence, Modern Stoicism is a practical philosophy for living a virtuous and fulfilling life in the modern world, providing tools and techniques for cultivating inner strength, managing emotions, and building meaningful relationships. By focusing on what is within one’s control and acting with reason and virtue, individuals can navigate the complexities of life with greater resilience and peace.

    Modern Stoicism: Emotional Well-being Through Self-Awareness and Regulation

    Drawing upon the sources and our conversation history, emotional well-being involves several interconnected elements that, when cultivated, contribute to a balanced and fulfilling life. Modern Stoicism provides a framework for understanding and enhancing emotional well-being by emphasizing self-awareness, emotional regulation, and ethical behavior.

    Key components of emotional well-being, according to the sources, include:

    • Self-Worth and Self-Love:Cultivating self-worth from within, rather than relying on external validation, is essential for setting boundaries and protecting emotional well-being.
    • Practicing self-compassion and treating oneself with kindness reinforces self-esteem and emotional resilience.
    • Recognizing one’s intrinsic value and worthiness of love and respect is vital for maintaining healthy boundaries and relationships.
    • Emotional Regulation:Managing emotions and responding with reason rather than impulse is a core aspect of Stoicism.
    • Practicing emotional detachment involves understanding emotions without allowing them to dictate behavior, which helps in navigating challenging situations.
    • Developing the ability to pause and reflect before reacting to emotional triggers enables thoughtful responses aligned with one’s values.
    • Setting Boundaries:Establishing clear and healthy boundaries is crucial for protecting emotional energy and preventing exploitation.
    • Setting limits and saying “no” when necessary are acts of self-respect that ensure kindness comes from a place of strength rather than obligation.
    • Clearly communicating boundaries helps others respect one’s time, energy, and values.
    • Practicing Empathy and Compassion:Understanding and sharing the feelings of others allows for thoughtful responses rather than impulsive reactions.
    • Approaching difficult situations with kindness and understanding, while maintaining boundaries, fosters healing and balanced relationships.
    • Recognizing that others’ actions often stem from their own struggles promotes empathy and prevents resentment.
    • Letting Go of Past Hurts:Forgiveness is essential for freeing oneself from emotional burdens and releasing negative emotions.
    • Releasing emotional attachments to past events allows for a focus on personal healing and growth, enabling a more peaceful present.
    • Choosing peace over bitterness and focusing on personal growth helps in moving forward from past wrongs.
    • Living with Intention and Purpose:Setting clear goals aligned with one’s values provides direction and helps focus on what truly matters.
    • Aligning actions with values ensures that time and energy are directed toward pursuits that enrich personal growth and contribute to a sense of fulfillment.
    • Living in accordance with virtue and acting with reason fosters a sense of purpose and balance in life.
    • Managing External Influences:Distancing oneself from energy drainers and negative influences helps safeguard emotional and mental health.
    • Focusing on what is within one’s control and accepting what is not promotes inner peace and reduces unnecessary stress.
    • Surrounding oneself with supportive individuals fosters emotional resilience and personal growth.
    • Mindfulness and Self-Reflection:Being present in the moment, rather than dwelling on the past or worrying about the future, is essential for emotional regulation.
    • Regular self-reflection and self-assessment, including journaling and meditation, promote emotional awareness and help manage emotional overwhelm.

    These elements of emotional well-being are interconnected and mutually reinforcing. By cultivating self-awareness, practicing emotional regulation, setting healthy boundaries, and aligning actions with values, individuals can enhance their emotional resilience, build stronger relationships, and lead more fulfilling lives. Modern Stoicism provides practical tools and techniques for integrating these principles into daily life, enabling individuals to navigate challenges with greater clarity, purpose, and inner peace.

    The Art of Earning Respect: Kindness and Boundaries

    Drawing from the provided source, earned respect is achieved through a combination of kindness, wisdom, self-respect, and the establishment of clear boundaries. It is a reciprocal recognition of worth, not an entitlement or automatic response to generosity.

    Key aspects of respect earned, according to the sources:

    • Balance Between Kindness and Self-Respect:
    • Kindness, when given without boundaries, can lead to disrespect because people tend to devalue what is easily accessible.
    • Respect is commanded by acting in ways that show self-worth, not by simply giving oneself away.
    • Balancing generosity with self-preservation is crucial for earning genuine respect.
    • Setting and Enforcing Boundaries:
    • People respect the boundaries that are enforced.
    • Setting clear expectations and refusing to be taken advantage of often leads to greater respect.
    • Firmness and compassion are allies in earning respect; kindness should be strong, not weak.
    • Saying no is essential; those who know when to say no command true respect.
    • Intentional Kindness:
    • Kindness must be intentional, not automatic.
    • Acting with intention transforms kindness from appeasement to an expression of values.
    • Respect comes from being authentic, not just agreeable.
    • Kindness should be a conscious choice, not an unconscious habit.
    • Self-Control and Emotional Independence:
    • People instinctively admire those who are emotionally independent and do not seek validation through their acts of kindness.
    • True tranquility comes from mastering desires and detaching self-worth from others’ opinions.
    • A strong person offers kindness freely but does not beg for it in return.
    • Rewarding Appreciation, Not Entitlement:
    • Rewarding appreciation reinforces the right mindset and teaches people that kindness is a gift, not a debt.
    • Withdrawing kindness from those who demand it is necessary; self-respect is non-negotiable.
    • Avoiding Self-Sacrifice:
    • Generosity should not extend to the point of self-sacrifice or exhaustion.
    • True generosity involves offering help in a way that maintains dignity and well-being.
    • Kindness should never mean self-sacrifice at the expense of well-being.
    • Protecting Your Energy:
    • Protecting energy is as crucial as protecting time; respect is about how much of oneself is given, and to whom.
    • Being selective about where to invest energy and setting emotional boundaries are essential.
    • Knowing When to Walk Away:
    • Walking away from situations that undermine dignity demonstrates a commitment to self-respect and earns the respect of others.
    • It’s important to carefully discern where efforts are invested; kindness should not come at the cost of self-worth.

    In essence, earned respect is about creating a balance where kindness is a choice made from a position of strength and self-awareness, not a freely given resource that others can exploit. By setting boundaries, acting with intention, and valuing oneself, it’s possible to foster relationships built on mutual respect and appreciation.

    Why Kindness Makes People Disrespect You | Modern Stoicism

    The Original Text

    why kindness makes people disrespect you modern stoicism have you ever felt like the more kindness you show the less people respect you you offer a helping hand yet they start expecting it you go out of your way to be considerate yet you’re overlooked you try to be a good person yet somehow you become an easy target someone people take advantage of and here’s the real danger if you don’t recognize what’s happening you’ll keep wondering why people dismiss your needs walk over your boundaries and never truly appreciate you but don’t worry by the end of this video you’ll understand why kindness when used without wisdom can lead to disrespect and how to shift your approach to gain respect without losing losing your compassion because the problem isn’t kindness itself it’s how and when you apply it number one people value what they have to earn kindness is often seen as a virtue yet paradoxically in the modern world it can lead to disrespect when given too freely and without boundaries this is one of the great paradoxes of human nature people tend to devalue what is easily accessible the moment kindness becomes a constant unearned presence it transforms from a virtue into an expectation when others feel entitled to your generosity they no longer see it as a gift but as a given something they need not appreciate or reciprocate this is why modern stoicism teaches us the importance of self-respect and measured generosity Marcus Aurelius once wrote wa no more time arguing about what a good man should be be one but being a good person does not mean being a doormat if you are always available always saying yes and never establishing limits people will not admire your kindness they will assume it is simply who you are something they can take without consequence just as we value what we work hard for we also respect those whose kindness must be earned when you are too freely giving you teach others to expect rather than appreciate this is a hard truth that many people learn too late in life anything easily obtained is often overlooked while that which requires effort is cherished consider the example of luxury goods why do people covet designer Brands over cheap Alternatives it is not just about quality it is about scarcity and effort people respect what is rare what is different difficult to attain the same applies to Human Relationships if you are endlessly accommodating always bending over backward for others they may begin to see you as replaceable this is why setting boundaries is not about withholding kindness it is about ensuring that your kindness is Meaningful in letters from A stoic senica reminds us you act like Mortals in all that you fear and like Immortals in all that you desire if we desire respect we must act in ways that command it not simply give ourselves away expecting it in return the key is to make your kindness a conscious Choice rather than an unconscious habit when you say yes too often out of fear of disappointing others you become a tool rather than a person useful but not respected in Modern Life this lesson is especially relevant in a world driven by social media validation where people are pressured to be endlessly available many have lost the ability to say no the result burnout resentment and ironically a lack of true respect from those they strive to please the truth is when you set boundaries you teach others that your time and energy are valuable you show them that your kindness is not free flowing but intentional this is a core principle of stoic Secret control what is within your power and let go of what is not respect starts with self-respect if you respect yourself enough to set limits others will follow suit epic tetus taught how long will you wait before you demand the best for yourself this is a question worth reflecting on are you allowing yourself to be drained by the expectations of others or are you ensuring that your kindness remains a conscious Act of virtue rather than an unconscious obligation the practical application of this wisdom is simple yet powerful practice saying no when you are always agreeable people take you for granted but when you establish clear limits when you give selectively and intentionally your kindness retains its value instead of always being available be present on your own terms let people understand that your time and generosity are gifts not rights this will not make you less kind it will make your kindness more respected modern stoicism emphasizes the idea that true strength is found in balance between generosity and self-preservation between compassion and wisdom those who fail to find this balance often end up exhausted disrespected and bitter the world world does not reward unlimited self-sacrifice it rewards those who understand the value of their own worth number two unchecked kindness can make you seem weak unchecked kindness can often be mistaken for weakness not because kindness itself is a flaw but because the world respects those who balance compassion with self-respect in society we often see strength associated with assertiveness and the ability to set clear boundaries those who can confidently say no when necessary are viewed as people with strong principles while those who always say yes always yield and never push back can easily be overlooked or even taken advantage of stoicism teaches us that emotional control is a virtue but that does not mean we should be passive or allow others to walk all over us this does not mean being cold or unfeeling but rather understanding that true kindness cannot come at the cost of your own dignity real kindness isn’t just about how much you give it’s about knowing when to give and when to stand your ground think about the story of Daniel a man known for always helping others he never said no never stood up for himself and always put the needs of others before his own at first people admired his generosity but over time what happened his kindness was no longer seen as a virtue it became an expectation people stopped asking if he had the time or energy to help they simply assumed he would and the moment Daniel tried to say no people were upset they weren’t grateful for all he had done in the past instead they felt entitled to his help he hadn’t changed but the way people treated him had because he never established boundaries in the first place his kindness was real but Without Limits it lost its value now ask yourself how many times have you felt like your kindness was taken for granted how often have you agreed to something just to avoid disappointing others have you ever felt drained because you constantly put others before yourself this isn’t about becoming selfish or cruel it’s about realizing that kindness does not mean being a doormat for kindness to have meaning it must be given with intention and wisdom strength and kindness are not opposites they go handin hand if you don’t respect yourself don’t expect others to respect you a truly kind person is not someone who always says yes but someone who knows how to balance giving with self- protection someone who understands that saying no when necess necessary is not unkind it’s a sign of self-worth and that is the kind of person who earns true respect the lesson here is simple don’t let your kindness become a burden being kind does not mean letting others take advantage of you it means fostering relationships built on mutual respect if you want your kindness to be valued start by valuing yourself number three people test how far they can push you kindness is a virtue but when it is given without boundaries it can invite disrespect why because human nature tends to test limits if you consistently let things slide if you allow a friend to always be late without consequence if you accept extra work from a coworker without pushing back or if you tolerate a partner neglecting your needs what message are you really sending whether you realize it or not you’re teaching people how to treat you epicus wisely said you are not to blame for being uneducated but you are to blame for refusing to learn and one of the most crucial lessons in life is this people will only respect the boundaries that you enforce stoicism teaches us that while kindness is admirable it must be coupled with self-respect if not it becomes a silent signal that you don’t value yourself enough to stand firm have you ever noticed how those who set clear expectations who know their worth and refuse to be taken advantage of are often the most respected Marcus aelius one of the greatest stoic leaders understood this well he said the soul becomes dyed with the color of its thoughts if you constantly think that kindness means being endlessly accommodating your soul your character and your self-worth will reflect that but true stoic wisdom tells us that virtue is about balance be kind but never at the cost of your dignity imagine a river strong flowing and full of life it nurtures everything around it but it also carves Stone shapes Landscapes and determines its own path kindness should be like that generous but firm if people sense that you lack the strength to say no they will push to see how far they can go this isn’t because they’re necessarily malicious it’s simply how people operate even children test their parents patience to understand what is acceptable so why would adults be any different a stoic doesn’t resent this reality they accept it and act accordingly senica once said he who does does not prevent a crime when he can encourages it if you don’t set limits you are silently approving of mistreatment this doesn’t mean you should become harsh or unkind stoic lessons emphasize that self-control wisdom and Justice must work together be kind yes but let that kindness be strong not weak a person who truly embodies stoicism understands that firmness and compassion are not opposite they are allies so ask yourself are you being kind because it aligns with your values or because you fear confrontation are you letting others dictate your worth by how much you’re willing to endure the answer to these questions determines whether your kindness is a strength or a weakness kindness should never mean self-sacrifice at the expense of your well-being the stoics knew that a life lived with virtue requires wisdom knowing when to say yes and more importantly when to say no so the next time someone pushes your limits remember your response teaches them exactly how far they can go what lesson are you giving them if you’ve watched up to this point you’re already on the path to understanding the hidden dynamics of kindness and respect in today’s world comment below with stoic strength to affirm your commitment to master ing modern stoicism but don’t stop here there’s still valuable Insight ahead that can change the way you navigate respect boundaries and personal power stay until the end to uncover how true kindness Guided by wisdom earns genuine respect number four it creates an imbalance in relationships kindness when given without boundaries often creates an imbalance in relationships that many fail to recognize until they feel drained used or unappreciated modern stoicism teaches us the importance of equilibrium in human interactions giving without expectation but also ensuring we are not taken for granted senica once wrote he who gives when he is asked has waited too long this reminds us that generosity when excessive or poorly placed can foster dependency and entitlement rather than mutual respect when you are always the one offering help making sacrifices or accommodating others you unconsciously set a precedent one where you are expected to give and others feel entitled to receive the more you extend kindness Without Limits the less people value it and soon they no longer see it as generosity but as an obligation you owe them this leads to an unspoken Dynamic where one person carries the burden of maintaining the relationship while the other simply takes without feeling the need to reciprocate in the context of Modern Life we often see this imbalance in friendships workplaces and even within families the employee who always says yes to extra work without question soon becomes the one everyone relies on yet receives the least appreciation the friend who always listens and gives emotional support but never shares their own struggles becomes the emotional crutch for others yet is left alone in their own moments of need the partner who continuously compromises to keep the peace eventually realizes that their needs are ignored because they have never been firm about them this isn’t to say kindness is a weakness far from it the stoic secrets to maintaining respect lie in practicing kindness with wisdom Marcus Aurelius reminds us be tolerant with others and strict with yourself this means offering kindness but also setting boundaries that prevent you from being diminished by your own good nature if you give without discernment you risk turning your virtue into a vice where kindness is no longer an act of strength but a self-imposed burden a well-balanced relationship is built on mutual respect not silent sacrifice the greatest respect you can command from others is by demonstrating self-respect first people unconsciously mirror the way you treat yourself if you place no value on your time your energy and your efforts neither will they if you constantly say yes to every demand people will assume you have nothing better to do and your kindness will not only be undervalued but eventually ignored this means Having the courage to disappoint others sometimes to say no when necessary and to stand firm in your decisions this doesn’t mean becoming cold or indifferent but rather understanding that respect is built not on endless giving but on Mutual recognition of worth look at those who command true respect in life they are not the ones who say yes to everything but those who know when to say no they give where it matters but they also hold their ground when necessary modern stoicism reminds us that virtue is about balance if you lean too far into self-sacrifice you lose your own stability if you lean too far into selfishness you lose connection with others the key is to be kind but not to the extent that it breeds entitlement in others and exhaustion in yourself true generosity is not about giving endlessly but about giving wisely only to those who appreciate it and only when it does not come at the cost of your own dignity in relationships fairness must exist if your kindness is not reciprocated it is not kindness it is self- neglect so how do you correct this imbalance by first acknowledging your own worth by recognizing that your time and energy are not infinite resources to be drained by those who only take by understanding that true kindness does not mean always saying yes but knowing when to say no by reminding yourself that being a good person does not mean being a doormat and part of being a good person is ensuring that your kindness is respected not exploited in a world that often mistakes kindness for weakness be both firm and fair generous yet Discerning kindness should never be a burden but a gift one that when given wisely Fosters respect rather than diminishing it number five it makes you a target for manipulators kindness is a virtue but in a world where not everyone acts with good intentions it can also make you a target for manip ulators those who seek control whether it’s a toxic boss a selfish friend or a manipulative partner are always on the lookout for people who are easy to sway and who better to exploit than someone who always says yes always puts others first and never questions when their generosity is being taken advantage of you might believe that being kind will earn you respect but to the wrong people it signals weakness they see it as an open invitation to push boundaries to take without giving and to bend you to their will but here’s the truth kindness when paired with wisdom is not weakness it’s strength the stoics understood this well Marcus Aurelius one of the greatest stoic philosophers wrote the best revenge is to be unlike him who performed the injury this means you don’t have to become cold or cruel in response to manipulation but you do have to be Discerning being kind does not mean being naive and it certainly does not mean allowing others to take advantage of you consider the story of Jake a talented designer who always went out of his way to help his co-workers he would cover for them when they miss deadlines fix their mistakes and even stay late to ensure projects were completed on time at first he thought his kindness was appreciated until he realized his workload was twice that of anyone else’s and his so-called friends were dumping their responsibilities on him while taking credit for his efforts one day his boss asked him to stay late yet again to finish someone else’s work without so much as a thank you that was when it hit him his kindness wasn’t being respected it was being exploited Jake decided to set back boundaries he stopped saying yes to every request prioritized his own work and made sure his contributions were recognized some people resented this change but the ones who truly valued him adjusted he didn’t stop being kind but he stopped being an easy target so ask yourself are you being kind or are you being taken advantage of do the people in your life appreciate your kindness or do they simply expect it the stoics teach us to be mindful of who we allow into our Inner Circle and to recognize when kindness is being mistaken for weakness epicus reminds us the key is to keep company only with people who uplift you whose presence calls forth your best true kindness isn’t about pleasing everyone it’s about acting with Integrity wisdom and self-respect when you learn to balance kindness with strength you you command respect instead of inviting manipulation the lesson here is clear give kindness freely but not blindly because the moment you allow yourself to be used your kindness is no longer kindness It’s self-sacrifice at your own expense number six people see you as emotionally dependent kindness when rooted in strength is a powerful virtue but when it stems from a place of emotional dependence it can become a silent invitation for disrespect people instinctively admire those who are emotionally independent those who do not seek validation through their acts of kindness but rather offer it from a place of inner abundance if your kindness is driven by the fear of rejection or the need for approval it ceases to be an act of virtue and instead becomes a bargaining tool one that often backfires stoicism teaches us that true Tranquility comes from within from mastering our desires and detaching our selfworth from the fleeting opinions of others as Marcus Aurelius said you have power over your mind not outside events realize this and you will find strength a person who is kind because they choose to be because it aligns with their values not because they crave appreciation is naturally respected but when kindness is merely a mask for insecurity people sense it they may not always articulate it but they will feel it and in time their respect for you will diminish consider a man who tolerates blatant disrespect from a woman just to keep her in his life to an outsider it may seem like patience or devotion but in reality it signals weakness a person who does not set boundaries who allows mistreatment out of fear of loss is not truly kind they are emotionally dependent and dependence especially in relationships is rarely admired a strong person offers kindness freely but does not beg for it in return they do not tolerate abuse under the illusion of loyalty epic tetus reminds us if you want to improve be content to be thought foolish and stupid in other words prioritizing virtue over popularity requires the courage to be misunderstood to stand firm in your principles even when others do not immediately see their value why is it that people respect those who are willing to walk away but take advantage of those who cling too tightly the answer lies in human nature we are wired to Value what is scarce to admire what is self-sufficient when you are excessively kind in hopes of being liked you unwittingly communicate that your worth depends on the approval of others and the moment people sense that you need them more than they need you the power Dynamic shifts you become easy to take for granted this is why stoic lessons emphasize self-sufficiency the ability to be content with oneself regardless of external circumstances if your kindness is genuine it will not waver in the face of indifference if it is strategic it will eventually betray you think about it when was the last time you truly respected someone who lacked self-respect when you meet someone who stands firm in their values who does not compromise themselves for the sake of acceptance do you not instinctively admire them contrast that with someone who constantly seeks to please who bends over backward to accom odate everyone even at the cost of their dignity over time their efforts become predictable their presence easy to overlook this is not because kindness itself is weakness but because misplaced kindness kindness rooted in fear rather than principle is as senica wisely observed he who is brave is free the courage to assert yourself to establish boundaries to remain kind yet not sub subservient that is true Freedom so ask yourself is your kindness a choice or is it a strategy are you kind because it aligns with your character or because you hope to be liked in return if your answer leans toward the latter you must reassess your approach kindness should be an extension of strength not a symptom of emotional dependence true stoicism teaches us to act in accordance with virtue to do what is right without being attached to how others perceive us if people respect you for your kindness let it be because they recognize it as a reflection of your inner stability not because they see an opportunity to exploit it in the end the only approval that truly matters is the one you give yourself do you think kindness without self-respect leads to being taken for granted many mistake people pleasing for genuine kindness but true virtue comes from Inner Strength not the fear of rejection share your thoughts below kindness without self-respect invites disrespect number seven true kindness comes from strength not approval true kindness stems from strength not from a need for approval when your actions are motivated by a desire to be liked to gain validation or to secure affection they lose their authenticity people can sense when kindness is transactional when it’s a silent plea for acceptance rather than a genuine expression of Good Will the stoics teach us that our worth is not dictated by how others perceive us but by the virtues we embody when you give excessively gifts time attention without it being reciprocated and especially if your intent is to win favor it can come across has neediness rather than generosity and neediness repels imagine a man who constantly showers a woman with compliments expensive gifts and undivided attention not because he genuinely wants to give but because he hopes she will like him more he believes that by overwhelming her with kindness she will feel compelled to reciprocate but instead of admiration she may feel uncomfortable even pressured because the generosity is laced with expectation it’s not truly about her it’s about his need for validation this Dynamic plays out in friendships workplaces and even within families when someone senses that your kindness is a form of emotional bribery respect is lost think about it who do you admire more the person who gives freely because it is simply in their nature or the one who gives with the the silent hope of something in return people are drawn to those who are self-sufficient who give without attachment who are content with or without external validation the moment you make your selfworth dependent on how others receive your kindness you become vulnerable to manipulation and disappointment instead embrace the stoic principle of acting according to Virtue not reaction if you are kind be kind mind because it aligns with your values not because you need something in return the strongest relationships romantic or otherwise are built on mutual respect not desperation consider the story of Daniel a man who always put others first not because he was selfless but because he feared rejection he would go out of his way to please to avoid conflict to be liked by everyone yet despite his constant efforts people took him for granted they knew he wouldn’t say no that he was always available always seeking their approval over time he grew resentful feeling used and unappreciated but the truth was he had set the terms of those relationships by teaching others that his kindness came with an unspoken contract if I do this for you will you like me it wasn’t until he learned to give with without attachment to be kind without expectation that he found real peace some relationships faded but the ones that remained were genuine so ask yourself is your kindness an extension of your character or is it a strategy are you giving from a place of abundance or are you hoping to receive something in return true strength is found in self-sufficiency in knowing that your worth is not measured by how others respond to you when you stop seeking validation you become the kind of person who naturally commands respect and respect unlike approval is never begged for it is earned kindness is a virtue but when applied without wisdom it can become a liability the harsh truth is that people often take for granted what is freely given and unchecked generosity can lead to an imbalance in relationship exploitation and ultimately a loss of respect this is not because kindness itself is flawed but because human nature tends to test limits the stoics understood that true kindness must be paired with self-respect Marcus aelius senica and epicus all taught that a life of virtue requires balance between generosity and self-preservation between compassion and firmness to be truly kind you must also be Discerning you must recognize when your kindness is being valued and when it is being exploited and above all you must never let kindness come at the cost of your own dignity so where do we go from here how do we ensure that our kindness is respected rather than mistaken for weakness this is where Modern stoicism provides us with a practice iCal path forward in the next section we’ll explore how to command respect without losing your kindness because being kind does not mean being passive it does not mean saying yes to everything and it certainly does not mean allowing others to take advantage of you how to command respect without losing your kindness many believe that being kind means always saying yes of avoiding conflict and putting others first but as we’ve seen unchecked kindness can lead to disrespect and burnout so does this mean you should stop being kind not at all instead you must practice kindness with wisdom and boundaries stoicism teaches that true kindness isn’t about pleasing everyone it’s about acting with purpose Marcus Aurelius LED with virtue but never at the EXP expense of self-respect to command respect you must set limits give intentionally and ensure your kindness is valued not exploited in this section we’ll explore how to balance kindness with strength ensuring that your generosity earns respect rather than invites entitlement let’s begin number one kindness must be intentional not automatic commanding respect while maintaining kindness is a delicate balance but it is not about people pleasing or seeking approval it is about acting with intention Marcus Aurelius one of History’s Greatest stoic philosophers was known for his generosity and fairness but he never allowed himself to be controlled by the expectations of others his kindness was a choice not an obligation this is a crucial distinction in in modern stoicism to be truly kind one must be deliberate rather than reactive too often people mistake kindness for weakness thinking that saying yes to every request earns them admiration in reality respect is built on boundaries not blind compliance before extending your help or agreeing to something pause and ask yourself am I doing this because I genuinely want to or am I acting out of of fear of disapproval senica once said if you wish to be loved love but this love must be given freely not extracted through guilt or pressure when you make kindness intentional it transforms from an act of appeasement into an expression of your values this is a stoic secret true kindness does not seek validation it stems from inner strength in today’s world where social obligations workplace expectations and personal relationships often blur the lines between generosity and self-sacrifice it is vital to recognize that saying no does not make you unkind it makes you Discerning consider the difference between a leader who helps because they fear conflict versus one who helps because they see value in doing so the latter commands respect because their kindness is grounded in principle not in security people sense when kindness is genuine and when it is laced with silent resentment if you are constantly overextending yourself to avoid disappointing others you are not being kind you are being controlled the modern stoic understands that respect is earned by standing firm in their choices not by bending to every demand this does not mean turning cold or indifferent the key is to be as generous with your kindness as you are with your discipline epic tetus reminds us no man is free who is not master of himself if you allow external pressure to dictate your generosity you are no longer in command of your own will instead practice mindful kindness give when it aligns with your principles not when it is expected of you in the workplace for instance a boss who is always accommodating out of fear of being disliked will soon be taken for granted however a leader who helps when it makes sense while setting firm expectations earns both respect and appreciation in personal relationships the same rule applies consider a friend who always says yes to Favors even at their own expense over time their kindness loses its value because it is given without discernment but a friend who helps thoughtfully who knows when to give and when to say no is respected because their kindness holds weight this is why intentional kindness is so powerful it is rare it is valuable and it is given with meaning as the stoics teach respect comes not from being agreeable but from being authentic the modern world often pressures us to be endlessly accommodating mistaking self-sacrifice for virtue but self-sacrifice without purpose leads to resentment not respect true kindness as understood in modern stoicism is neither weak nor passive it is strong deliberate and aligned with your values to command respect without losing your kindness start by making each Act of generosity a conscious decision rather than an automatic reaction train yourself to pause before saying yes ensuring that your kindness is an expression of your strength not a response to fear as you practice this you will notice something remarkable people will respect you more not less they will see that your kindness is not a tool for approval but a reflection of your inner power this is the secret of those who live by stoic wisdom they do not seek to please yet they are deeply respected they do not Chase validation yet they are valued and they do not give out of fear but out of choice number two say no without explaining yourself respect and kindness are not opposites in fact the most respected people often possess both in Perfect Balance but one of the quickest ways to lose respect is to stretch yourself too thin to always be available always saying yes until your time energy and even selfworth become diluted senica said he who is everywhere is nowhere if you try to please everyone you’ll end up pleasing no one not even yourself the ability to say no without justifying without overe explaining without feeling guilty is one of the greatest strengths you can develop it’s a quiet assertion of self-respect and the world responds to it in kind think think about a time when someone asked you for a favor you didn’t really want to do maybe it was staying late at work when you had already sacrificed enough or a friend expecting you to drop everything to help when you were struggling with your own responsibilities you wanted to say no but you hesitated maybe you offered an excuse or softened your refusal with too much explanation but why why do we feel the need to justify protecting our own time and energy often it’s because we fear disappointing others or being seen as unkind but here’s the truth when you respect your own limits others do too if you constantly say yes to everything people will assume your time is free your boundaries are flexible and your needs come second that’s not kindness that’s self- neglect consider the story of James a hardworking designer who always said yes his colleagues knew they could count on him to pick up extra work his friends knew he’d always be there and his family knew he’d never say no even if it meant sacrificing sleep and personal time at first he felt good about being the Dependable one but over time resentment built up he felt exhausted used and strangely invisible the respect he thought he was earning by being agreeable wasn’t real it was conditional based on his willingness to be endlessly available one day when his boss asked him to take on yet another lastminute project James did something different he simply said I can’t do that no excuse no elaborate reason just a firm clear statement the room was silent for a moment then his boss nodded and moved on James realized in that moment that he had been giving away his power all along the fear of saying no had been far worse than the reality of it when you start saying no with confidence you may notice a shift in how people treat you some will push back especially if they’ve benefited from your constant compliance but others will respect you more recognizing that you are someone who values yourself and the most surprising thing the world doesn’t end when you say no your true friends the people who genuinely respect you won’t leave because you set a boundary they’ll stay and they’ll probably admire you even more for it ask yourself this what would change in your life if you stopped overexplained your refusals how much energy would you reclaim if you reserved your time for what truly matters learning to say no isn’t about being harsh it’s about being clear a simple I can’t or that doesn’t work for me is enough you don’t owe anyone an elaborate justification for prioritizing your well-being true kindness isn’t about sacrificing yourself it’s about offering your best self to the world and you can only do that when you protect your energy so the next time you feel pressured to explain your no pause let it stand on its own respect yourself first and others will follow number three reward appreciation not entitlement respect is not about being feared or blindly obeyed it’s about being valued and one of the strongest ways to ensure you are respected without losing your kindness is by rewarding appreciation not entitlement imagine this you offer someone your time your help your patience and they genuinely appreciate it they recognize your effort they thank you and they show gratitude in return you feel motivated to continue giving to continue being there because you know your kindness is respected but now imagine another scenario someone doesn’t acknowledge your efforts instead they expect them they assume you will always be there always saying yes always offering your kindness without question the moment someone demands your kindness rather than appreciates it they reveal their entitlement and this is where you must draw the line as Marcus aelius one of the greatest stoic philosophers said the happiness of your life depends upon the quality of your thoughts and this applies to how you allow others to treat you if you continue to give kindness to those who feel entitled to it you reinforce the wrong mindset not just in them but in yourself you teach them that you are always available no matter how they treat you but is that truly an act of kindness or is it self- neglect in stoicism self-respect is non-negotiable the stoics believed in virtue Justice and wisdom and part of that wisdom is knowing when to give and when to step back senica once wrote he who is not a good servant will not be a good Master this means that if you don’t command respect through your actions if you let others walk over your kindness you lose control not just over them but over yourself the person who respects themselves knows that kindness should never be given out of obligation it is a gift not a debt when people see that you reward appreciation and not entitlement they begin to respect your boundaries they understand that your kindness is not a weakness but a choice and this is where the power lies too often we fear that if we stop giving if we withdraw our kindness from those who take it for granted we will be seen as rude unkind or selfish but ask yourself why is it selfish to protect your energy why is it rude to expect basic respect in return the truth is it is not there is a crucial difference between kind and peop pleasing kindness is intentional strong and wise peop pleasing on the other hand is rooted in fear the fear of rejection the fear of conflict the fear of being disliked in other words if setting boundaries means some people see you as unkind let them your duty is not to meet the expectations of those who feel entitled to you it is to live virtuously with self-respect and wisdom a truly kind person does not just give endlessly they give wisely they recognize that kindness without boundaries turns into self-sacrifice and self-sacrifice without purpose leads to resentment have you ever found yourself exhausted drained or frustrated because you kept giving to someone who never appreciated it that frustration is a signal it is your mind telling you that something thing is off balance and balance is essential just like the stoics believed in controlling what is within our power you must take control of your kindness ask yourself who truly values what I give who sees my kindness as a gift rather than an expectation who if I stopped giving would still respect me these are the people worthy of your time your effort your kindness so what is the the takeaway do not be afraid to withdraw your kindness from those who demand it do not let fear dictate how you set your boundaries instead practice wise generosity give where appreciation exists and where it does not let go without guilt you are not unkind for choosing who gets access to your energy you are simply living by the stoic lessons that have guided the greatest thinkers of History self-respect wisdom and the courage to stand firm in your values because in the end respect is not commanded through endless giving it is earned through the way you value yourself and when you respect yourself others have no choice but to do the same if you’ve watched up to this point you’re already on the path to understanding the hidden dynamics of kindness and respect in today’s world comment below with stoic strength to airm your commitment to mastering modern stoicism but don’t stop here there’s still valuable Insight ahead that can change the way you navigate respect boundaries and personal power stay until the end to uncover how true kindness Guided by wisdom earns genuine respect number four be generous but not at your own expense being generous is a no quality but without boundaries it can lead to being undervalued or even taken for granted modern stoicism teaches us that true kindness is not about self-sacrifice to the point of exhaustion but about giving wisely to command respect without losing your kindness practice generosity from a place of strength not depletion if you constantly give without regard for your own well-being you risk becoming a resource rather than a person in the eyes of others the key to balanced generosity lies in discernment helping others while ensuring that your kindness is not exploited a common mistake people make is believing that being available and accommodating at all times earns them respect in reality the opposite often happens when you give without boundaries some will come to expect it and others will see it as a weakness to exploit this is why setting limits is not an act of selfishness it is an act of self-respect This Means holding yourself to high standards of kindness while also expecting fair treatment from others if a friend only reaches out when they need something but disappears when you need support it’s not wrong to step back people will respect you more when they realize that your generosity comes with principles a helpful rule in navigating gener generosity is to give from abundance not depletion if giving drains you whether it’s time energy or resources you need to reassess your approach imagine someone who always says yes to extra work hoping for recognition only to be overlooked for promotions while those who set boundaries are respected this happens because people respect what is valued and take for granted what is always available a wise leader knows that saying no at times allows them to say yes with greater impact when it truly matters it is the same in personal relationships if you are always available to solve problems for others while neglecting your own you teach them that your time is worth less than theirs true generosity is not about sacrificing yourself but about offering help in a way that maintains ains your dignity and well-being in Modern Life where people are often overwhelmed by demands from work family and social obligations understanding the stoic secrets of generosity is crucial the world is full of people who will take what you give without thinking twice but it is your responsibility to Define your limits a simple test if your generosity leaves you feeling drained unappreciated or resentful it’s time to adjust those who truly value you will respect the boundaries you set while those who only seek to benefit from you may fade away and that is a good thing this is not about withholding kindness but about ensuring that it is given to those who deserve it as Epictetus wisely noted attach yourself to what is spiritually Superior regardless of what other people think or do hold to your truth true aspirations no matter what is going on around you your kindness is a gift but only when given with wisdom does it truly command respect number five be kind but don’t seek approval if you want to command respect without losing your kindness one of the most powerful stoic lessons to embrace is this be kind but don’t seek approval too often people confuse kindness with people pleasing believing that in order to be liked they must always agree always comply always put others before themselves even at their own expense but in reality seeking approval is a weakness not a virtue when you make other people’s opinions the measure of your self-worth you give away your power Marcus aelius wisely said it never ceases to amaze me we all love ourselves more than other people but care more about their opinion than our own why do we exhaust ourselves trying to be liked trying to fit into a mold trying to meet expectations that were never ours to begin with when your kindness comes from a place of insecurity when you say yes just to avoid conflict when you go along with something just to keep the peace people will sense it and here’s the heart truth they will respect you less not more true kindness is an act of strength not submission a truly kind person does not need validation to feel whole they do good not because they want something in return but because it aligns with their principles epicus taught if you wish to be good first believe that you are bad that is to say recognize the ways in which you compromise yourself notice where your need for approval is dictating your actions and then correct it kindness when done right is not about making others comfortable at your own expense it’s about embodying your values regardless of how others respond imagine a scenario where someone presents an idea that you don’t agree with a people pleaser might nod along forcing a smile afraid to challenge the moment but a strong kind person will hold their ground while while remaining respectful I see where you’re coming from but I have a different perspective a simple sentence but one that shows you have your own mind you don’t need to agree to be agreeable you don’t need to please to be respected ask yourself how often do you say yes when you really mean no how many times have you swallowed Your Truth just to avoid disappointing someone else if you want to command respect start by respecting yourself the stoics believed that virtue courage wisdom Justice and Temperance should be the guiding force of your life not the shifting opinions of others when you live with Integrity when your kindness is rooted in genuine goodwi rather than a desperate need to be liked people notice they might not always agree with you but they will respect you and more importantly you will respect respect yourself so the next time you find yourself hesitating afraid to express your thoughts or enforce your boundaries remember this you were not put on this Earth to be agreeable you were put here to be strong wise and virtuous choose kindness yes but choose it on your terms not as a currency for approval now I want to hear from you what’s more important to you being liked or being respected com comment respect over approval always if you agree that self-worth comes before approval or comment being liked matters just as much if you think being liked matters just as much let’s see where you stand number six protect your energy as fiercely as your time if you want to command respect without losing your kindness one of the most critical stoic lessons to embrace is this protect your energy as fiercely as your time too often people focus on guarding their schedules setting boundaries around their availability and ensuring their time is not wasted but what about their emotional and mental energy respect is not just about how much time you give it’s about how much of yourself you give and to whom Marcus Aurelius wrote in meditations you have power over your mind not outside events realize this and you will find strength this wisdom applies directly to how you manage your energy you cannot control how others act but you can control how much of yourself you allow them to drain your energy is a limited resource if you give it away too freely to the wrong people to pointless conflicts to those who do not value it you will have little left for what truly matters consider the difference between two types of people one person allows everyone to vent their frustrations solve their problems and demand their attention Without Limits by the end of the day they feel drained frustrated and unseen the second person however is kind but selective they support others when they can but they do not absorb unnecessary negativity they listen but they do not take on burdens that are not theirs which person do you think commands more respect kindness does not mean allowing yourself to be an emotional Dumping Ground many people mistake being a good person for being endlessly available but true generosity true kindness comes from a place of strength not exhaustion if you constantly deplete yourself for others without replenishing your own energy you will become resentful not respected this is why stoicism teaches us to be intentional about where we place our Focus senica once said associate with those who will make a better man of you in other words surround yourself with people who uplift you not those who take without giving there is a difference between helping someone who genuinely appreciates your kindness and allowing someone to drain your energy because they see you as an easy source of support the modern world is full of distractions endless notifications unnecessary drama and people who thrive on conflict every time you engage in something meaningless you lose a piece of your energy ask yourself how often do I give my mental and emotional energy to things that do not serve me how many times have I left a conversation feeling worse than when I entered it to command respect you must first respect yourself enough to protect your energy this does not mean cutting people off or becoming indifferent it means recognizing when to engage and when to step back it means setting boundaries not just with your time but with your emotions for example if a friend only reaches out when they need something never offering support in return it it is not unkind to limit how much energy you invest in that relationship if a colleague constantly brings negativity into conversations it is not rude to excuse yourself if social media drains you rather than inspires you it is wise to reduce your time spent on it the strongest people are not those who give endlessly they are those who know when to say I have given enough the most respected leaders think of and mentors do not allow their energy to be dictated by external forces they decide where to invest their focus this is why Marcus Aurelius advised the Tranquility that comes when you stop caring what they say or think or do only what you do when you stop allowing outside distractions to consume your inner peace you gain power power over yourself power over your emotions and ultimately power over how others treat you so what does this mean in practice it means setting mental boundaries as firmly as you set time boundaries it means choosing your battles wisely deciding which conversations deserve your energy and knowing when to walk away from situations that add no value to your life if you want to command respect while maintaining your kindness remember this energy like time is finite give it wisely protect it fiercely and spend it only on what truly matters the world respects those who know their worth and nothing signals self-respect more than guarding your energy from those who do not deserve it number seven know when to walk away knowing when to walk away is one of the most understated yet powerful aspects of commanding resp effect without compromising your kindness in a world where many equate kindness with weakness the ability to step back from toxic Dynamics sends a message far louder than words people will often test boundaries consciously or unconsciously to gauge how much you are willing to tolerate if you allow disrespect to persist you inadvertently signal that such treatment is acceptable however when you decisively walk away from situation s that undermine your dignity you demonstrate an unwavering commitment to self-respect something that naturally earns the respect of others as the stoic philosopher epicus wisely said The more we value things outside our control the less control we have your time energy and peace of mind are among your most valuable assets and not everyone deserves access to them modern stoicism teaches that we must carefully discern where we invest our efforts there is a fine line between being patient and being a pushover you may think that by enduring mistreatment you are displaying resilience but in reality you may be enabling bad behavior whether it’s a friendship that drains your energy a workplace that consistently undervalues your contributions or a relationship that thrives on imbalance staying in such situations does not make you Noble it makes you complicit in your own suffering true kindness is not about allowing others to walk all over you it is about maintaining generosity while ensuring that your own worth is never diminished in the process walking away does not always mean Burning Bridges or severing ties in Anger it means making a conscious decision to remove yourself from situations where respect is absent sometimes distancing yourself is the only way to make people realize your value many only understand what they had once it is gone the moment you show that you are willing to leave when necessary people begin to treat your presence with the respect it deserves this is not about manipulation it’s about setting a standard for how you expect to be treated kindness should never come at the cost of self-worth as senica stated associate with people who are likely to improve you surrounding yourself with those who respect and uplift you is not selfish it is essential for personal growth and mental well-being in today’s fast-paced world where relationships and professional environments can often become transactional it is easy to fall into the Trap Of overgiving The Secret of modern stoicism lies in Striking the perfect balance being kind yet firm G generous yet Discerning compassionate yet self-respecting the ability to walk away when necessary does not make you unkind it makes you wise those who truly value you will respect your boundaries and those who do not were never worthy of your kindness in the first place life is too short to spend it proving your Worth to those who refuse to see it the moment you internalize this truth you not only command respect effortlessly but also cultivate inner peace the ultimate stoic secret to a fulfilling life kindness is a virtue but without wisdom it can lead to disrespect and exhaustion the key is balance being generous yet Discerning compassionate yet firm set boundaries protect your energy and give where your kindness is valued true respect starts with self-respect if you found this video helpful like share and subscribe to the channel turn on notifications so you don’t miss our next video on stoic wisdom for a stronger wiser life see you next time are you being too kind seven lessons on how to deal with those who hurt you modern stoicism don’t set yourself on fire to keep others warm this powerful saying captures a key lesson we often Overlook in our quest to be kind and generous while kindness is a virtue that strengthens relationships and builds character there are moments when being too kind can come at a cost our own well-being in today’s video we’ll dive into how modern stoicism offers invaluable wisdom on balancing generosity with self-care will explore seven powerful lessons on how to navigate relationships set healthy boundaries and stop sacrificing our mental emotional and physical health for the sake of others are you someone who tends to put others first even when it harms you let’s talk about how you can use stoic principles to protect your peace while still being the compassionate person you are if you’ve ever struggled with setting limits in your relationships leave a comment below and share your experience don’t forget to subscribe to stoic secrets for more insights on how stoicism can help you live a life of balance resilience and personal growth number one don’t set yourself on fire to warm others in Modern Life we often find ourselves caught in the cycle of giving whether it’s helping a colleague with a project so supporting a friend through a tough time or stepping in to fix someone else’s problem while kindness and generosity are noble virtues there’s a crucial lesson from stoicism that we must remember don’t set yourself on fire to warm others this stoic principle speaks to the importance of maintaining boundaries and not sacrificing your own well-being in the name of helping others stoicism encourages us to live in accordance with reason and virtue which includes making thoughtful decisions rather than acting impulsively or out of an emotional desire to please others it teaches that we must first tend to ourselves if we are to be of any true help to others there is a fine line between offering assistance and overextending ourselves to the point of exhaustion when we constantly give without checking in on our own needs we risk burning out physically emotionally and M mentally the act of self-sacrifice though often celebrated in modern culture can be counterproductive if it leads to our own suffering in today’s fast-paced world saying yes is often seen as a sign of commitment Good Will and even self-worth however this desire to be helpful or liked can make us blind to the toll it takes on our own lives we can easily become the person who is always ready to lend a hand but never takes time for their own needs as the stoic philosopher epicus wisely stated when you are about to start some task stand for a moment and reflect on the nature of the task you are about to perform this simple but profound advice encourages us to pause before jumping into another commitment it’s important to ask ourselves will helping this person take away from my ability to care for myself if the answer is yes it may be time to practice the stoic virtue of self-discipline and set a boundary this act of reflection doesn’t mean we lack compassion it simply means we recognize that true generosity comes from a place of balance not from self-destruction in our relationships especially with loved ones there’s an underlying temptation to give so much of ourselves that we lose sight of our own needs we may find find ourselves taking on too much thinking we can handle it all but just as a candle cannot burn at both ends in definitely we too cannot sustain endless self-sacrifice without burning out stoicism teaches us that our actions should be governed by Reason Not by guilt or obligation we need to assess whether the task at hand aligns with our values and whether it is a reasonable request to help others with without harming ourselves requires wisdom and discernment in modern stoicism this means taking a step back to ensure we are not giving at the expense of our mental and physical health moreover stoicism reminds us that we cannot control how others respond to our boundaries in fact we may face resistance or even criticism when we choose to say no but this too is part of the stoic practice of accepting what is beyond beond our control the most important thing is that our actions align with our own well-being and integrity Marcus Aurelius the Roman Emperor and stoic philosopher taught waste no more time arguing about what a good man should be be one this wisdom encourages us to act in accordance with our values without feeling the need to justify our choices to others saying no when needed is not a failure of kindness it is a conscious decision to preserve our own peace and resources so we can continue to offer help when it truly serves both others and ourselves in Modern Life where the pressure to constantly give and be available can be overwhelming practicing the art of balance is crucial remember that true generosity doesn’t mean sacrificing your happiness or health it means offering what you can in a sustainable and mindful way by learning to set boundaries and make thoughtful decisions we can live according to the wisdom of stoicism and cultivate a life that honors both our ability to help others and our need for self-care number two reciprocity has an expiration date in a world where we often seek validation stoicism offers us an alternative giving freely without the expectation of anything in return this ancient philosophy teaches that the true value of generosity lies not in what we receive but in what we offer to others when we extend kindness support or love without any anticipation of reciprocation we create a source of inner peace and fulfillment however as human beings we are naturally inclined to hope for some form of acknowledgement or return whether it’s a favor gratitude or simply a gesture of kindness this natural desire to receive something in return can lead to disappointment frustration and even bitterness when our expectations are not met the emotional toll of expecting reciprocity can be profound as we might start mentally tallying up what others owe us whether it’s a favor or a thank you when these debts go unpaid we can feel hurt or betrayed and that emotional burden can chip away at our sense of well-being modern stoicism however teaches us to break free from this cycle of expectation epicus one of the great stoic philosophers famously stated there are two rules to keep ready that there is nothing good or bad outside my own choice and that we should not try to lead events but follow them this powerful teaching reminds us that while we cannot control how others respond to our generosity we can control how we choose to act and react by relinquishing our expectations of reciprocation we free ourselves from the emotional roller coaster that often accompanies unfulfilled desires the more we give without expecting a return the more we cultivate a sense of emotional freedom in this way we are no longer dependent on others to meet our our emotional needs or validate our worth think about the peace that comes from giving for the sheer Joy of it without attaching any strings this sense of Detachment from expectations is not only liberating but essential for our mental well-being it allows us to preserve our peace of mind even in the face of indifference or in gratitude in the modern world we are constantly bombarded with messages that tell us to expect more or demand better but stoicism teaches us that true wealth doesn’t come from material possessions or reciprocal acts it comes from the ability to give without wanting anything in return when we practice this we enrich our lives in ways that are far deeper than any external rewards could provide by embracing this mindset we maintain a sense of equinity and inner tranquility regardless of how others respond to our kindness as you navigate life’s interactions remember that giving

    without expectation is not a sign of weakness or naivity it is a powerful form of emotional resilience in fact it strengthens your inner resolve and enables you to weather the ups and downs of relationships without being tossed around by every slight or unfulfilled promise the stoic philosophy ER Sena echoed this sentiment when he said it is not the man who has little but he who desires more that is poor by focusing on the act of giving rather than on what we might receive we redefine our sense of wealth and fulfillment in the end the key to True generosity is not what we get from others but the peace we cultivate within ourselves as a result of giving freely and without expectation [Music] in the fastpaced and often transactional world we live in today adopting the stoic practice of giving without the need for reciprocity is not only a way to preserve your peace of mind but it is also a profound Act of self-care it allows you to move through life with Grace undisturbed by the fluctuations of others Behavior so the next time you offer something to someone whether it’s a helping hand a kind kind word or an act of Love remember that your true reward is not in what you receive in return but in the calm and fulfillment that come from giving freely without the burden of expectation this is the essence of modern stoicism the freedom that comes when we stop seeking approval and start living according to our own principles of kindness and generosity number three received requests have no limits one of the core principles of stoicism that many of us tend to overlook in our busy fast-paced lives is the importance of setting limits especially when it comes to helping others in a world that constantly demands our attention it can feel like we’re always on call ready to assist give advice or offer emotional support to those who reach out and as human beings it’s natural to want to help we feel good when we are generous when we show kindness and when we make others feel supported but here’s the catch without clear boundaries our willingness to help can quickly spiral into frustration resentment and burnout have you ever said yes to someone even when you felt like saying no simply because you didn’t want to disappoint them or felt guilty for not being able to help it’s easy to slip into this pattern when we lack the courage to set limits however this unchecked eagerness to help others can leave us emotionally drained physically exhausted and mentally overwhelmed and worse it can prevent the very people we’re trying to help from developing the strength and Independence they need to navigate their own lives take the story of a mother who spent her entire life caring for her adult daughter who struggled with illness the mother’s love and support were constant always available and always filled with care but in her efforts to protect and care for her daughter the mother unintentionally stunted her daughter’s growth she did everything for her handled the chores managed the finances and even made decisions that the daughter should have been making herself the mother’s unrelenting desire to help created a pattern of dependency that kept the daughter from learning how to manage on her own when the mother passed away the daughter was suddenly forced to stand on her own to everyone’s surprise she adjusted remarkably well she stepped up took responsibility and began thriving without her mother’s constant help the tragedy here wasn’t the loss of the mother but that her constant giving prevented her daughter from learning how to take charge of her own life life the lesson here is simple yet profound when we overh help we risk preventing others from discovering their own strength from a stoic perspective this is a powerful illustration of why setting boundaries is not just a tool for protecting our own well-being but a crucial part of fostering Independence in others stoicism teaches us that we must learn to distinguish between times when we can truly offer help and times when our assistance may actually be more harmful than beneficial as Marcus Aurelius one of the greatest stoic philosophers famously said a man’s job is to stand upright not to be kept upright by others this quote is a reminder that while helping others is a noble and compassionate act there’s a limit to how much we should intervene in the lives of others by constantly offering assistance Without Limits we may inadvertently dis Empower others from developing the skills they need to face their own challenges think about it how many times have you stepped in to solve someone else’s problem only to realize later that your help didn’t actually solve anything or worse that it only delayed their growth in those moments it’s important to ask yourself is this a situation where my help is necessary or is it one where this person needs to learn and grow on their own own setting clear and healthy boundaries doesn’t mean you don’t care or that you’re unwilling to help it’s simply means that you recognize when your help will be empowering and when it might inadvertently prevent someone from standing on their own by setting limits you not only protect your own energy but also help the people you care about to build their own resilience stoic Secrets like this remind us that generosity isn’t just about giving Without Limits it’s about knowing when and how to give in a way that Fosters long-term growth for both the giver and the receiver we need to balance our kindness with wisdom and that starts with asking is my help really helping here or am I just making it easier for someone to avoid their own responsibility the next time someone asks for your assistance take a moment to reflect ask yourself whether this is a opportunity to guide them toward Independence or whether you’re simply doing what they could and should be doing for themselves by setting healthy boundaries you’re ensuring that your generosity doesn’t come at the cost of your well-being and that it empowers others to manage their own lives boundaries are not just a way to protect your time and energy they are a way to teach others how to take charge of their own growth so let your kindness be a gift that supports Independence rather than creating dependency remember true help isn’t about doing things for others but about giving them the tools and space to do things for themselves if something from today’s video resonated with you share your thoughts in the comments below whether you’re new here or have been with us for a while I want to hear from you if you’re just joining us comment I’m new here or if you’re a seasoned member of our Community drop her I’m seasoned member in the comments to let us know how you’ve been applying these stoic principles in your life your engagement means so much and is a constant source of inspiration for us to keep creating meaningful content now let’s continue our journey of stoic wisdom together number four being seen and treated as fragile in today’s fast-paced world where the pressure to be kind helpful and accommodating is ever present we often Overlook a critical aspect of personal well-being the importance of setting boundaries we may feel compelled to give freely help whenever we can and always say yes to the demands of others however if we give too much without recognizing our own limits we risk not only burning ourselves out but also being perceived as fragile or incapable of asserting our needs this perception can undermine our Authority erode respect and in the long run damage our sense of self-worth this is a fundamental lesson rooted in stoic philosophy which emphasizes Inner Strength self-control and the importance of respecting oneself when we fail to set clear boundaries in our relationships we inadvertently open ourselves up to exploitation it is easy to fall into the Trap of trying to please others driven by a desire to be liked or to feel needed we want to be seen as generous understanding and compassionate but there is a fine line between being helpful and over extending ourselves if we are always available always ready to lend a hand and never set a firm no we send a message to others that we lack the strength to protect our time energy and emotional well-being over time this continuous availability can lead to exhaustion and frustration as others may take advantage of our kindness expecting more from us than is reasonable the issue however is not our desire to help it’s that we haven’t properly safeguarded our own well-being by setting boundaries stoicism offers a powerful remedy for this situation at its core stoic philosophy teaches us to respect ourselves and our time by asserting our boundaries we communicate to others that we value our energy and resources and that we are not endlessly available for the taking saying no is not a sign of selfishness but an important exercise in self-respect when we set clear limits we redefine how others perceive us not as a person to be exploited but as someone who values their own time and well-being as Cicero a well-known stoic philosopher reminds us what you think of yourself is much more important than what others think of you this simple but profound statement reflects the stoic belief that our sense of self-worth should not be defined by external approval or the opinions of others but by our own principles and the respect we show ourselves while saying no might feel uncomfort able especially in a world that often equates kindness with accommodating others it is essential for maintaining our own mental and emotional health in Modern Life we are often made to feel guilty if we don’t help others or if we refuse requests that drain us we may worry about exclusion criticism or being seen as unkind these feelings are natural but from a stoic perspective they are opportunities for growth the discomfort we feel in asserting our boundaries reveals our attachment to the approval of others and challenges us to examine our priorities stoicism teaches us that such challenges are not obstacles but tests of our inner strength and wisdom by facing these tests we gain valuable insights into who truly respects our boundaries and who is simply taking advantage of our generosity over time we become more skilled at Discerning who deserves our time and energy and who simply seeks to exploit our kindness setting boundaries is not about shutting ourselves off from others it’s about creating space for the things that truly matter it’s about making sure we can give to others in a sustainable way without depleting ourselves healthy boundaries allow us to engage with the world from a place of strength not fragility they help us protect our well-being while still fostering meaningful relationships with those who respect us and reciprocate our efforts when we say no we are not rejecting others we are protecting ourselves ensuring that we can continue to contribute positively and maintain a healthy balance in our lives modern stoicism teaches us that by navigating the challenges of setting boundaries we cultivate resilience and self-awareness each time we practice the art of saying no we become better at balancing our generosity with self-respect ultimately leading to deeper more fulfilling relationships this practice strengthens us and those around us enriching our lives and helping us live with greater purpose and Clarity in a world that often demands more than we can give stoicism offers a frame work for reclaiming our strength and ensuring that our kindness is sustainable by setting boundaries with respect and Clarity we can navigate our relationships with wisdom avoid burnout and build a life where both our own needs and the needs of others are honored through Modern stoicism we learn that true strength comes not from constant giving but from knowing when to say no and preserving our energy for what truly matters number five we will see who our true friends are in today’s world where superficial and transactional relationships often dominate stoicism encourages us to approach our interactions with discernment and wisdom at the core of stoic philosophy is the belief that actions speak louder than words true friendship according to stoicism is Def defined by consistent thoughtful actions rather than Grand promises or declarations not all relationships are built on this Foundation often we encounter people who value US not for who we are but for what we can provide these individuals may seek our company when we are generous with our time energy or resources only to distance themselves once we stop overextending ourselves while this can be painful stoicism helps us view such experiences not as betrayals but as opportunities to understand the true nature of these relationships as Marcus Aurelius wisely said when you are offended at any man’s fault turn to yourself and reflect in what way you are a culprit by embracing this self-reflection we can move past resentment and accept that others Behavior often reflects their needs and limitations rather than our worth stoicism also emphasizes the practice of discernment which allows us to differentiate between genuine relationships and those that are opportunistic it teaches us to observe not only what people say but how they act especially in times of need this Discerning perspective is invaluable in navigating both personal and professional Relationships by focusing on those who truly appreciate us for Who We Are we can protect our emotional well-being and invest our energy in relationships that are mutually beneficial stoicism does not discourage generosity or kindness but it advocates for directing these qualities toward people who will value them when we stop overextending ourselves we create space for more authentic connections relationships that are based on respect reciprocity and shared growth by doing so we preserve our our energy and flourish in environments where our presence is respected not exploited the reality is that relationships may not always stay balanced people we thought would be there for us may turn away when the dynamic of give and take shifts however stoicism helps us deal with these disappointments with Grace it teaches us that we cannot control others actions but we can control how we respond we are not respons responsible for others choices but we are responsible for how we navigate these situations the stoic approach encourages us to let go of resentment and focus on cultivating relationships that support our growth and well-being true friends are not just there in times of convenience but are those who respect our boundaries offer support in struggles and encourage our development these are the relationships that bring True Value to Our Lives as we practice discernment we create space for Meaningful lasting connections that enhance our lives in profound ways these relationships grounded in mutual respect and understanding encourage us to reflect on the quality of the connections we maintain stoicism teaches that true friendship is about understanding and being understood as senica said one of the most beautiful qualities of true friendship is to understand and to be understood in Modern Life where we are often distracted and pulled in many directions this stoic perspective on friendship provides both Clarity and a sense of Peace it reminds us that the quality of our relationships not their quantity is what truly matters modern stoicism teaches us that the true measure of friendship lies not in what others cannot offer us but in how they value us as individuals by practicing discernment and reflecting on the quality of our relationships we can identify those who genuinely support us and invest our time and energy in those connections we are not obligated to maintain relationships that drain us or leave us feeling unappreciated instead we can focus on cultivating authentic meaningful relationships that contribute to our well-being and fulfillment embracing this stoic approach frees us from the disappointment of shallow one-sided friendships and opens the door to deeper more rewarding connections that sustain us over time number six the power of emotional Detachment one of the most commonly misunderstood Concepts in stoicism is emotional detachment many believe it means becoming cold indifferent or even heartless in reality emotional Detachment is about learning to manage our emotions so that they do not control our actions or reactions in a world where we are constantly faced with emotional triggers whether it’s a harsh comment from a coworker a misunderstanding with a friend or everyday stress stoicism offers a valuable tool for navigating this emotional turbulence it teaches us to respond with Reason Not impulse the goal isn’t to suppress or ignore our feelings but to understand them and choose how we respond to them by doing this we can avoid reacting in ways that do not align with our values or best interests when we practice emotional Detachment we are not denying our feelings we are simply preventing them from dictating our behavior for example imagine imagine you’re in a meeting and a colleague sharply criticizes your idea your first instinct might be to feel anger or frustration and perhaps even to respond defensively but stoic emotional Detachment encourages you to pause and reflect before reacting in that moment you can take a deep breath acknowledge your feelings and choose a response that is thoughtful measured and aligned with your values this pause between stimulus and response is key in stoic philosophy it allows us to see emotions as signals not commands rather than being Swept Away by emotional impulses we can choose the best course of action preserving our dignity and peace of mind this practice of emotional Detachment becomes especially important when others attempt to provoke us or manipulate our emotions for example if a friend or family member says something hurtful emotional Detachment helps prevent an impulsive reaction it doesn’t mean you stop caring about others or their feelings rather it means you don’t let their behavior disturb your inner peace by managing our emotions we can stay grounded and calm in situations that might otherwise lead to unnecessary conflict this approach isn’t about avoiding difficult conversations or conflict but responding to Life’s challenges from a place of clarity and reason take Sarah for example she often found herself in conflict with her friends every time someone made a critical or hurtful comment she immediately felt wounded which led to arguments and strained relationships one day Sarah decided to practice emotional Detachment the next time a comment upset her instead of reacting immediately with anger or hurt she paused she took a moment to the time Sarah found that she wasn’t as affected by the words of others she still cared about her friends but emotional Detachment helped her respond calmly and thoughtfully ultimately bringing her more peace as the stoic philosopher epicus wisely said wealth consists not in having great possessions but in having few wants this concept of Detachment is key when we detach from the need to control everything or everyone we open up space for Freedom emotional Detachment allows us to preserve our peace and respond to Life’s challenges in a measured way protecting our emotional well-being and avoiding unnecessary conflict it also helps us deal with toxic individuals who might try to drain our energy or bring negativity into our lives by practicing Detachment we can protect ourselves from their harmful behaviors and remain focused on what truly matters it’s important to note that emotional Detachment is not about becoming emotionally numb or disengaged rather it’s about consciously choosing how we respond to the world around us when we practice Detachment we gain the ability to respond with logic and Clarity instead of emotional impulsivity this practice helps us build healthier more balanced relationships because we are no longer at the mercy of emotional highs and lows we can still care deeply about others but we no longer let their actions determine our emotional state stoic Secrets like this teach us that by letting go of the need to control everything we gain control over our own happiness and inner peace the next time you find yourself in an emotional situation ask yourself am I reacting out of impulse or am I responding with calm and Clarity by practicing emotional Detachment you can maintain control over your emotions protect your inner peace and navigate even the most challenging situations with Grace emotional Detachment is not about being cold or detached from others it’s about being wise enough to recognize your emotions and choose the best response no matter what life throws your way this practice empowers you to live more peacefully thoughtfully and authentically number seven letting go of past hurts letting go of past hurts is one of the most liberating practices we can Embrace in our lives holding on to grudges anger or resentment only serves to poison our own minds and Spirits leaving us trapped in negative emotions that prevent us from fully experiencing the present in fact clinging to these feelings doesn’t harm the person who wronged us it harms us modern stoicism teaches us that forgiveness is not just a moral or ethical Choice it is a powerful means of freeing ourselves from emotional burdens that weigh us down the pain we hold from the past often tethers us to harmful emotions keeping us stuck in a cycle of frustration and Sorrow by choosing to release these emotional weights we open ourselves to a life of peace tranquility and emotional Freedom it’s crucial to understand that Letting Go doesn’t mean forgetting or excusing the actions of others it means making the conscious decision to sever the emotional attachment to those past events that caused us pain choosing instead to focus on our own healing and growth stoicism encourages us to focus on what is within our control our our thoughts feelings and responses while accepting that we cannot change the past in doing so we gain the power to move forward instead of being defined by the wrongs done to us Marcus Aurelius one of the most revered stoic philosophers offers powerful guidance on this subject when he says the best revenge is to be unlike him who performed the injury this wisdom teaches us that the most effective way to respond to harm is not through retaliation or bitterness but by Rising above it maintaining our integrity and using the experience as a stepping stone for personal growth choosing to rise above harm allows us to preserve our peace of mind and keep our emotional equilibrium intact rather than being Shackled by resentment we can reclaim our inner peace and emotional strength the act of Letting Go begins with a an knowledging the pain and reflecting on its source it is only through understanding the root causes of our emotional hurt that we can begin the process of releasing it mindfulness and self-reflection are invaluable Tools in this journey of forgiveness they allow us to step back and look at our emotions objectively helping us separate the person who hurt us from the emotional baggage We Carry in the process of forgiving we don’t condone the behavior that caused us harm we simply choose to no longer allow that behavior to have a hold on our present state of being in this way forgiveness becomes not a gift we give to others but a gift we give ourselves allowing us to break free from the chains of anger and resentment by letting go of past hurts we release ourselves from the cycle of pain and open up space for healing emotional balance and stronger more authentic relationships this is a practice that directly aligns with the stoic goal of cultivating emotional resilience allowing us to live more freely and fully in the present moment forgiveness is not about excusing harmful Behavior or forgetting the wrongs that were done to us it’s about choosing peace over bitterness it’s about acknowledging the hurt learning from it and then choosing to release the hold it has over us it’s a process of reclaiming our emotional freedom and taking back control of our lives in doing so we make space for a future that is not burdened by the weight of past grievances by choosing to forgive we become better versions of ourselves more compassionate more resilient and more focused on creating a life rooted in peace rather than past pain modern stoicism reminds us that we are the masters of our responses and by by letting go of past hurts we reclaim our power and create room for Joy growth and emotional balance when we practice forgiveness we are not only improving our emotional health but we are also strengthening our relationships and cultivating a future that is open to possibility rather than weighed down by the Shadows of the past letting go of past hurts is essential for emotional well-being and it is one of the most free steps we can take in our personal development by embracing the stoic principle of forgiveness we clear the path for emotional balance healing and deeper connections with others as we let go of resentment and bitterness we unlock the freedom to move forward with a lighter heart and a clearer mind in this way forgiveness becomes the key that unlocks the door to a brighter more peaceful future one that is no longer defined by past pain but by the strength resilience and wisdom we gain from overcoming it what do you think about setting boundaries to protect your peace it can be tough but it’s so necessary for our emotional health here are three simple responses you can share in the comments boundaries are essential for peace or it’s hard but necessary or setting limits saves energy be sure to watch until the end of the video especially the section on insights on healing and setting boundaries you’ll find some deep thought-provoking tips that could change how you approach relationships insights on healing and setting boundaries having explored seven crucial lessons on how to deal with those who hurt you it’s time to delve deeper into to the next phase of healing and personal growth once we understand these lessons the next step is to gain further insights into how to heal set healthy boundaries and cultivate emotional resilience let’s now explore how you can continue your journey toward emotional well-being and self-empowerment number one developing self-worth and self-love self-worth is the internal compass that shapes how we perceive ourselves and is essential for setting boundaries that protect our emotional well-being it is not determined by others opinions or actions but by recognizing our own intrinsic value modern stoicism teaches us to cultivate self-worth from within rather than relying on external validation when we learn to see ourselves as valuable and Des deserving of respect we naturally create boundaries that preserve our peace of mind this self-awareness serves as a shield preventing others from taking advantage of us or diminishing our sense of worth the Cornerstone of this process is self-love a practice that nurtures our emotional health and strengthens our ability to stand firm in our decisions self-love is not about selfishness or narcissism it is about cultivating a balanced sense of self-respect and treating ourselves with the same kindness and compassion we would offer to a dear friend by embracing self-love we set an example for how we wish to be treated and we can enforce the boundaries that Safeguard our emotional well-being without self-love asserting our needs or saying no can become difficult often leaving us conflicted or guilty building self-worth involves understanding that our value does not depend on external approval an essential part of this process is practicing self-compassion when we make mistakes or face setbacks instead of being harsh on ourselves we learn to treat ourselves with the same understanding we would extend to others as the stoic philosopher epicus said wealth consists not in having great possessions but in having few wants similarly our true wealth lies in our ability to recognize and affirm our own worth rather than depending on others opinions practicing self-compassion helps to strengthen our emotional resilience and positive affirmations can reinforce our self-esteem each small victory no matter how seemingly insignificant should be celebrated as it builds confidence and belief in ourselves by acknowledging our progress we reinforce our worthiness of love respect and care another key aspect of self-worth as taught by stoicism is focusing on what we can control in Modern Life we cannot control the actions of others or external circumstances but we can control our reactions by cultivating self-love we free ourselves from the need for external validation as we no longer depend on others to feel secure in our worth this emotional Independence is crucial for developing the resilience needed to set and maintain healthy boundaries as Marcus Aurelius wisely said the happiness of your life depends upon the quality of your thoughts if we reinforce our selfworth and treat ourselves with respect we create a solid foundation for emotional well-being this Inner Strength allows us to maintain boundaries without guilt or second guessing our decisions in a world where external pressures and societal expectations often fuel self-doubt developing a strong sense of self-worth has never been more important it empowers us to prioritize our needs and establish relationships that are mutually respectful and supportive by setting boundaries rooted in self-love we approach others from a place of emotional strength ensuring that our relationships enhance Our Lives rather than depleting us moreover developing self-worth and self-love is an ongoing Journey not a one-time effort each day presents an opportunity to reaffirm our value practice self-compassion and protect our emotional well-being with the wisdom of modern stoicism we are reminded that by focusing on what we can control our thoughts and actions and responses we can navigate life’s challenges with resilience and peace through self-love we build a deep Inner Strength that supports Us in all areas of life enabling us to grow heal and Thrive cultivating self-worth and self-love is essential for living a fulfilling and peaceful Life by recognizing our inherent value we create space for healthy relationships and meaningful connections modern stoicism teaches us that we are The Architects of our own happiness and by embracing our worth we free ourselves from the need for external validation this emotional Independence allows us to protect our well-being while fostering relationships that are rooted in mutual respect as we continue to nurture self-love we equip ourselves with the emotional resilience needed to face life’s challenges with confidence creating a life that aligns with our true values and is authentic to our inner selves number two the importance of patience and understanding one of the most powerful stoic Secrets is the virtue of patience and understanding particularly when we face the pain caused by others in a world where we’re often encouraged to react quickly and defend ourselves in the face of hurt stoicism offers a different approach creating space between our emotions and our actions when we’re hurt our immediate Instinct might be to lash out or defend ourselves but stoicism teaches us to pause Instead This pause allows us to reflect process our emotions and choose a thoughtful response rather than reacting impulsively practicing patience helps us build emotional resilience ensuring that we’re not controlled by our immediate reactions it doesn’t mean suppressing feelings but rather understanding and managing them to make better decisions in difficult situations a key aspect of patience is understanding the behavior of others it’s easy to take offense when someone says or does something hurtful but often their actions come from their own struggles when we see their behavior through the lens of compassion instead of of anger we realize their actions might be more about them than about us people often lash out because they’re dealing with their own pain or unresolved issues understanding this helps us respond with empathy not resentment this shift in perspective doesn’t excuse harmful Behavior but it allows us to protect our peace and avoid letting their actions disrupt our emotional state with patience we create space for both both ourselves and others to heal enabling us to respond with more clarity and calm emotional healing too requires patience when we’re hurt the natural urge is to move past the pain quickly however emotional wounds don’t heal overnight if we rush through the process we might only cover the wound temporarily without truly addressing the underlying issue stoicism teaches that emotional healing is a journey much like physical healing instead of suppressing or rushing our feelings we should give ourselves time to process and reflect on them patience allows us to heal more fully gaining Clarity and resilience this process isn’t always easy but through patience we grow stronger from our experiences and emerge with a healthier mindset consider a modern example Sarah a young woman who often found herself in conflict with her friends each time someone made a hurtful comment Sarah’s first reaction was anger leading to arguments and strained relationships one day she decided to apply the stoic principle of patience the next time she was hurt she paused and reflected she realized her friend was struggling with personal issues and the comment wasn’t a personal attack on her this shift in perspective allowed ER to respond with understanding instead of defensiveness over time her practice of patience not only helped her heal emotionally but also strengthened her relationships and brought her a deeper sense of Peace as stoic philosopher epicus said wealth consists not in having great possessions but in having few wants in the same way emotional wealth isn’t about avoiding pain or controlling every situation but about without cultivating patience and understanding in the face of adversity detaching from the need for immediate resolution allows us to approach challenges with wisdom and Grace practicing patience helps us respond thoughtfully preventing impulsive actions we might regret to cultivate patience in daily life try mindfulness practices like deep breathing meditation or simply taking a moment before reacting to emotional triggers these techniques help us slow down Center ourselves and respond more clearly the next time you’re hurt or facing a challenge ask yourself am I reacting out of impulse or am I responding with patience and understanding this question can help you apply the stoic secret of patience enabling you to navigate life with greater Clarity emotional resilience and peace patient allows us to protect our emotional well-being and respond with empathy both for others and for ourselves by practicing patience we can heal grow and ultimately find peace in the face of adversity number three the power of perspective one of the most powerful Tools in managing hurt and adversity is perspective modern stoicism teaches us that pain and suffering are inevitable but they don’t have to Define us while we can’t always control what happens we can control how we respond pain rather than being our enemy can be a catalyst for growth resilience and self-discovery by adjusting our perspective we can transform difficult situations into opportunities for personal development instead of letting negative emotions consume us we can shift our view seeing pain as a lesson rather than a burden in this way we lighten the emotional load and turn adversity into a stepping stone for growth reframing negative events is a crucial skill for maintaining emotional balance instead of seeing hurtful situations as personal attacks we can choose to view them as valuable lessons for instance a difficult conversation with a friend might reveal where our communication needs Improvement or a challenging situation at work May highlight areas where we need to assert ourselves more confidently this shift in perspective doesn’t deny the hurt but reframes it allowing us to focus on what can be learned from the experience by changing the narrative we gain control over our emotional response which is key to navigating life’s difficulties with resilience resilience the ability to bounce back from setbacks thrives on this mindset shift it’s not about avoiding pain but learning to navigate it without losing emotional stability resilient individuals focus on what’s within their control our thoughts feelings and actions and remain Anchored In what truly matters our integrity and growth instead of being paralyzed by setbacks we use them as fuel for Progress this perspective allows us to stay grounded and move forward with determination even in the face of adversity a practical tool for shifting perspective is the practice of gratitude in a world that often highlights the negative gratitude helps us focus on the positives even in the toughest of times there’s always something to be grateful for a supportive friend a moment of peace or simply the chance to learn from a difficult experience making gratitude a habit trains our minds to look for the good in every situation helping us maintain a positive outlook even in challenging times stoic philosopher senica wisely said we suffer more often in imagination than in reality this reminds us that much of our pain is not from external circumstances but from our own negative interpretations gratitude and mindfulness help us stay grounded in the present preventing us from spiraling into despair another way to shift perspective is by challenging negative thoughts as they arise in moments of difficulty it’s easy to fall into self-pity or blame the stoics understood that our thoughts shape our emotional experience if we can recognize and challenge negative thoughts we regain control over how we respond acknowledging painful emotions without letting them control us allows us to reframe the situation and move forward with Clarity and strength the power of perspective is about more than just denying pain or pretending challenges don’t exist it’s about choosing how to respond to adversity stoicism teaches that we are not at the mercy of external events we hold the key to our emotional Freedom through our thoughts and attitudes by reframing negative experiences and maintaining a resilient Outlook we reduce the emotional turbulence that life brings as Marcus Aurelius wisely said the happiness of your life depends upon the quality of your thoughts in today’s world where challenges are constant the ability to shift perspective is more important than ever by practicing gratitude mindfulness and reframing we can navigate life’s difficulty ulties with emotional balance and purpose the power of perspective is essential for managing hurt and adversity by adjusting our mindset we not only release the emotional weight of pain but also create space for growth resilience and emotional strength through the lens of modern stoicism we can transform hardships into opportunities for self-improvement and learning we are not defined by the pain we experience but by how we Rise Above It by reframing challenges and focusing on what is within our control we Empower ourselves to live with greater Clarity peace and emotional balance based on the stoic principles you’ve been learning you’re building a strong inner resilience to manage your emotions and create a more peaceful Life share with us in the comments I value myself or I see challenges as opportunities for growth to let us know how you’re applying these principles in your life and don’t forget to stay tuned there’s only one lesson left and you’ll regret missing it number four practicing empathy and compassion empathy is the ability to understand and share the feelings of another and it plays a vital role in managing challenging relationships and emotional pain even when we are hurt empathy allows us to to pause and consider the other person’s motivations struggles and challenges rather than reacting impulsively with anger or resentment empathy provides the emotional space needed to respond thoughtfully this concept is deeply rooted in modern stoicism which teaches us that while we cannot control the actions of others we can control how we react as epicus wisely said it’s not what happens to you you but how you react to it That Matters by stepping into the other person’s shoes we break free from the cycle of emotional retaliation fostering our own healing and building healthier more balanced relationships this approach helps us make conscious choices that align with our values allowing us to move forward with Clarity and resilience compassion an extension of empathy acts as an antidote to resentment holding on to anger or bitterness only empowers others to control our emotions trapping Us in the very pain we seek to escape compassion on the other hand releases us from this grip it doesn’t mean tolerating mistreatment but rather approaching difficult situations with kindness and understanding without compromising our boundaries as Marcus Aurelius said the best revenge is to be unlike him who performed the injury compassion allows us to respond with dignity healing from past wounds while still protecting our peace of mind it enables us to let go of negative emotions freeing us to move forward without becoming bitter or emotionally drained empathy and healthy boundaries are not mutually exclusive they can coexist understanding the struggles behind another person’s harmful Behavior allows us to set clear and compassionate boundaries without escalating conflict we can acknowledge the other person’s pain while asserting our own needs and protecting our emotional well-being modern stoicism teaches that we have the power to control how we respond to others by practicing empathy we can protect our emotional health without compromising our values or becoming overwhelmed setting healthy boundaries ensures our peace while still respecting the humanity of others fost ing a balanced emotional environment cultivating empathy requires active listening and a conscious effort to understand others perspectives this involves more than hearing words it means recognizing the emotions and struggles beneath the surface reflecting on our own experiences of pain can deepen our empathy reminding us that everyone faces challenges even if they are not visible when we recall moments when we were hurt or misunderstood we develop a greater sense of compassion for others empathy in this way becomes both a tool for personal growth and a bridge to Stronger more resilient Relationships by practicing empathy regularly we navigate difficult relationships with more grace setting boundaries that protect us while fostering meaningful connections modern stoicism provides a powerful framework for practicing EMP empathy and compassion it teaches us that we cannot control others actions but we can control our responses by adopting this stoic mindset we learn to understand those who may hurt us protecting ourselves in ways that Foster personal growth instead of conflict stoic philosophy reminds us that true peace comes not from external circumstances but from maintaining inner calm and compos Ure when we approach hurt and betrayal with empathy and compassion we strengthen our emotional resilience and create space to set healthy boundaries that preserve our well-being these practices lead to a more Balanced Life free from anger and resentment enabling us to thrive emotionally and mentally practicing empathy and compassion doesn’t mean being passive or tolerating mistreatment it means responding to hurt with understanding while still protecting our emotional health modern stoicism teaches us that while we cannot control what others do we can control how we react by cultivating empathy we approach difficult relationships with compassion turning potential conflicts into opportunities for growth this balanced approach not only Fosters emotional healing but also strengthens relationships empowering us to move forward with greater peace and Clarity in our lives as we wrap up today’s video I want to remind you of the key takeaways setting boundaries is not just important it’s essential for maintaining your mental and emotional well-being by establishing clear boundaries you protect yourself from burnout and preserve your energy for the things that truly matter remember practicing stoicism in daily life through self-discipline emotional awareness and discernment will help you build stronger healthier relationships and navigate challenges with resilience and peace of mind now take a moment to reflect on your current relationships are there areas where you’ve been overextending yourself where can you set healthier boundaries to prioritize your own needs if you found today’s lesson helpful please like this video share it with someone who could benefit And subscribe to stoic secrets for more content on stoicism and personal growth don’t forget to turn on notifications so you never miss out on our upcoming videos thank you for being here today remember it’s okay to say no when you need to and true generosity always comes from a place of balance and self-respect I wish you strength and peace as you continue to apply stoic principles in your life see you in the next video nine ways how kindness will ruin your life stoicism modern stoicism while kindness is often celebrated as one of life’s greatest virtues what happens when that kindness begins to hurt more than it helps Society constantly pushes us to put others first encouraging selflessness as the ultimate goal but in the modern world excessive kindness can have unintended consequences it can leave you drained exploited and even stripped of your own sense of self-worth here at stoic secrets we uncover the Truths Behind modern stoicism and how its ancient wisdom can help us navigate these challenges in this video we’ll explore nine ways how kindness will ruin your life and reveal how the principles of stoicism can Empower you to set boundaries protect your well-being and transform your relationships for the better stay with us as we uncover how to make kindness a strength not a sacrifice number one people will take advantage kindness is often celebrated as a noble and admirable virtue a quality that strengthens relationships and fosters good will however when offered without boundaries it can become a double-edged sword cutting into your well-being and opening the door for others to take advantage of your generosity excessive kindness given freely and Without Limits sends the message that your resources whether time energy or effort are infinite and always available this creates fertile ground for exploitation where people begin to rely on you not because they value your help but because it has become convenient for them over time this imbalance subtly erodes mutual respect and leaves you feeling unappreciated even resentful picture a coworker who constantly leans on you to complete their tasks but never offers to assist you in return such a scenario illustrates how unchecked kindness Fosters dependence undervaluing your contributions while ignoring your boundaries this cycle of overextending yourself is not just emotionally draining but also counterproductive when you consistently give without considering your own needs you inadvertently teach others that your kindness is not a gift but an obligation they may come to expect your help as a given rather than appreciating it as an intent Act of Good Will Marcus Aurelius one of the great stoic philosophers reminds us you have power over your mind not outside events realize this and you will find strength his words underscore the importance of self-awareness and mindful action qualities that modern stoicism emphasizes as essential for navigating the complexities of contemporary Life by understanding your own limits and acting with intention you can ensure that your kindness remains meaningful and does not become a source of personal depletion in today’s fast-paced world where demands on our time and energy are constant the principle of setting boundaries is more important than ever boundaries are not about denying kindness but about protecting its integrity and ensuring that it is given from a place of genuine care rather than obligation when you communicate your limits confidently and assertively you teach others to respect your time and effort this Clarity Fosters a dynamic where kindness is valued and mutual respect is preserved setting these boundaries may feel uncomfortable at first but It ultimately empowers you to maintain balance and prioritize your well-being kindness when practiced with wisdom and moderation becomes a source of strength rather than a vulnerability modern stoicism offers valuable guidance here teaching us to approach kindness not as a limitless resource but as a deliberate choice that aligns with our principles by embracing the stoic ideal of temperance you transform your kindness into a practice that uplifts both yourself and others creating meaningful connections that are rooted in mutual respect as you navigate life’s complexities remember that kindness should not come at the expense of your own Inner Harmony by balancing compassion with self-awareness you create a life where your generosity remains a powerful force for good both for others and for yourself number two you may be seen as weak kindness when given freely and without boundaries can sometimes bring about unintended and even painful consequences what starts as a genuine desire to help can be misunderstood as a lack of resolve or strength encouraging others to take advantage of your accommodating nature have you ever had a friend who repeatedly borrows money never repaying it not because they can’t but because they see your generosity as weakness or perhaps a colleague who constantly relies on you to clean up their messes assuming you’ll always step in over time these situations can leave you feeling drained unappreciated and even disrespected your energy is consumed your confidence eroded and you may begin to wonder why your kindness doesn’t lead to the connection and appreciation you had hoped for the respect you once commanded starts to diminish as others assume you’ll always comply no matter how inconvenient or costly it is to you this isn’t just a blow to your emotional well-being it’s a quiet Insidious erosion of your dignity stoicism however offers a perspective that can help you navigate this delicate balance the philosophy teaches that kindness while a noble virtue is most powerful when it is deliberate and measured kindness without boundaries loses its Essence and often its value picture a workplace scenario a colleague consistently dumps l last minute tasks on you knowing you’ll never say no at first you take on the extra work out of a desire to be helpful or a fear of being seen as uncooperative but the weight of their responsibilities starts to overwhelm you finally you draw a line calmly explaining that while you’re happy to support when needed you can’t manage additional tasks at the expense of your own priorities to your surprise they don’t react negatively instead they acknowledge your honesty and make an effort to respect your time by asserting yourself you not only protect your energy but also shift the dynamic earning respect and fostering a healthier interaction the stoic secrets of inner strength and self-discipline remind us that saying no is not an act of Cruelty but a declaration of self-respect when you practice assertiveness you send a clear message your kindness is a conscious choice not a limitless resource to be taken for granted this approach allows you to build relationships grounded in mutual respect where kindness is a shared exchange rather than a onesided expectation true kindness uplifts both the giver and the receiver creating connections rooted in understanding and balance take a moment to reflect how often have you felt depleted because someone mistook your kindness for weakness could things have been different if you had established firmer boundaries stoicism doesn’t ask you to close your heart or become indifferent instead it calls you to protect your energy and ensure that your actions stem from strength and Clarity when you give freely but thoughtfully your kindness becomes more impactful and sustainable the next time you’re tempted to stretch yourself too thin pause and ask is this act of kindness coming from a place of genuine willingness or is it depleting me are you helping others while neglecting your own well-being remember the courage to say no when necessary is not selfish it’s an act of self-preservation that ensures you can continue to give authentically even the smallest no can be one of the kindest gifts you offer to your yourself and to those around you by embracing this balance you’ll find that your kindness becomes a source of strength enriching your relationships and your life in ways that are both profound and enduring number three your priorities will be ignored let’s take a deeper dive into kindness and how when it’s not balanced it can become a silent thief of your priorities and personal growth both picture this you’ve become the go-to person for everyone around you a coworker needs help finishing a project a friend needs advice late into the night your neighbor needs a hand with their latest Home Improvement naturally you step up helping others feels rewarding at first it’s uplifting to know you’re making someone’s life easier bringing a smile to their face or being the person they can count on but over time you begin to notice something the things that are most important to you are slipping further and further down your priority list that weekend project you wanted to finish still untouched the quiet evening of rest you promised yourself forgotten you’re running on empty frustrated and wondering where all your energy went have you ever asked yourself at what point does helping others turn into sacrificing myself this is where Modern stoicism provides much needed Clarity and direction if you’re constantly pouring yourself into others needs while neglecting your own you’re not engaging in kindness you’re engaging in self-neglect and here’s the hard truth when you allow your well-being to erode the kindness you offer becomes less effective and authentic how can you truly support others if your own Foundation is crumbling true kindness doesn’t require you to exhaust yourself or abandon your personal goals it comes from a place of balance where you can give generously because you’ve taken care of your own needs first think of it like this you can’t pour from an empty cup when you fail to set boundaries or say no when necessary you risk burnout resentment and a gradual loss of self-respect epicus wisely observed no man is free who is not master of himself so ask yourself are you in control of your time or are you letting the demands of others dictate your life the key to preserving both your kindness and your sense of self lies in learning to set firm compassionate boundaries saying no isn’t a rejection of others it’s an affirmation of your priorities and self-respect take a moment to reflect on what truly matters to you when someone asks for your help pause and ask yourself will this align with the life I want to build communicating your needs openly and honestly with yourself and with others is one of the most empowering acts of self-care you can practice it’s not about being selfish it’s about ensuring that your kindness is sustainable and that it enhances your life as much as it supports others remember your time and energy are finite resources and how you spend them shapes the person you become balance is everything when you protect your priorities you’re not just benefiting yourself you’re also ensuring that the help and support you offer come from a place of genuine strength and abundance modern stoicism teaches us to live intentionally to focus on what we can control and to build lives filled with purpose and fulfillment so let me leave you with this question how can you give your best to the world if you’re not being true to yourself number four you will attract opportunists excessive kindness though admirable in intent can sometimes have unintended consequences attracting opportunists who see your generosity not as a meaningful Exchange but as an endless resource to exploit imagine a colleague who consistently asks for favors borrows your time or leans on your support yet never reciprocates when you are in need these are not mere instances of imbalanced kindness they are warning signs of relationships that take far more than they give over time such Dynamics do more than exhaust your physical energy they deplete your emotional Reserves leaving you feeling unvalued and drained the wisdom of the ancient stoic philosopher epicus offers Insight here it is impossible for a man to learn what he thinks he already knows this serves as a call to approach relationships with Clarity and self-awareness recognizing the critical difference between genuine connections and exploitative ones the core of stoic philosophy lies in discernment the ability to evaluate situations and relationships with wisdom and precision this is especially vital in today’s fastpaced and interconnected world where opportunities for connection abound but so too do the risks of engaging with individuals who lack mutual respect or Genuine appreciation relationships that thrive are built on shared effort Mutual care and a sense of equality while those with opportunists often become imbalanced leaving one party to carry the weight of the connection perhaps you’ve encountered people who consistently demand your attention time or resources but never offer anything meaningful in return in such situations the stoic secret to peace lies in establishing and maintaining boundaries a practice that isn’t selfish but essential for preserving your self-worth and well-being setting clear expect ations in relationships is a profound Act of self-respect by observing how others respond to your boundaries you can discern who truly values your kindness and who merely seeks to benefit at your expense those who genuinely care will respect your limits while opportunists will often become frustrated or withdraw when they realize they cannot take advantage of you senica’s Timeless advice associate with those who will make a better man of you serves as a reminder to carefully choose your companions and focus on fostering relationships that contribute to your growth and Happiness by prioritizing connections with individuals who uplift and support you you align yourself with stoic principles of balance and virtue ensuring your kindness is met with equal appreciation and reciprocity kindness should never come at the cost of your inner peace your emotional stability it is a powerful and transformative Force but it must be guided by wisdom and self-awareness to wield kindness effectively you must learn to balance generosity with discernment understanding that not every relationship is worth your time and energy by practicing self-reflection and remaining Vigilant in your interactions you protect yourself from the emotional toll of one-sided Connections in instead you create space for Meaningful enriching relationships that Inspire and fulfill you the stoic secrets of discernment and self-awareness provide Timeless guidance for navigating these challenges allowing your kindness to shine as a light that warms others while preserving your own flame in doing so you live in harmony with stoic ideals embodying a life of wisdom virtue and resilience let me ask you this are you ready to reclaim your time protect your energy and align your relationships with your values if so take the first step now like this post and share your thoughts below kindness with wisdom is power remember true strength lies not in giving endlessly but in Discerning where your kindness will truly Thrive number five you will be doubted kindness though often celebrated as one of Humanity’s greatest virtues can sometimes bring about unexpected challenges for those who practice it consistently and wholeheartedly while acts of generosity are generally appreciated when your kindness becomes frequent or seemingly excessive it may invite unwarranted skepticism people might question your motives suspecting that your actions are more strategic than sincere as if hidden agendas were driving your Goodwill for instance if you consistently assist a coworker with their tasks the quiet hum of office gossip might suggest you are seeking to Curry favor with your boss rather than simply extending a helping hand this type of Suspicion though often baseless has a way of straining relationships and unsettling your confidence over time the weight of being Mis understood or undervalued might even lead you to question the worth of your kindness causing you to suppress your natural inclination to do good modern stoicism however offers an empowering perspective to navigate these moments of doubt it encourages us to ground our actions in our principles and focus on the purity of our intent rather than the shifting perceptions of others Marcus aelius wisely noted waste no more time arguing about what a good man should be be one this Timeless reminder serves as a beacon guiding us to act according to our values regardless of how others interpret our actions if your kindness stems from a genuine place of virtue and integrity no amount of external doubt

    should deter you yes misunderstandings and skepticism are inevitable but your purpose is not to control control others opinions it is to remain steadfast in living as the person you strive to be the key to overcoming this challenge lies in unwavering consistency when your actions consistently reflect your values they create a pattern of sincerity that becomes impossible to ignore even those who doubt your motives initially may come to recognize the authenticity behind your Deeds As Time unfolds while you cannot expect to change every skeptical mind those who truly matter will eventually understand your intentions in the meantime it is essential to remember that others judgments are beyond your control as epicus wisely observed it is not what happens to you but how you react to it that matters holding on to this perspective allows you to maintain your integrity and peace of mind in the face of external doubts in today’s world where cynicism often overshadows Goodwill staying committed to kindness requires resilience and self-awareness your acts of generosity are not transactional they are a reflection of your character and values if others doubt your motives resist the temptation to retreat into bitterness or defensiveness instead treat these situations as opportunities to practice patience and self-discipline knowing that your worth is not tied to others perceptions modern stoicism reminds us that a life lived in harmony with our principles is its own reward by embracing this truth you free yourself from the weight of external validation and discover that the value of kindness when rooted in virtue far surpasses any Shadow of Doubt let this conviction anchor you for kindness is never wasted when it arises from a place of integrity and authenticity number six you may become dependent on others have you ever noticed how excessive kindness despite its good intentions can sometimes backfire leaving you feeling vulnerable or even disempowered one of the subtle dangers of being overly kind is falling into a cycle of dependency not just for practical support but for emotional validation when you consistently put others needs ahead of your own it can teach you often without realizing it to lean on their approval to feel worthy or valued imagine this have you ever delayed an important decision waiting for a friend or loved one to weigh in just so you could feel reassured while it might seem harmless at first over time this pattern can quietly erode your confidence making you doubt your own instincts and judgment it’s almost like handing over the control of your happiness to someone else only to feel a drift and unsure when that support disappears let me share a story that illustrates this Clara a woman admired for her boundless kindness was always there for her friends she was the one everyone could count on offering a listening ear solving problems and sacrificing her own needs to lift others up But as time went on Clara realized she had unknowingly become reliant on the feedback of her loved ones for every major decision in her life when her closest friend moved abroad Clara suddenly felt lost uncertain and unable to trust her own choices it was a harsh wakeup call she had spent so much time prioritizing others and seeking their input that she had forgotten how to stand on her own two feet Clara’s Journey back to self-reliance wasn’t easy it required uncomfortable periods of solitude self-reflection and rebuilding her trust in herself but through this process she uncovered a strength she hadn’t realized she possessed and she grew more resilient and self assured this is where stoicism comes in stoicism a philosophy rooted in self-mastery reminds us that our true worth and happiness come from within not from the everchanging opinions or actions of others when we become overly reliant on external validation we give others the power to dictate our inner peace this leaves us vulnerable not just to disappointment but also to manipulation or emotional instability when that validation is no longer available one of the most valuable stoic Secrets is learning to cultivate your inner strength and embrace solitude as a way to grow your resilience this doesn’t mean you shut others out or stop seeking connection instead it’s about building a strong Foundation of self- trust so that the support of others is a bonus not a necessity think about your own life are there times when you feel stuck unable to move forward without someone else’s input how often do you find yourself doubting your own decisions waiting for validation before taking a step these might be signs that it’s time to look Inward and build your Independence start small maybe today you make a decision any decision without consulting anyone else notice how it feels even if it’s uncomfortable at first over time as you practice trusting yourself you’ll find that your confidence grows and you’ll rely Less on external validation to feel grounded here’s the lesson kindness is a beautiful and necessary part of life but it must be balanced with self-reliance when you cultivate the ability to trust your own judgment and embrace the Stillness of solitude you strengthen not only your Independence but also your relationships instead of giving out of a place of neediness you give from a position of balance and Inner Strength this in turn allows you to live a life of Greater fulfillment and peace remember the key to a fulfilled life isn’t found in how much you give to others it’s found in how much you nurture your own resilience and Inner Strength so ask yourself are you ready to embrace this balance and reclaim control over your happiness number seven you will have unrealistic expectations one of the pitfalls of being overly kind is that it can lead to unrealistic expectations and this is a lesson many of us learn the hard way when you give generously of yourself your time your energy your support it’s natural to Hope even subconsciously that others will do the same in return after all doesn’t the world feel like it should operate on the principle of fairness but let me ask you how often does reality actually meet those hopes perhaps perhaps you’ve gone out of your way to help a friend during a difficult time only to find that when your own life took a turn for the worse they weren’t there to offer the same level of support that feeling of disappointment can sting and when it lingers it can even grow into resentment carrying that kind of emotional weight is exhausting and it’s here that modern stoicism offers us a Lifeline helping us realign our focus with what we can truly control our actions and reactions Marcus Aurelius one of the most revered stoic philosophers reminds us in his meditations you have power over your mind not outside events realize this and you will find strength this simple yet profound truth has the power to shift how we approach kindness by expecting others to reciprocate our generosity in the exact way we envision we hand over control of our emotional well-being to forces we cannot govern think about that for a moment do you really want your happiness your peace of mind to depend on whether others meet your expectations it’s a precarious position to be in and the burden can be heavy are you prepared to carry that weight or is it time to reexamine how and why you give in the first place the problem lies not in kindness itself but in the invisible strings we sometimes attach to it when we tie our happiness to how others respond to our generosity we create a recipe for frustration it’s like expecting a garden to bloom exactly the way you imagined forgetting that the soil the weather and the seeds all have their own will but what if you let go of that expectation entirely What If instead of giving with a silent hope for a return you gave simply because it aligns with your values senica another brilliant stoic thinker wisely observed he who is brave is free and isn’t it an act of courage to give without expecting anything back when you free yourself from the need for others to meet your standards you also free your emotions you can begin to accept people as they are in all their flaws and complexities rather than feeling disappointed when they don’t behave as you’d hoped this shift doesn’t just protect your peace it enhances your relationships making them more authentic and less transactional letting go of expectations is not an overnight process it’s a practice a mindset that requires patience and introspection it means confronting your own habits of mind and asking tough questions why do I give what am I hoping for in return am I aligning my actions with my values or am I seeking external validation every step you take toward answering these questions helps you cultivate a lighter Freer self modern stoicism teaches us that kindness should never be a transaction it should be an expression of who you are at your core a reflection of your character and your commitment to making the world a little brighter think of kindness as planting a seed you don’t plant it because you’re certain of a harvest or because you demand fruit from it you plant it because it’s an Act of Faith a way to contribute to the beauty and vitality Of The World Isn’t that reason enough when you Embrace this perspective you’ll find that the rewards of kindness come not from what others give you in return but from the quiet satisfaction of knowing you’ve acted in alignment with your values and here’s the beauty of it this approach not only nurtures your own peace of mind but it also creates healthier more meaningful relationships ask yourself are you ready to embrace this form of kindness can you see how it might transform not only your relationships but your own sense of inner peace modern stoicism reminds us that kindness is one of the purest forms of strength it’s not about what you gain it’s about who you become through the act of giving by shifting your focus from expectation to intention you can reclaim your emotional freedom and walk through life with a lighter heart and a stronger sense of purpose so the next time you give do it not because you’re waiting for something in return but because it’s a reflection of the person you choose to be can you imagine how much lighter your life could feel if you let go of those unrealistic expectations it’s worth considering isn’t it number eight you might develop harmful habits overextending yourself for others often feels Noble but it can quickly become a double-edged sword leading to stress and triggering harmful coping mechanisms when you constantly sacrifice your time energy and emotional reserves without prioritizing your well-being you create a dangerous imbalance in such states of exhaustion it’s easy to turn to Temporary Comforts like overeating binge watching TV excessive alcohol consumption or other self-destructive habits as a way to manage feelings of frustration and burnout these fleeting escapes May provide relief in the moment but they only mask the deeper issues never addressing their root causes instead they compound your challenges adding physical strain and emotional guilt to an already overwhelming situation stoicism with its core focus on moderation self-discipline and inner balance warns us against succumbing to such patterns of excess senica wisely noted it is not the man who has too little but the man who craves more that is poor chasing external distractions or temporary relief does not resolve the struggle within it amplifies it the key to Breaking Free from this cycle lies in taking a proactive approach rooted in stoic principles to confront stressors directly Begin by examining the sources of your stress is it a packed schedule that leaves no room for rest unrealistic expectations from yourself or others or perhaps the difficulty of setting boundaries which often comes with the fear of disappointing people but by identifying these triggers you can approach them with Clarity and reason taking intentional steps to address the actual problem rather than merely numbing its symptoms this deliberate confrontation requires courage and reflection but it is far more effective than avoidance stoicism also teaches us that self-care is not Indulgence it is wisdom as epicus remarked no man is free who is not master of himself this Mastery begins with cultivating habits that restore your energy and promote mental Clarity mindfulness is a powerful tool in this process by practicing mindfulness whether through meditation breathing exercises or simply taking time to notice the present moment you can anchor yourself in the here and now this helps you manage emotional overwhelm and maintain perspective preventing ing your emotions from hijacking your reason additionally creating space for restorative practices such as regular exercise journaling or spending time in nature allows you to recharge in a sustainable way building resilience against stress and reducing Reliance on unhealthy behaviors a balanced life is one of Harmony and stoicism consistently encourages us to avoid extremes when you Embrace balance in your actions you protect yourself from the chaos of overextension and the destructive Tendencies it Fosters for example learning to say no to excessive demands is not selfish it is an act of self-respect and self-preservation by doing so you cons serve the energy needed to focus on what truly matters and ensure that the kindness you offer others stems from a place of abundance not depete completion developing healthier habits aligned with reason and virtue not only safeguards your well-being but also strengthens your ability to navigate challenges effectively and with dignity these stoic Secrets remind us that life’s demands will always be present but how we respond determines our Peace of Mind balance is the essence of living meaningfully it Shields us from the chaos of harmful habits while imp empowering us to act with purpose ensuring that our kindness enriches both others and ourselves by prioritizing moderation and self-discipline we create a life that is steady and fulfilling a life where kindness becomes a strength rather than a burden if you’ve made it this far it’s clear that you value thoughtful reflection and the pursuit of balance in life let’s continue the conversation share your thoughts in the comments by say simply saying balance begins with boundaries together we’ll keep learning and growing through these powerful stoic principles stay tuned there’s more eye-opening content coming your way soon number nine your boundaries will be violated failing to establish and enforce boundaries in your acts of kindness often leads to others overstepping and disregarding your limits leaving you feeling overburdened and unappreciated when your time energy or values are ignored repeatedly you may find yourself in a cycle where your good will is taken for granted consider a coworker who continually adds tasks to your workload knowing you’ll always say yes while this might seem harmless initially overtime it Fosters a dynamic where your contributions are undervalued and your kindness is treated as an expectation rather than a choice these violations of boundaries not only deplete your emotional reserves but also lead to frustration and resentment as your efforts go unnoticed and unreciprocated senica the stoic philosopher aptly reminds us no person hands out their money to passes by but to how many do we hand out our lives we are tight-fisted with property and money yet think too little of what wasting time the one thing about which we should all be the toughest misers his words underscore the importance of valuing our own resources time and energy enough to safeguard them with boundaries in the philosophy of modern stoicism boundaries are seen as essential tools for living with intention and balance they are not walls to isolate yourself but Frameworks that allow your kindness to thrive without undermining your well-being setting clear limits ensures that your acts of generosity come from a place of genuine care rather than obligation creating healthier and more respectful relationships when you communicate your boundaries assertively whether by declining extra work or addressing a pattern of overreach in a relationship you teach others to respect you while preserving your emotional and physical health this act of self-respect also aligns with the stoic principle of living in accordance with nature as maintaining balance in our interactions is critical to a harmonious life in today’s world where demands on our time and energy are seemingly endless boundary setting becomes even more vital without boundaries you risk burnout and discontent as others May unknowingly exploit your generosity to prevent this practice the art of saying no when needed and follow through with consistent action when your limits are crossed for instance if a colleague continues to assign you tasks without your consent it is perfectly reasonable to redirect the work back to them or involve a supervisor to establish Clarity by doing so you protect your time and energy ensuring your kindness is appreciated rather than exploited through these measures you are uphold the stoic ideal of moderation transforming your kindness from a source of stress into a meaningful expression of Good Will kindness without boundaries is unsustainable both for you and those you aim to help by defining and enforcing limits you preserve the value of your generosity ensuring it uplifts rather than depletes you modern stoicism teaches us that living with purpose and mindfulness is key to maintaining Harmony in our lives protecting your boundaries allows you to act with intention offering kindness where it matters most and fostering relationships built on mutual respect in doing so you embody the wisdom of the stoics cultivating a life that balances compassion with self-respect a balance that not only benefits you but also enriches the lives of those around you the ways kindness can ruin your life reveal an important truth even positive traits can become burdensome if not carefully managed and applied correctly kindness itself isn’t wrong but when it’s abused it can lead to losing your sense of self setting unrealistic expectations and breaking personal boundaries to avoid falling into this negative cycle understanding the risks and knowing how to manage them is key five stoic strategies to stop being taken advantage of while kindness can have unintended consequences this doesn’t mean you need to abandon it instead you can apply stoic strategies to maintain kindness in a balanced and empowering way helping you protect yourself from being taken advantage of while staying true to your values keep watching to discover how stoicism can help you stay kind when without being exploited and transform your kindness into an unshakable source of Power number one understand your emotions understanding your emotions is the Cornerstone of stoic philosophy and a vital tool for preventing the emotional burnout that often stems from unchecked kindness when you give endlessly without considering your emotional capacity feelings of frustration exhaustion or even resentment can creep in and quietly take hold these emotions may seem insignificant at first but they tend to accumulate emerging later as irritability stress or a sense of being unappreciated imagine helping a friend over and over again offering rides lending a hand with projects or being their emotional support system only to feel overlooked when they don’t acknowledge your efforts that unspoken disappointment can morph into resentment souring not only your relationship with them but also your own emotional well-being stoicism with its Timeless wisdom encourages us to observe our emotions not as enemies to be suppressed but as signals guiding us toward balance the stoic Secrets teach us to approach our feelings with curiosity identifying their roots and understanding understanding their triggers for instance when you notice yourself feeling drained after yet another act of kindness pause and ask what’s behind this feeling am I giving too much too often without ensuring my own needs are met this self-awareness allows you to recognize when your boundaries are being stretched too thin giving you the power to recalibrate your actions before they lead to burnout it’s not about withdrawing your kindness it’s about offering it in ways that are genuine sustainable and aligned with your own emotional health one powerful strategy for cultivating this balance is regular self-reflection carve out time each day even just a few minutes to ask yourself questions like how do I feel after helping others or am I sacrificing my well-being for the sake of being seen as kind consider a modern example a co-worker who frequently asks you to cover their shifts or pick up their slack you comply fearing conflict or wanting to maintain a helpful image but over time you start to dread their requests and feel resentment building if you reflect on your emotions and acknowledge this pattern you can prepare yourself to set boundaries perhaps by saying I’d love to help but I can’t this time this small Act of assertion not only protects your energy but also reshapes the dynamic into one of mutual respect here’s an important truth to internalize understanding your emotions and setting limits isn’t selfish it’s essential if you’re running on empty how can you continue to give authentically the stoic approach to kindness isn’t about closing off your heart it’s about ensuring that your kindness flows from a place of strength and intention when you acknowledge and respect your emotions you create a healthier foundation for your relationships and preserve your capacity to give in meaningful ways let me ask you this how often do you find yourself feeling stretched too thin yet reluctant to say anything for fear of being seen as unkind could tuning into your emotions and adjusting your actions make a difference remember stoicism reminds us that a life lived with self-awareness is a life lived with purpose by embracing this principle you can transform your kindness into something that uplifts both you and those around you the next time you feel your generosity tipping into exhaustion take a step back and reflect is this kindness depleting you or is it rooted in genuine care when you find that balance you you’ll discover that your acts of kindness become not only more impactful but also deeply fulfilling for both you and the people in your life number two learn to say no let’s talk about one of the hardest but most liberating words you can ever learn to say no it seems simple doesn’t it but for so many of us saying no feels like a betrayal of kindness we worry about letting people down being seen as selfish or even facing rejection so we keep saying yes yes to the extra project at work even when your plate is already full yes to helping a friend move even when your own weekend is packed with plans at first it feels good to help like you’re being dependable and kind but then the weight of overc commitment sets in you feel overwhelmed stressed maybe even resentful and here’s the kicker the more you say yes when you really mean no the more you teach others to take your time and energy for granted have you ever stopped to ask yourself how much of my life am I giving away and at what cost to myself this is where Modern stoicism offers a Lifeline the stoics masters of wisdom and discipline understood the value of setting boundaries they knew that saying no is not an act of Cruelty it’s an act of self-respect Marcus Aurelius wrote it is not death that a man should fear but he should fear never beginning to live by overcommit and prioritizing everyone else’s needs above your own you risk losing the time and energy needed to live a life aligned with your values modern stoicism reminds us that we can only be truly kind when our action come from a place of strength not obligation learning to say no is one of the most powerful ways to protect your well-being when you decline a request that doesn’t align with your priorities you’re not just setting a boundary you’re reclaiming control over your life think of it this way every time you say yes to something you’re also saying no to something else often something that matters more to you how often are you sacrificing your own goals peace of mind or even your health just to avoid the discomfort of a no epic tetus reminds us he who is not master of himself is a slave are you a master of your time or are you letting fear of disapproval dictate your choices start small practice saying no to minor requests that don’t serve your priorities use polite but firm language like I’d love to help but I’m fully committed right now notice how empowering it feels to draw a line and stand by it over time this builds confidence and reinforces your boundaries it’s not about being selfish it’s about ensuring your kindness remains genuine and balanced when you protect your own time and energy the help you offer others comes from a place of abundance not exhaustion remember remember people who truly value you will respect your boundaries and those who don’t they likely never valued you only what you could do for them saying no isn’t rejection it’s an affirmation of your priorities and your Worth Modern stoicism teaches us that discipline and self-respect are key to living a fulfilling life so ask yourself what kind of Life am I building if I never Never Say No by learning to decline what doesn’t serve you you open the door to a life that truly does after all how can you live authentically if you’re always living for others number three dedicate time to yourself dedicating time to yourself is not an act of selfishness it is a fundamental pillar of emotional and mental well-being in a society that often confuses worth with constant availability self-care can easily feel like an Indulgence instead of a necessity however the truth is that endlessly prioritizing others whether by helping friends with their projects or giving up weekends for everyone else’s needs inevitably leads to neglecting your own this imbalance may not be noticeable at first but over time it breeds burnout dissatisfaction and even resentment senica’s Timeless wisdom reminds us it is not that we have a short time to live but that we waste a lot of it his words are a call to action urging us to use our time deliberately and to recognize that self-care is not a luxury but an essential practice for leading a balanced and meaningful life stoicism teaches that true strength and productivity arise from self-mastery and this Mastery is only possible when we make time for reflection renewal and personal growth taking time for yourself might involve physical activities like exercising mental enrichment through reading or learning or simply finding moments of peace to let your mind rest these practices are not escapes from your responsibilities they are the very Foundation that equips you to face life’s demands with Clarity and vigor the stoic secret to thriving lies in treating self-care as a non-negotiable commitment without it you risk depleting the energy you need to effectively support others and to pursue your own aspirations to make self-care a sustainable habit Begin by intentionally scheduling regular time for yourself and treating it as sacred whether it’s an hour in the morning to meditate an evening to journal or a week can to immerse yourself in a hobby this time should be viewed as non-negotiable just as you would not cancel a crucial meeting or family obligation respect these commitments to yourself set clear boundaries with those around you and don’t hesitate to say no when interruptions arise dedicating time to yourself is not about withdrawing from others but rather about fortifying your ability to connect with and care for them more effectively when you nurture your own well-being you create a foundation of strength and Clarity that benefits not only you but also those who rely on you this is an act of profound self-respect and a demonstration of the stoic principle of balance by prioritizing self-care you ensure that your kindness and efforts for others stem from a place of abundance rather than exhaustion taking care of yourself is the Cornerstone of a life lived with Clarity purpose and resilience by carving out time for your well-being you align with the stoic ideal of purposeful living ensuring that your energy is used wisely and your actions reflect your values this practice not only empowers you to thrive but also enriches your ability to contribute meaningfully to the lives of others your well-being is not just a gift to yourself it is the foundation from which all other aspects of your life can flourish if you’ve ever struggled with the guilt of taking time for yourself or felt drained from constantly prioritizing others share your resolve by commenting I honor my well-being below your commitment to self-care can Inspire others to recognize the importance of nurturing their own strength and living a life of balance and purpose let’s support each other in building lives rooted in clarity resilience and the stoic principle of balance number four set clear goals setting clear goals is essential for creating Direction in life giving you a sense of purpose and helping you focus on what truly matters without defined objectives it’s easy to be pulled in countless directions by the demands and expectations of others leaving you feeling aimless and unfulfilled imagine committing to a professional growth plan such as completing a certification course only to find your time consumed by favors and distractions that have no connection to your aspirations this scenario underscores the importance of clarity in your goals as they act like a compass guiding your actions toward meaningful progress sener a stoic philosopher wisely stated if one does not know to which Port one is sailing no wind is favorable this Timeless wisdom highlights how essential it is to know your destination both in life and in your daily actions to avoid being Swept Away by distractions modern stoicism teaches us the value of purposeful living emphasizing the importance of aligning your actions with your values and long-term aspirations setting goals is not just about productivity it is about ensuring that your time and energy are directed toward Pursuits that enrich your personal growth and contribute to your sense of fulfillment by having a Clear Vision of what you want to achieve you Empower yourself to make intentional decisions that serve your best interests rather than succumbing to external pressures or fleeting demands this Focus not only strengthens your resolve but also preserves your mental and emotional well-being as you no longer feel burdened by obligations that pull you away from your true priorities to make this principle actionable start by identifying your priorities and breaking them into smaller manageable steps for example if your goal is to enhance your career outline specific tasks such as researching programs enrolling in courses and dedicating time each week to study regularly revisit your goals to measure your progress and make adjustments as needed ensuring they remain relevant and achievable additionally clearly communicate your objectives to those around you helping them understand why your time and energy are dedicated to specific Pursuits this transparency not only reinforces your commitment to your goals but also teaches others to respect your boundaries and the importance of your aspirations in Modern Life where distractions are constant and time feels increasingly scarce having clear goals is more critical than ever without them it becomes easy to say yes to every request leaving little room for personal growth or meaningful achievement by consciously prioritizing your objectives and asserting your boundaries you not only Safeguard your progress but also Inspire others to do the same modern stoicism M encourages this disciplined approach showing us that living with purpose and Clarity leads to a more harmonious and fulfilling life when you align your actions with your goals you cultivate a mindset of intentionality turning every decision into a step toward a life of meaning and balance number five distance yourself from energy drainers distancing yourself from energy drainers those who constantly take from you without giving anything in return is one of the most important steps you can take to safeguard your emotional and mental health we’ve all encountered these people maybe it’s the coworker who always has a crisis but never listens when you share your struggles or a friend who endlessly leans on you for support yet is never available when you need a shoulder these individuals don’t intentionally set out to harm you but they’re relentless less negativity and one-sided needs leave you feeling exhausted undervalued and emotionally drained over time this imbalance can chip away at your well-being making you question why you’re always left Running on Empty while they seem to take and take without giving back stoicism offers Timeless wisdom for navigating these relationships one of its stoic Secrets is the principle of discernment carefully choosing who you invest your time and energy in the stoics teach that our peace of mind is precious and should be fiercely protected to do this you must first recognize the signs of an energy drainer do you feel consistently depleted after interacting with someone do their demands feel excessive or their negativity overwhelming if the answer is yes it might be time to re-evaluate that relationship take a modern example a colleague who always vents about their workload and demands your help with their tasks but never reciprocates when you’re under pressure by continuing to indulge them you not only reinforce the behavior but also neglect your own priorities and emotional balance creating distance doesn’t mean shutting people out cruy it means setting healthy boundaries start by limiting how often and How Deeply you engage with energy drainers if they they constantly ask for favors politely decline when their requests feel excessive redirect the conversation or gently remind them that you have your own responsibilities to focus on at the same time make a conscious effort to surround yourself with positive supportive individuals those who Inspire and encourage you a friend who listens as much as they talk or a colleague who collaborates and shares the workload can have an incredible impact on your sense of balance and fulfillment these are the relationships that build emotional resilience and promote personal growth let me ask you how often do you find yourself saying yes to someone even when it feels like too much how does that leave you feeling afterward recognizing and addressing these Dynamics can transform your relationships and protect your mental health remember stoicism isn’t about avoiding all challenges or cutting off everyone who frustrates you it’s about focusing your energy on what truly matters and what aligns with your values when you let go of negativity you create space for relationships that are uplifting and enriching where kindness and support flow both ways so the next time you find yourself faced with an energy drainer pause and reflect is this connection nurturing you or draining you is it time to step back and reclaim Your Peace by putting the stoic principle of discernment into practice you’ll discover that your kindness and energy are most valuable when shared with those who truly appreciate and respect them protect your peace of mind and you’ll cultivate a life filled with balance growth and meaningful connections as we wrap up let’s refle on the key takeaway kindness is a powerful and admirable trait but without boundaries it can lead to burnout frustration and a loss of self-respect by applying the Timeless strategies of modern stoicism like self-awareness clear goal setting and nurturing healthy relationships you can Safeguard your priorities while still fostering meaningful connections the wisdom of the stoics teaches us that true kindness begins with respect for yourself and when you live in alignment with your values you can give to others in a way that’s both genuine and sustainable now it’s time to take action how will you apply these stoic secrets to your own life are there areas where you need to set better boundaries or say no to protect your well-being I’d love to hear your thoughts share your experiences in the comments below and if if you found value in today’s video don’t forget to like subscribe to stoic secrets and hit the Bell icon for more insights into stoicism and personal growth together let’s continue this journey toward a balanced and fulfilling life Guided by the wisdom of the stoics

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog