<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Abdelmajid E.</title>
    <description>The latest articles on DEV Community by Abdelmajid E. (@elayachiabdelmajid).</description>
    <link>https://dev.to/elayachiabdelmajid</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F850950%2F4d96f3ff-90dc-44bf-a122-1e4067df0fed.jpg</url>
      <title>DEV Community: Abdelmajid E.</title>
      <link>https://dev.to/elayachiabdelmajid</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/elayachiabdelmajid"/>
    <language>en</language>
    <item>
      <title>Design Pattern : difference between composition and inheritance and decorator.</title>
      <dc:creator>Abdelmajid E.</dc:creator>
      <pubDate>Fri, 04 Oct 2024 13:25:07 +0000</pubDate>
      <link>https://dev.to/elayachiabdelmajid/design-pattern-difference-between-composition-and-inheritance-and-decorator-mji</link>
      <guid>https://dev.to/elayachiabdelmajid/design-pattern-difference-between-composition-and-inheritance-and-decorator-mji</guid>
      <description>&lt;p&gt;To Understand the difference between these three design pattern, first we need to understand each one of them:&lt;/p&gt;

&lt;h2&gt;
  
  
  Inheritance
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;What is Inheritance?&lt;/p&gt;

&lt;p&gt;Inheritance is one of the object-oriented programming concepts in Java. Inheritance enables the acquisition of data members and properties from one class to another.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Base Class (Parent Class)&lt;br&gt;
The base class provides the data members and methods in alternative words. Any base class that needs methods or data members will have to borrow them from their respective parent or base class.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Subclass (Child Class)&lt;br&gt;
The subclass is also known as the child class. The implementation of its parent class recreates a new class, which is the child class. &lt;/p&gt;

&lt;p&gt;To inherit the parent class, a child class must include a keyword called "extends." The keyword "extends" enables the compiler to understand that the child class derives the functionalities and members of its parent class.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Why Do We Need Inheritance?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We need use Inheritance for two main reason:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Run-Time Polymorphism&lt;br&gt;
Runtime, also known as dynamic polymorphism, is a method call in the execution process that overrides a different method in the run time.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Code Reusability &lt;br&gt;
The process of inheritance involves reusing the methods and data members defined in the parent class. Inheritance eliminates the need to write the same code in the child class—saving time as a result.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Example
here is the class diagram:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0s232ei132igcn9n3p5w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0s232ei132igcn9n3p5w.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package org.designpattern;

public class Main {
    public static void main(String[] args) {
        // Create an array of Shape objects
        Shape[] shapes = new Shape[3];
        shapes[0] = new Circle("Red", 5);
        shapes[1] = new Rectangle("Blue", 4, 6);
        shapes[2] = new Circle("Green", 3);

        // Iterate through the shapes and demonstrate polymorphism
        for (Shape shape : shapes) {
            shape.displayColor();
            System.out.println("Area: " + shape.calculateArea());

            // Demonstrate instanceof and casting
            if (shape instanceof Circle) {
                System.out.println("This is a circle");
            } else if (shape instanceof Rectangle) {
                System.out.println("This is a rectangle");
            }

            System.out.println(); // For readability
        }
    }
}

/** Parent class
 * this class should have at least one abstract method (in this cas it is calculateArea())
 **/
abstract class Shape {
    protected String color;

    public Shape(String color) {
        this.color = color;
    }

    // abstract method
    public abstract double calculateArea();

    public void displayColor() {
        System.out.println("This shape is " + color);
    }
}

// Child class Circle
class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    @Override
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

// Child class Rectangle
class Rectangle extends Shape {
    private double length;
    private double width;

    public Rectangle(String color, double length, double width) {
        super(color);
        this.length = length;
        this.width = width;
    }

    @Override
    public double calculateArea() {
        return length * width;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have a class abstract which is the parent (in another base class) (NB: this class should have at least one method abstract).&lt;/p&gt;

&lt;h2&gt;
  
  
  What is composition
&lt;/h2&gt;

&lt;p&gt;Composition in java is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition in java for code reuse.&lt;br&gt;
     Java composition is achieved by using instance variables that refers to other objects. For example, a House has a Room. Let’s see this with a java composition example code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.ArrayList;
import java.util.List;

class House {
    private List&amp;lt;Room&amp;gt; rooms;

    public House() {
        this.rooms = new ArrayList&amp;lt;&amp;gt;();
    }

    public void addRoom(String name, long width, long length, long height) {
        Room room = new Room(name, width, length, height);
        rooms.add(room);
    }

    public List&amp;lt;Room&amp;gt; getRooms() {
        return rooms;
    }

    public void printHouseDetails() {
        for (Room room : rooms) {
            System.out.println("Room: " + room.getName());
            System.out.println("Dimensions (WxLxH): " + room.getWidth() + " x " + room.getLength() + " x " + room.getHeight());
            System.out.println();
        }
    }

}

class Room {
    private String name;
    private long width;
    private long length;
    private long height;

    public Room(String name, long width, long length, long height) {
        this.name = name;
        this.width = width;
        this.length = length;
        this.height = height;
    }

    public String getName() {
        return name;
    }

    public long getWidth() {
        return width;
    }

    public long getLength() {
        return length;
    }

    public long getHeight() {
        return height;
    }

}

public class Composition {
    public static void main(String[] args) {
        House house = new House();
        house.addRoom("Living Room", 500, 600, 300);
        house.addRoom("Bedroom", 400, 500, 300);
        house.addRoom("Kitchen", 300, 400, 300);

        house.printHouseDetails();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why do we need Composition
&lt;/h2&gt;

&lt;p&gt;Notice that above test program for composition in java is not affected by any change in the Room object. If you are looking for code reuse and the relationship between two classes is has-a then you should use composition rather than inheritance. Benefit of using composition in java is that we can control the visibility of other object to client classes and reuse only what we need. Also if there is any change in the other class implementation, for example getRooms returning list of Room, we need to change House class to accommodate it but client classes doesn’t need to change. Composition allows creation of back-end class when it’s needed.&lt;/p&gt;

&lt;h3&gt;
  
  
  types of composition:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;One to One&lt;/strong&gt;:&lt;br&gt;
In a one-to-one composition, one object is composed of exactly one instance of another object. This implies a strong relationship where the composed object is a crucial part of the composing object.&lt;/p&gt;

&lt;p&gt;Example: A Person and their Heart. Each person has exactly one heart, and the heart cannot exist independently of the person.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Person {
    private Heart heart;

    public Person() {
        this.heart = new Heart();
    }

    // getters and other methods
}

class Heart {
    // Heart properties and methods
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;One to Many&lt;/strong&gt;:&lt;br&gt;
In a one-to-many composition, one object is composed of multiple instances of another object. The composed objects are part of the lifecycle of the composing object.&lt;/p&gt;

&lt;p&gt;Example: A Library and Books. A library contains many books, but those books are part of the library's collection.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.ArrayList;
import java.util.List;

class Library {
    private List&amp;lt;Book&amp;gt; books;

    public Library() {
        this.books = new ArrayList&amp;lt;&amp;gt;();
    }

    public void addBook(Book book) {
        books.add(book);
    }

    // getters and other methods
}

class Book {
    private String title;

    public Book(String title) {
        this.title = title;
    }

    // getters and other methods
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Many to One&lt;/strong&gt;:&lt;br&gt;
In a many-to-one composition, multiple objects are composed within one instance of another object. This often implies that the composed object has a shared dependency on a single instance of the other object.&lt;/p&gt;

&lt;p&gt;Example: Several Employees working in a single Company. Each employee works for one company, and the company manages all its employees.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.ArrayList;
import java.util.List;

class Company {
    private List&amp;lt;Employee&amp;gt; employees;

    public Company() {
        this.employees = new ArrayList&amp;lt;&amp;gt;();
    }

    public void addEmployee(Employee employee) {
        employees.add(employee);
    }

    // getters and other methods
}

class Employee {
    private String name;

    public Employee(String name) {
        this.name = name;
    }

    // getters and other methods
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What is decorator
&lt;/h2&gt;

&lt;p&gt;The decorator design pattern allows us to dynamically add functionality and behavior to an object without affecting the behavior of other existing objects in the same class. &lt;/p&gt;

&lt;p&gt;We use inheritance or composition to extend the behavior of an object but this is done at compile time and its applicable to all the instances of the class. We can’t add any new functionality of remove any existing behavior at runtime - this is when Decorator pattern comes into picture. Suppose we want to implement different kinds of cars - we can create interface Car to define the assemble method and then we can have a Basic car, further more we can extend it to Sports car and Luxury Car. The implementation hierarchy will look like below image.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1wsmybir2yod88isyep2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1wsmybir2yod88isyep2.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Step 1: Define the Car interface
interface Car {
    void assemble();
}

// Step 2: Create a basic implementation of Car
class BasicCar implements Car {
    @Override
    public void assemble() {
        System.out.print("Basic Car.");
    }
}

// Step 3: Create the CarDecorator class implementing the Car interface
class CarDecorator implements Car {
    protected Car car;

    public CarDecorator(Car car) {
        this.car = car;
    }

    @Override
    public void assemble() {
        this.car.assemble();  // Delegates the call to the wrapped car object
    }
}

// Step 4: Create specific decorators by extending CarDecorator
class SportsCar extends CarDecorator {

    public SportsCar(Car car) {
        super(car);
    }

    @Override
    public void assemble() {
        super.assemble();
        System.out.print(" Adding features of a Sports Car.");
    }
}

class LuxuryCar extends CarDecorator {

    public LuxuryCar(Car car) {
        super(car);
    }

    @Override
    public void assemble() {
        super.assemble();
        System.out.print(" Adding features of a Luxury Car.");
    }
}

// Step 5: Demonstrate the usage of the Decorator Pattern
public class DecoratorPatternTest {
    public static void main(String[] args) {
        Car sportsCar = new SportsCar(new BasicCar());
        sportsCar.assemble();
        System.out.println("\n-----");

        Car luxuryCar = new LuxuryCar(new BasicCar());
        luxuryCar.assemble();
        System.out.println("\n-----");

        Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar()));
        sportsLuxuryCar.assemble();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Basic Car. Adding features of a Sports Car.
Basic Car. Adding features of a Luxury Car.
Basic Car. Adding features of a Luxury Car. Adding features of a Sports Car.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion:
&lt;/h3&gt;

&lt;p&gt;To understand the differences between &lt;strong&gt;inheritance&lt;/strong&gt;, &lt;strong&gt;composition&lt;/strong&gt;, and &lt;strong&gt;decorator design patterns&lt;/strong&gt;, it’s important to grasp each concept individually:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Inheritance&lt;/strong&gt; is used for an "is-a" relationship where classes inherit methods and properties from a parent class. It promotes &lt;strong&gt;code reusability&lt;/strong&gt; and &lt;strong&gt;run-time polymorphism&lt;/strong&gt; but can lead to rigid class hierarchies.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Composition&lt;/strong&gt; implements a "has-a" relationship and is favored for &lt;strong&gt;code reuse&lt;/strong&gt; where objects are composed of other objects. It offers more flexibility and avoids the tight coupling seen in inheritance. Composition allows objects to contain other objects, fostering easier maintenance and flexibility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Decorator Pattern&lt;/strong&gt; is a structural pattern that allows behavior to be added dynamically to an object at runtime without affecting other objects. Unlike inheritance, which happens at compile-time, decorators provide a flexible alternative, allowing functionalities to be composed as needed.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each pattern addresses different use cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use &lt;strong&gt;inheritance&lt;/strong&gt; when objects share a clear hierarchical relationship.&lt;/li&gt;
&lt;li&gt;Use &lt;strong&gt;composition&lt;/strong&gt; for flexibility when creating complex objects.&lt;/li&gt;
&lt;li&gt;Use &lt;strong&gt;decorators&lt;/strong&gt; when you need to add functionality dynamically at runtime, without modifying existing class structures.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>java</category>
      <category>webdev</category>
      <category>designpatterns</category>
      <category>oop</category>
    </item>
    <item>
      <title>Java 21: The Magic Behind Virtual Threads</title>
      <dc:creator>Abdelmajid E.</dc:creator>
      <pubDate>Wed, 29 May 2024 12:37:58 +0000</pubDate>
      <link>https://dev.to/elayachiabdelmajid/java-21-virtual-threads-1h5b</link>
      <guid>https://dev.to/elayachiabdelmajid/java-21-virtual-threads-1h5b</guid>
      <description>&lt;p&gt;To understand virtual threads very well, we need to know how Java threads work.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Quick Introduction to Java Threads (Platform Threads) and How They Work&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;First, let's review the relationship between the threads we've been creating (Java threads) and the OS threads. Whenever we create an object of type Thread, that object, among other things, contains the code that needs to execute and the start method. When we run that start method, we ask the OS to create and start a new OS thread belonging to our application's process, and ask the JVM to allocate a fixed-size stack space to store the thread's local variables from that point on. The OS is fully responsible for scheduling and running the thread on the CPU, just like any other thread.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhehr9patf202mph4kc79.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhehr9patf202mph4kc79.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, in a sense, that Thread object inside the JVM is just a thin layer or wrapper around an OS thread.&lt;/p&gt;

&lt;p&gt;From now on, we're going to call this type of Java thread a platform thread. As we've already seen, those platform threads are expensive and heavy, because each platform thread maps 1-to-1 to an OS thread, which is a limited resource, and it is also tied to a static stack space within the JVM.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe4wqqqjjt6bke0qce0wd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe4wqqqjjt6bke0qce0wd.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Introduction to Virtual Threads&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Virtual threads are a relatively newer type of thread that has been introduced as part of &lt;strong&gt;JDK 19&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Like platform threads, virtual threads contain, among other things, the code we want to execute concurrently, and the start method. However, unlike a platform thread, a virtual thread fully belongs and is managed by the JVM and does not come with a fixed-size stack.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb61bckdqhv7hnejw15vu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb61bckdqhv7hnejw15vu.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The OS takes no role in creating or managing it and is not even aware of it. In fact, a virtual thread is just like any Java object allocated on the heap and can be reclaimed by the JVM's garbage collection when it is no longer needed. The consequence of those facts is that unlike platform threads, which are very expensive to create and heavy to manage, virtual threads are very cheap and fast to create in large quantities.&lt;/p&gt;

&lt;p&gt;Now, a good question you may ask at this point is: if virtual threads are just Java objects, how do they actually run on the CPU?&lt;/p&gt;

&lt;p&gt;The answer is, as soon as we create at least one virtual thread, under the hood, the JVM creates a relatively small internal pool of platform threads. Whenever the JVM wants to run a particular virtual thread, for example, thread A, it mounts it on one of the platform threads within its pool.&lt;/p&gt;

&lt;p&gt;When a virtual thread is mounted on a platform thread, that platform thread is called a carrier thread. If the virtual thread finishes its execution, the JVM will unmount that thread from its carrier and make that platform thread available for other virtual threads. That virtual thread object now becomes garbage, which the garbage collection can clean up at any time. However, in certain situations, if thread A has not finished but is unable to make any progress at that time, the JVM will unmount it but save its current state on the heap.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Famcnwbuc5c52q224axge.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Famcnwbuc5c52q224axge.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It's worth pointing out that we as developers have very little control over the carrier threads and the scheduling of the virtual threads on them. It is something that the JVM manages for us under the hood.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Quick Demo&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For demonstration purposes, we will create a Java thread to see the difference between a virtual thread and a platform thread.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Platform Thread (Java Thread)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Inside your IDE, create a class with a main method, like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ThreadDemo&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Thread&lt;/span&gt; &lt;span class="n"&gt;thread&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Thread: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;currentThread&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="o"&gt;});&lt;/span&gt;
        &lt;span class="n"&gt;thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;start&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So, let's create a virtual thread:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VirtualThreadDemo&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;startVirtualThread&lt;/span&gt;&lt;span class="o"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Virtual Thread: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;currentThread&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="o"&gt;});&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see when we run the program, the first thing we notice is the object we printed is of type VirtualThread, then we see that its ID is 24, and the name is "ForkJoinPool.commonPool-worker-1". This tells us a few things. First, it tells us that to schedule this and any future virtual threads, the JVM created an internal thread pool of platform threads, which is called ForkJoinPool.commonPool, and then the JVM mounted our virtual thread on one of those worker threads, which is called worker-1.&lt;/p&gt;

&lt;p&gt;To make this easier to understand, let's create another virtual thread:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VirtualThreadDemo&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;startVirtualThread&lt;/span&gt;&lt;span class="o"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Virtual Thread 1: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;currentThread&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="o"&gt;});&lt;/span&gt;
        &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;startVirtualThread&lt;/span&gt;&lt;span class="o"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Virtual Thread 2: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;currentThread&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="o"&gt;});&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see, we have two virtual threads, their IDs are 24 and 25, respectively. They ran on the same pool of carrier threads, which is called ForkJoinPool.commonPool, but because we ran them concurrently, each one was mounted on a different worker thread to be its carrier. The first one was mounted on worker-1, and the second on worker-2.&lt;/p&gt;

&lt;p&gt;Now, to see the relationship between the number of virtual threads and the number of platform threads within that ForkJoinPool, let's increase the number of virtual threads from 2 to 20:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VirtualThreadDemo&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;startVirtualThread&lt;/span&gt;&lt;span class="o"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Virtual Thread "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;": "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;currentThread&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
            &lt;span class="o"&gt;});&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see on the screen, we indeed created 20 new virtual threads, each with its own unique ID. However, based on their names, we can see that the JVM dynamically decided to create a pool of seven platform threads to be their carriers, and all those virtual threads were scheduled to run on this small pool of threads.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hope this blog is helpful to you, and I hope you enjoy it.&lt;/p&gt;

</description>
      <category>java</category>
      <category>multitheading</category>
      <category>virtualthread</category>
      <category>javathread</category>
    </item>
    <item>
      <title>Setup Laravel 9 with JWT-Authentification</title>
      <dc:creator>Abdelmajid E.</dc:creator>
      <pubDate>Fri, 01 Jul 2022 12:23:54 +0000</pubDate>
      <link>https://dev.to/elayachiabdelmajid/setup-laravel-9-with-jwt-authentification-2hb1</link>
      <guid>https://dev.to/elayachiabdelmajid/setup-laravel-9-with-jwt-authentification-2hb1</guid>
      <description>&lt;p&gt;Are you looking to start building a project with backend laravel and send API requests using Rest API here is a good tutorial.&lt;/p&gt;

&lt;p&gt;In this tutorial, I will build a simple backend project with laravel and Tymon JWT-auth.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setup a Laravel Project using Composer&lt;/strong&gt;&lt;br&gt;
There are a few options when it comes to installing Laravel. We will be using Composer to setup the Laravel framework.&lt;/p&gt;

&lt;p&gt;For this you will need to install the following:&lt;/p&gt;

&lt;p&gt;Composer&lt;br&gt;
Node&lt;br&gt;
And for development, you will be needing PHP 8.&lt;/p&gt;

&lt;p&gt;After installing all of this, we can simply run the following command to scaffold a complete Laravel project:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;composer create-project Laravel/laravel laravel-jwt-rest-api&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setup a .env file database connexion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, create a database by the same name of the project "laravel-jwt-rest-api", add connexion to .env file:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_jwt_rest_api
DB_USERNAME=root
DB_PASSWORD=


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, Let's Install JWT Auth&lt;br&gt;
&lt;code&gt;composer require tymon/jwt-auth --ignore-platform-reqs&lt;/code&gt;&lt;br&gt;
And you need to install laravel to generate jwt encryption keys. This command will create the encryption keys needed to generate secure access tokens:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;php artisan jwt:secret&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;After successfully install laravel jwt, register providers. Open config/app.php . and put the bellow code :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

'providers' =&amp;gt; [
….
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],
'aliases' =&amp;gt; [
….
'JWTAuth' =&amp;gt; 'Tymon\JWTAuth\Facades\JWTAuth',
'JWTFactory' =&amp;gt; 'Tymon\JWTAuth\Facades\JWTFactory',
],


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;JWT auth package comes up with middlewares that we can use. Register auth.jwt middleware in &lt;/p&gt;

&lt;p&gt;app/Http/Kernel.php&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

protected $routeMiddleware = [
        'auth' =&amp;gt; \App\Http\Middleware\Authenticate::class,
        'auth.basic' =&amp;gt; \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' =&amp;gt; \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' =&amp;gt; \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' =&amp;gt; \Illuminate\Auth\Middleware\Authorize::class,
        'guest' =&amp;gt; \App\Http\Middleware\RedirectIfAuthenticated::class,
        'jwtAuth' =&amp;gt; \App\Http\Middleware\JWTMiddleware::class,
        'password.confirm' =&amp;gt; \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' =&amp;gt; \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' =&amp;gt; \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' =&amp;gt; \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we need to modify User model. Open App/Models/User.php file and implement Tymon\JWTAuth\Contracts\JWTSubject interface. We also need to add two model methods getJWTIdentifier() and getJWTCustomClaims().&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable;

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this-&amp;gt;getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, the default authentication guard is web. We need to change it to api. Open config/auth.php file and change default guard to api.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

return [


    'defaults' =&amp;gt; [
        'guard' =&amp;gt; 'api',
        'passwords' =&amp;gt; 'users',
    ],


    'guards' =&amp;gt; [
        'web' =&amp;gt; [
            'driver' =&amp;gt; 'session',
            'provider' =&amp;gt; 'users',
        ],
        'api' =&amp;gt; [
            'driver' =&amp;gt; 'jwt',
            'provider' =&amp;gt; 'users',
            'hash'=&amp;gt;false,
        ],
    ],

    'providers' =&amp;gt; [
        'users' =&amp;gt; [
            'driver' =&amp;gt; 'eloquent',
            'model' =&amp;gt; App\Models\User::class,
        ],
    ],


    'passwords' =&amp;gt; [
        'users' =&amp;gt; [
            'provider' =&amp;gt; 'users',
            'table' =&amp;gt; 'password_resets',
            'expire' =&amp;gt; 60,
            'throttle' =&amp;gt; 60,
        ],
    ],


    'password_timeout' =&amp;gt; 10800,

];




&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Add Authentication routes
&lt;/h2&gt;

&lt;p&gt;We need to register authentication routes into routes/api.php file. Open the file and add below routes into it.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// user
Route::post('/login',  [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::get('/logout', [AuthController::class, 'logout'])-&amp;gt;middleware("jwtAuth");
Route::post('/refresh', [AuthController::class, 'refresh'])-&amp;gt;middleware("jwtAuth");
Route::get('/user-profile', [AuthController::class, 'getUser'])-&amp;gt;middleware("jwtAuth");


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Create AuthController controller class
&lt;/h2&gt;

&lt;p&gt;We have defined routes for authentication so far. We need to create a controller class to build application logic. The below Artisan command will generate a controller class at App/Http/Controllers/Api directory.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:controller AuthController


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the controller class, add the methods as per routes.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Validator;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpFoundation\Response;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    public $token = true;

    public function register(Request $request)
    {

         $validator = Validator::make($request-&amp;gt;all(), 
                      [ 
                      'name' =&amp;gt; 'required',
                      'email' =&amp;gt; 'required|email',
                      'password' =&amp;gt; 'required',  
                      'c_password' =&amp;gt; 'required|same:password', 
                     ]);  

         if ($validator-&amp;gt;fails()) {  

               return response()-&amp;gt;json(['error'=&amp;gt;$validator-&amp;gt;errors()], 401); 

            }   


        $user = new User();
        $user-&amp;gt;name = $request-&amp;gt;name;
        $user-&amp;gt;email = $request-&amp;gt;email;
        $user-&amp;gt;password = bcrypt($request-&amp;gt;password);
        $user-&amp;gt;save();

        if ($this-&amp;gt;token) {
            return $this-&amp;gt;login($request);
        }

        return response()-&amp;gt;json([
            'success' =&amp;gt; true,
            'data' =&amp;gt; $user
        ], Response::HTTP_OK);
    }

    public function login(Request $request)
    {
        $input = $request-&amp;gt;only('email', 'password');
        $jwt_token = null;

        if (!$jwt_token = JWTAuth::attempt($input)) {
            return response()-&amp;gt;json([
                'success' =&amp;gt; false,
                'message' =&amp;gt; 'Invalid Email or Password',
            ], Response::HTTP_UNAUTHORIZED);
        }

        return response()-&amp;gt;json([
            'success' =&amp;gt; true,
            'token' =&amp;gt; $jwt_token,
            'user'=&amp;gt; Auth::user(),
            ]);
    }

    public function logout(Request $request)
    {

        try {
            JWTAuth::invalidate(JWTAuth::parseToken($request-&amp;gt;token));

            return response()-&amp;gt;json([
                'success' =&amp;gt; true,
                'message' =&amp;gt; 'User logged out successfully'
            ]);
        } catch (JWTException $exception) {
            return response()-&amp;gt;json([
                'success' =&amp;gt; false,
                'message' =&amp;gt; 'Sorry, the user cannot be logged out'
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }

    }

    public function getUser(Request $request)
    {
        try{
            $user = JWTAuth::authenticate($request-&amp;gt;token);
            return response()-&amp;gt;json(['user' =&amp;gt; $user]);

        }catch(Exception $e){
            return response()-&amp;gt;json(['success'=&amp;gt;false,'message'=&amp;gt;'something went wrong']);
        }
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We have created methods for authenticating APIs for Login, Register, getUser, Token Refresh, and Logout routes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create JWTMiddleware controller class
&lt;/h2&gt;

&lt;p&gt;We need to protect our routes before the user gets into the controllers, for that we need to create a middleware JWTMiddleware using the command : &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:middleware JWTMiddleware


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The JWTMiddleware contains the verification of the Token sent with API.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;


&amp;lt;?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;

class JWTMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $message = '';
        try {
            // check validation of the token
            JWTAuth::parseToken()-&amp;gt;authenticate();
            return $next($request);
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            $message = 'Token expired';
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            $message = 'Invalid token';
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            $message = 'Provide token';
        }
        return response()-&amp;gt;json(['success' =&amp;gt; false, 'message' =&amp;gt; $message]);
    }
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Do the migration
&lt;/h2&gt;

&lt;p&gt;First, you need to create a database by the name laravel_jwt_rest_api,then run this command : &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan migrate



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Test application in Postman
&lt;/h2&gt;

&lt;p&gt;We have completed the application coding. Start the Laravel server using below Artisan command.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan serve


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For testing APIs, we will use Postman application.  Postman is an API platform for building and using APIs. We will test all API. Lets start from register API.&lt;/p&gt;

&lt;h2&gt;
  
  
  Register API
&lt;/h2&gt;

&lt;p&gt;All API routes are prefixed with api namespace. In the postman use &lt;a href="http://127.0.0.1:8000/api/register" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/api/register&lt;/a&gt; API endpoint. Pass name, email, password and c_password parameters into request. You will get message and user details into response.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1vqyo9lr3lk6sgtwbk08.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1vqyo9lr3lk6sgtwbk08.png" alt="Image description"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Login API
&lt;/h2&gt;

&lt;p&gt;Use &lt;a href="http://127.0.0.1:8000/api/login" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/api/login&lt;/a&gt; API endpoint with email password parameter with request. If the email and password matches with registered user, you will receive token json object into response&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5cd2jhzsw3e2sh029sil.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5cd2jhzsw3e2sh029sil.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  GetUser API
&lt;/h2&gt;

&lt;p&gt;All JWTMiddleware middleware routes are protected with api guard. You need to pass access_token in Header as bearer token.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fempygisb0z3cpr6dynr4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fempygisb0z3cpr6dynr4.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F61s910f6wkfdhjflflws.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F61s910f6wkfdhjflflws.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Logout API
&lt;/h2&gt;

&lt;p&gt;To logout the user, you need to invalidate the current token. You can simply call auth()-&amp;gt;logout() method to invalidate current access token. Once user, logged out, it can't access protected routes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fahdvcc6jzb4dfbygxvd8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fahdvcc6jzb4dfbygxvd8.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Eventually, our tutorial is over. We have learned how to implement JWT authentication in Laravel application. In the next tutorial, we will use JWT token for REST API.&lt;/p&gt;

&lt;p&gt;I hope, this tutorial will help on your development. If you liked this tutorial, please consider to share with your friends.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>beginners</category>
      <category>api</category>
      <category>jwt</category>
    </item>
  </channel>
</rss>
