Level Up Your PHP Skills with Our Laravel Mastery Course

“Leverage Laravel’s Powerful Features Dive Deep into MVC Architecture, Eloquent ORM, and Modern Web Development Practices.”

Strat Your Test Now Dear learners, Are you interested in assessing your progress? Request your mentor to give you access and start your Test.

Are you ready to master one of the most popular PHP frameworks for web development? Our comprehensive Laravel course is designed to take you from beginner to advanced level, covering everything you need to know to build modern web applications with ease.

Learn Basic Laravel

1.Basic Routing:

In Laravel, all requests are mapped with the help of routes. Basic routing routes the request to the associated controllers. This chapter discusses routing in Laravel.

Defining Routes: Routes are typically defined in the routes/web.php file for web routes and routes/api.php for API routes. You can define routes using the Route facade or helper functions like get, post, put, delete, etc.

PHP

 // Define a basic GET route
Route::get('/welcome', function () {
    return 'Welcome to Laravel!';
}); 

OUTPUT

Route Parameters: You can define dynamic route parameters by enclosing them in curly braces {}. These parameters will be passed to the route callback function.

PHP

// Define a route with a dynamic parameter
Route::get('/user/{id}', function ($id) {
    return 'User ID: ' . $id;
});

OUTPUT

Route Naming: Routes can be named to simplify referencing them in your application. This is especially useful for generating URLs.

PHP

// Define a named route
Route::get('/profile', function () {
    // Route logic
})->name('profile');

OUTPUT

Route Groups: You can group related routes using the Route::group method. This allows you to apply middleware or prefix routes.

PHP

// Define a route group with middleware
Route::group(['middleware' => 'auth'], function () {
    // Routes that require authentication
});

OUTPUT

Route Prefixes: You can prefix all routes within a group with a common URI segment.

PHP

// Define route group with prefix
Route::prefix('admin')->group(function () {
    // Routes for admin section
});

OUTPUT

Fallback Routes: You can define a fallback route that will be called if no other route matches the incoming request.

PHP

// Define a fallback route
Route::fallback(function () {
    return '404 - Page Not Found';
});

OUTPUT

1.Introduction to routes and creating simple routes: In Laravel, routes are used to define how the application responds to HTTP requests. They serve as the entry points for incoming requests and map URLs to controllers or closures that handle the request logic. Here’s an introduction to routes and creating simple routes in Laravel:

1. Understanding Routes:

Routes in Laravel are typically defined in the routes directory. There are two main types of routes:
  • Web Routes: These routes are used for handling web requests and are defined in the routes/web.php file.
  • API Routes: These routes are used for building APIs and are defined in the routes/api.php file.

2. Creating Simple Routes:

Web Routes:
In the routes/web.php file, you can define routes using the Route facade or helper functions like get, post, put, delete, etc.

PHP

 // Define a basic GET route
Route::get('/hello', function () {
    return 'Hello, Laravel!';
});

// Define a route that responds to POST requests
Route::post('/submit-form', function () {
    return 'Form submitted successfully!';
});

API Routes

// Define a GET route for fetching user data
Route::get('/users', function () {
    return [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        // More user data...
    ];
});

// Define a route with route parameters
Route::get('/user/{id}', function ($id) {
    return 'User ID: ' . $id;
});

3. Route Parameters:

You can define dynamic route parameters by enclosing them in curly braces {}. These parameters will be passed to the route callback function.

PHP

// Define a route with a dynamic parameter
Route::get('/user/{id}', function ($id) {
    return 'User ID: ' . $id;
});

OUTPUT

4. Named Routes:

Routes can be named to simplify referencing them in your application, especially when generating URLs.
Conclusion:
Routes play a crucial role in Laravel applications, allowing you to define how your application responds to various HTTP requests. By defining routes, you can create a logical structure for your application and map URLs to specific actions or controllers. This allows for clean and organized code, making it easier to maintain and scale your application.

PHP

// Define a named route
Route::get('/profile', function () {
    // Route logic
})->name('profile');

OUTPUT

Controllers:

In Laravel, controllers are used to handle the application logic for processing HTTP requests. They provide a centralized location to organize and manage the handling of different HTTP request methods (GET, POST, PUT, DELETE, etc.) for specific routes or URI endpoints. Here’s an overview of controllers in Laravel:
1. Creating Controllers:
You can create controllers using Artisan, Laravel’s command-line interface. Use the make:controller command to generate a new controller:

bash

php artisan make:controller UserController

OUTPUT

2. Controller Structure:
A controller class typically extends Laravel’s base Controller class and contains methods to handle various actions related to a particular resource or functionality.

PHP

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    // Method to handle GET requests
    public function index()
    {
        // Logic to fetch and return data
    }

    // Method to handle POST requests
    public function store(Request $request)
    {
        // Logic to store data
    }

    // Method to handle PUT/PATCH requests
    public function update(Request $request, $id)
    {
        // Logic to update data
    }

    // Method to handle DELETE requests
    public function destroy($id)
    {
        // Logic to delete data
    }
}

OUTPUT

3. Route-Controller Mapping:
Once you’ve created a controller, you can map routes to controller methods in the routes/web.php or routes/api.php file.

PHP

use App\Http\Controllers\UserController;

// Map routes to controller methods
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);

OUTPUT

4. Route Parameters:
Controllers can accept route parameters by defining them as method arguments.

PHP

public function show($id)
{
    // Logic to fetch and return data for a specific resource
}

output

5. Dependency Injection:
Controllers can also accept dependencies through constructor injection. This allows you to easily inject services or other dependencies into your controllers.
Conclusion:
Controllers play a crucial role in Laravel applications by encapsulating the logic for handling HTTP requests. They help in maintaining clean and organized code by separating concerns and adhering to the MVC architectural pattern. With controllers, you can easily manage the application’s behavior and interact with models, views, and other components to build robust web applications.

PHP

use App\Services\UserService;

class UserController extends Controller
{
    protected $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    // Controller methods using $userService
}

OUTPUT

Creating controllers and understanding their role :

Creating controllers and understanding their role is fundamental in Laravel development. Controllers serve as the intermediary between routes and business logic, helping organize and manage the application’s behavior. Here’s how to create controllers and understand their role in Laravel:
1. Creating Controllers:
You can create controllers using Laravel’s Artisan command-line tool. Open your terminal and run the following command:

bash

php artisan make:controller UserController

OUTPUT

2. Defining Controller Methods:

Inside the controller file, you define methods to handle various actions related to a specific resource or functionality. For example:

PHP

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('users.index', ['users' => $users]);
    }

    public function show($id)
    {
        $user = User::findOrFail($id);
        return view('users.show', ['user' => $user]);
    }

    public function store(Request $request)
    {
        // Validation and store logic
    }

    public function update(Request $request, $id)
    {
        // Validation and update logic
    }

    public function destroy($id)
    {
        // Delete logic
    }
}

OUTPUT

3. Role of Controllers:

  • Request Handling: Controllers handle incoming HTTP requests and define how the application responds to them. They encapsulate the logic for processing requests, fetching data, and returning appropriate responses.
  • Business Logic: Controllers contain the business logic necessary to perform operations on resources, such as creating, reading, updating, and deleting data from the database.
  • Route-Controller Mapping: Controllers are mapped to routes in the routes/web.php or routes/api.php files. Each route points to a specific controller method, defining the endpoint’s behavior.
  • Separation of Concerns: Controllers help maintain separation of concerns by keeping request handling and business logic separate from the routing and view presentation layers.
  • Code Organization: Controllers provide a centralized location to organize and manage application logic related to specific resources or functionalities, promoting code reusability and maintainability.
Conclusion:
Controllers play a crucial role in Laravel applications by handling request processing, encapsulating business logic, and maintaining code organization. By creating controllers and defining their methods, you can build robust and scalable web applications in Laravel. Understanding the role of controllers is essential for effective Laravel development.
3. Views:
In Laravel, views are responsible for rendering the HTML content that is sent back to the client’s browser. They contain the presentation layer of your application and allow you to display dynamic data to users. Here’s an overview of views in Laravel:
1. Creating Views:
Views in Laravel are typically stored in the resources/views directory. You can create a new view file by simply creating a new .blade.php file within this directory.

PHP

// Example view file: resources/views/welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to our website!</h1>
</body>
</html>

OUTPUT

2. Blade Templating Engine:
Laravel uses the Blade templating engine for views, which allows for the use of templating features such as inheritance, conditionals, loops, and more.

PHP

// Example of Blade template inheritance
// resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title')</title>
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html>

// Example of extending the layout and providing content
// resources/views/welcome.blade.php
@extends('layouts.app')

@section('title', 'Welcome')

@section('content')
    <h1>Welcome to our website!</h1>
@endsection

OUTPUT

3. Passing Data to Views:
You can pass data from your controller to a view using the with() method or by compacting an array of data.

PHP

// Passing data to a view
public function index()
{
    $users = User::all();
    return view('users.index')->with('users', $users);
    // OR: return view('users.index', compact('users'));
}

OUTPUT

4. Blade Directives:
Blade provides a variety of directives for executing PHP code within your views, including control structures, conditionals, loops, and more.

PHP

// Example of Blade directives
@if(count($users) > 0)
    <ul>
        @foreach($users as $user)
            <li>{{ $user->name }}</li>
        @endforeach
    </ul>
@else
    <p>No users found.</p>
@endif

OUTPUT

5. View Composers:
View composers allow you to bind data to views automatically, without needing to pass it from the controller each time.
Conclusion:
Views play a crucial role in Laravel applications by providing the presentation layer and allowing you to render dynamic content to users. By using Blade templating engine, passing data to views, and leveraging Blade directives, you can create interactive and dynamic web pages with ease in Laravel. Understanding views is essential for building well-structured and user-friendly Laravel applications.

PHP

// Example of a view composer
public function boot()
{
    view()->composer('profile', function ($view) {
        $view->with('user', auth()->user());
    });
}

OUTPUT

Basics of Blade templating engine:
The Blade templating engine in Laravel provides a powerful and intuitive way to work with views. It allows you to create dynamic and reusable templates for your web application’s presentation layer. Here are the basics of Blade templating engine in Laravel:
1. Blade Syntax:
Blade uses curly braces {} to echo out variables and other expressions. For example:

PHP

// Echoing out a variable
{{ $name }}

// Using PHP echo inside Blade
{{ 'Hello, ' . $name }}

// Echoing out HTML
{{ '

Some HTML

' }} // Escaping HTML entities {!! '

Some HTML

' !!}

OUTPUT

2. Blade Directives:
Blade provides a variety of directives that allow you to execute PHP code more easily within your views. Some common directives include:
  • @if, @elseif, @else, @endif: Conditionals
  • @foreach, @endforeach: Loops
  • @for, @endfor: For loops
  • @while, @endwhile: While loops
  • @include: Including sub-views
  • @extends, @section, @yield, @endsection: Template inheritance
3. Template Inheritance:
Blade supports template inheritance, allowing you to define a master layout and extend or override sections in child views. This promotes code reusability and helps keep your views organized.

PHP

// Master layout: resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title')</title>
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html>

// Child view: resources/views/home.blade.php
@extends('layouts.app')

@section('title', 'Home')

@section('content')
    <h1>Welcome to our website!</h1>
@endsection

OUTPUT

4. Blade Comments:
Blade allows you to add comments to your views using the {{-- comment here --}} syntax. These comments will not be rendered in the final HTML output.
Conclusion:
Blade templating engine in Laravel simplifies the process of working with views by providing a concise and expressive syntax. With Blade, you can create dynamic and reusable templates, use control structures and loops more efficiently, and organize your views using template inheritance. Understanding the basics of Blade is essential for building efficient and maintainable Laravel applications.

PHP

{{-- This is a Blade comment --}}

OUTPUT

4.Creating and displaying views:
In Laravel, creating and displaying views is a fundamental aspect of building web applications. Views are responsible for rendering the HTML content that is sent back to the client’s browser. Here’s how you can create and display views in Laravel:
1. Creating Views:
Views in Laravel are typically stored in the resources/views directory. You can create a new view file by creating a new .blade.php file within this directory.

PHP

touch resources/views/welcome.blade.php

OUTPUT

2. Writing the View:
Open the newly created view file (welcome.blade.php) in your text editor and write the HTML content you want to display.

PHP

<!-- resources/views/welcome.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to our website!</h1>
</body>
</html><!-- resources/views/welcome.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to our website!</h1>
</body>
</html>

OUTPUT

3. Displaying Views:
There are multiple ways to display views in Laravel:
a. Using Route Closure:
You can return a view directly from a route closure in the routes/web.php file.

PHP

// routes/web.php
Route::get('/', function () {
    return view('welcome');
});

OUTPUT

b. Using Controller:
You can create a controller method to handle the logic and return a view from the controller.

PHP

// Create a controller using Artisan
php artisan make:controller HomeController

// HomeController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index()
    {
        return view('welcome');
    }
}

OUTPUT

4. Passing Data to Views:
You can pass data from your controller to a view using the with() method or by compacting an array of data.
Conclusion:
Creating and displaying views in Laravel is straightforward. By following these steps, you can create reusable view files, display them in your application using routes or controllers, and pass data to them as needed. Views play a crucial role in presenting the UI to users and are essential for building dynamic web applications in Laravel.

PHP

// HomeController.php
public function index()
{
    $name = 'John';
    return view('welcome')->with('name', $name);
    // OR: return view('welcome', compact('name'));
}

php

Models and Eloquent ORM:
In Laravel, models and the Eloquent ORM (Object-Relational Mapping) provide a convenient and expressive way to interact with your database tables. Models represent individual database tables, while the Eloquent ORM allows you to perform database operations using an object-oriented approach. Here’s an overview of models and Eloquent ORM in Laravel:
1. Creating Models:
You can create models using Artisan, Laravel’s command-line interface. Use the make:model command to generate a new model:

bash

php artisan make:model User

php

2. Defining Model Relationships:
In Laravel, you can define relationships between models using Eloquent’s relationship methods. There are several types of relationships:
  • One-to-One: Use the hasOne and belongsTo methods.
  • One-to-Many: Use the hasMany and belongsTo methods.
  • Many-to-Many: Use the belongsToMany method.

PHP

$user = User::create(['name' => 'John Doe', 'email' => 'john@example.com']);

php

2. Read:
Use various methods like all, find, first, where, etc., to retrieve records from the database.

PHP

$users = User::all();
$user = User::find(1);

php

Update: Use the update method to update existing records in the database.

PHP

$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();

php

Delete: Use the delete method to remove records from the database.

PHP

$user = User::find(1);
$user->delete();

php

4. Querying with Eloquent:
Eloquent provides a fluent query builder that allows you to write expressive and readable database queries:
Conclusion:
Models and the Eloquent ORM in Laravel provide a powerful way to interact with your database tables. By defining models, establishing relationships, and using Eloquent’s methods, you can perform database operations in a clean and expressive manner. Understanding models and Eloquent ORM is essential for building robust and efficient Laravel applications.

PHP

$users = User::where('age', '>', 18)
             ->orderBy('created_at', 'desc')
             ->get();

php

Introduction to models and relationships:
In PHP, models are components of the MVC (Model-View-Controller) architectural pattern used for managing the data of an application. Models represent the data structures, business logic, and rules of an application. They interact with the database, perform data manipulation, and enforce business rules.
1. Creating Models:
In PHP, models are typically created as classes. Each model class corresponds to a database table, and its properties represent the table columns.

PHP

// Example of a User model class
class User {
    public $id;
    public $username;
    public $email;
    // More properties and methods...
}

php

2. Defining Relationships:
Relationships between models represent how data entities are related to each other in the database. There are several types of relationships:
  • One-to-One: Each record in one table is related to only one record in another table.
  • One-to-Many: A single record in one table can be related to multiple records in another table.
  • Many-to-Many: Multiple records in one table can be related to multiple records in another table.

Example:

Consider a scenario where we have User and Post models. Each user can have multiple posts, establishing a one-to-many relationship.
Conclusion:
Models play a vital role in PHP applications, serving as the backbone for managing data and relationships. By defining models and relationships, you can organize your application’s data structure and enforce business rules effectively. Understanding models and relationships is essential for building scalable and maintainable PHP applications, especially when following the MVC architectural pattern.

PHP

// User model class
class User {
    public $id;
    public $username;
    public $email;
    // Define a relationship with Post model (one-to-many)
    public function posts() {
        return Post::findByUserId($this->id);
    }
}

// Post model class
class Post {
    public $id;
    public $title;
    public $content;
    public $user_id;
    // Define a method to find posts by user ID
    public static function findByUserId($userId) {
        // Database query to find posts by user ID
    }
}

php

Basic CRUD operations with Eloquent:
CRUD operations (Create, Read, Update, Delete) with Eloquent in Laravel allow you to interact with your database tables using expressive and intuitive syntax. Here’s how you can perform basic CRUD operations with Eloquent:
1. Creating Records (Create):
To create a new record in the database, you can use the create method of the corresponding Eloquent model. This method accepts an array of attributes representing the data to be inserted into the database.

PHP

use App\Models\User;

$user = User::create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => bcrypt('password123'),
]);

php

2. Reading Records (Read):
To retrieve records from the database, you can use various Eloquent query methods:
  • Retrieve All Records: Use the all method to fetch all records from the table.
  • Retrieve Single Record by ID: Use the find method to retrieve a single record by its primary key.
  • Retrieve Records with Conditions: Use methods like where to specify conditions for retrieving records.

PHP

$users = User::all();

$user = User::find(1);

$users = User::where('age', '>', 18)->get();

php

3. Updating Records (Update):
To update existing records in the database, you can retrieve the record, modify its attributes, and then call the save method. Alternatively, you can use the update method to update multiple records that match a given condition.

PHP

$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();

php

4. Deleting Records (Delete):
To delete records from the database, you can use the delete method on a model instance. Alternatively, you can use the destroy method to delete records by their primary keys.
Conclusion:
Eloquent in Laravel provides a fluent and expressive way to perform CRUD operations on database tables. By using methods like create, find, where, update, and delete, you can easily interact with your database tables and manipulate data according to your application’s requirements. Understanding basic CRUD operations with Eloquent is essential for building efficient and maintainable Laravel applications.

PHP

User::destroy([1, 2, 3]);

php

Database Migrations and Seeding :
Database migrations and seeding are essential features in Laravel for managing database schema and populating the database with test data. Let’s understand both concepts:
Database Migrations:
  1. Creating Migrations:
    • Use the make:migration Artisan command to create a new migration file.
  2. Defining Schema:
    • Inside the migration file, use the up method to define the schema changes for creating or modifying database tables.
    • Use the down method to define the rollback operations in case of migration rollback.

bash

php artisan make:migration create_users_table

php

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();
});

Running Migrations:

  • Execute pending migrations using the migrate Artisan command.

Rolling Back Migrations:

  • To rollback the last migration batch, use the rollback command.

bash

php artisan migrate

bash

php artisan migrate:rollback

Database Seeding:

  1. Creating Seeders:
    • Use the make:seeder Artisan command to generate a new seeder class.
    • Seeder classes are stored in the database/seeders directory.
  2. Defining Seed Data:
    • Inside the seeder class, use the run method to define the data to be inserted into the database.

bash

php artisan make:seeder UsersTableSeeder

php

public function run()
{
    User::factory()->count(10)->create();
}
Running Seeders:
  • Use the db:seed Artisan command to run specific seeders or all seeders.
Refreshing Database:
  • You can reset the database and re-run all migrations and seeders using the migrate:refresh command.
Conclusion:
Database migrations and seeding are crucial aspects of Laravel development, facilitating efficient management of database schema and data. Migrations enable version control for database schema changes, while seeding allows you to populate the database with initial or test data. By mastering migrations and seeding, you can effectively manage your application’s database structure and data integrity.

bash

php artisan db:seed

bash

php artisan migrate:refresh --seed

Managing database structure with migrations :

In Laravel, managing the database structure with migrations is a fundamental aspect of database management. Migrations allow you to version control your database schema changes, making it easy to update and roll back changes as needed. Here’s how you can manage your database structure using migrations in Laravel:
1. Creating Migrations:
You can create a new migration file using the make:migration Artisan command. Migration files are stored in the database/migrations directory.

bash

php artisan make:migration create_users_table

php

2. Defining Schema Changes:
Inside the migration file, you use the up method to define the schema changes you want to make to your database tables. This typically includes creating new tables, modifying existing tables, or adding/removing columns.

php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    public function up()
    {
        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();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

php

3. Running Migrations:
Once you’ve defined your migration file, you can execute the migrations using the migrate Artisan command. This command will run all pending migrations and update your database schema accordingly.
4. Rolling Back Migrations:
If you need to undo a migration and revert the changes made to your database schema, you can use the rollback command. This will undo the last batch of migrations that were run.

bash

php artisan migrate

bash

php artisan migrate:rollback
5. Viewing Migration Status:
You can check the status of your migrations using the migrate:status command. This will show you which migrations have been run and which are pending.
Conclusion:
Using migrations in Laravel allows you to manage your database structure in a systematic and organized way. By creating migration files, defining schema changes, and running migrations, you can easily version control your database schema and keep it in sync with your application’s codebase. This helps maintain data integrity and facilitates collaboration among developers working on the same project.

bash

php artisan migrate:status

php

Seeding the database with sample data :
Seeding the database with sample data in Laravel is a common practice for populating your application’s database tables with initial or test data. Laravel provides a convenient way to create seeders and run them to populate your database. Here’s how you can seed the database with sample data in Laravel:
1. Creating Seeders:
You can create a new seeder class using the make:seeder Artisan command. Seeder classes are stored in the database/seeders directory.

bash

php artisan make:seeder UsersTableSeeder

php

Middleware:
Middleware in Laravel is a mechanism that allows you to filter HTTP requests entering your application. It provides a convenient way to inspect, modify, or terminate incoming requests based on defined conditions. Middleware sits between the client’s request and your application’s routes, allowing you to perform tasks such as authentication, authorization, logging, and more. Here’s how middleware works in Laravel:
1. Creating Middleware:
You can create a new middleware class using the make:middleware Artisan command. Middleware classes are stored in the app/Http/Middleware directory.

bash

php artisan make:middleware CheckAge

output

2. Defining Middleware Logic:
Inside the middleware class, you implement the handle method, which receives the incoming request and a closure. You can perform checks or modifications to the request and then either pass it to the next middleware in the pipeline or return a response immediately.

PHP

namespace App\Http\Middleware;

use Closure;

class CheckAge
{
    public function handle($request, Closure $next)
    {
        if ($request->age >= 18) {
            return $next($request);
        }

        return redirect('home');
    }
}

OUTPUT

3. Registering Middleware:
You can register middleware globally, for specific routes, or within controller constructors. Global middleware runs on every HTTP request, while route middleware applies only to specific routes.
  • Global Middleware: Defined in the $middleware property of App/Http/Kernel.php.
  • Route Middleware: Registered in the $routeMiddleware property of App/Http/Kernel.php and assigned to routes in the routes/web.php or routes/api.php files.

php

// Registering middleware in Kernel.php
protected $routeMiddleware = [
    'check.age' => \App\Http\Middleware\CheckAge::class,
];

OUTPUT

4. Applying Middleware:
You can apply middleware to routes using the middleware method within route definitions. You can also group routes and apply middleware to the entire group.

PHP

// Applying middleware to a single route
Route::get('profile', function () {
    //
})->middleware('check.age');

// Applying middleware to a group of routes
Route::middleware(['auth', 'check.age'])->group(function () {
    Route::get('dashboard', function () {
        //
    });
});

OUTPUT

5. Terminable Middleware:
Middleware classes can implement the TerminableMiddleware interface, allowing them to perform tasks after the response has been sent to the client. This is useful for logging, cleanup, or other operations.
Conclusion:
Middleware in Laravel provides a flexible and powerful mechanism for filtering HTTP requests and performing tasks before or after they reach your application’s routes. By creating middleware classes, defining middleware logic, and registering them with your application, you can implement various features such as authentication, authorization, logging, and more, while keeping your code organized and maintainable.

PHP

namespace App\Http\Middleware;

use Closure;

class LogResponseTime
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Log response time or perform cleanup
    }
}

OUTPUT

Understanding and creating middleware for request handling:
Middleware in Laravel is a critical component for handling HTTP requests by filtering or modifying them before they reach your application’s routes. Let’s delve into understanding and creating middleware for request handling in Laravel:
Understanding Middleware:
Middleware acts as a bridge between a request and a response. It sits between the client’s request and your application’s routes, allowing you to intercept, modify, or terminate requests based on defined conditions. Middleware can be used for tasks such as authentication, authorization, logging, CSRF protection, and more.
Creating Middleware:
Here’s a step-by-step guide to creating middleware in Laravel:
  1. Generate Middleware Class: Use the make:middleware Artisan command to generate a new middleware class.

PHP

php artisan make:middleware CheckAgeMiddleware

OUTPUT

 Middleware Class Structure:

Open the generated middleware class located in the app/Http/Middleware directory. The class contains a handle method where you define the logic to be executed for each HTTP request.

PHP

namespace App\Http\Middleware;

use Closure;

class CheckAgeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform middleware logic here
        if ($request->age >= 18) {
            return $next($request);
        } else {
            return redirect('home');
        }
    }
}

OUTPUT

Register Middleware: Register your middleware in the $routeMiddleware array located in the app/Http/Kernel.php file. Applying Middleware: You can apply middleware to routes or route groups using the middleware method in your route definitions.
Conclusion:
Middleware in Laravel provides a powerful mechanism for intercepting and handling HTTP requests before they reach your application’s routes. By creating custom middleware, you can implement various request processing tasks in a modular and reusable manner. Understanding and creating middleware is essential for building robust and secure Laravel applications.

PHP

protected $routeMiddleware = [
    'check.age' => \App\Http\Middleware\CheckAgeMiddleware::class,
];

Route::get('profile', function () {
    //
})->middleware('check.age');

Route::middleware(['check.age'])->group(function () {
    // Routes that require check.age middleware
});

OUTPUT

Forms and Validation:
Forms and validation are essential components of web development, allowing users to input data and ensuring that the data meets certain criteria before being processed. In Laravel, form handling and validation are made easy with built-in features. Here’s how you can work with forms and validation in Laravel:
1. Creating Forms:
You can create HTML forms in your Laravel views using Blade templating syntax. For example, to create a simple form for user registration:

PHP

<form method="POST" action="{{ route('register') }}">
    @csrf
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Register</button>
</form>

OUTPUT

2. Handling Form Submissions:
In your controller, you can handle form submissions by accessing the incoming request data using the request() helper or type-hinting the Illuminate\Http\Request class. For example, to handle user registration:

PHP

use Illuminate\Http\Request;

public function register(Request $request)
{
    // Validate incoming data
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users|max:255',
        'password' => 'required|string|min:8',
    ]);

    // Create new user using validated data
    // ...
}

OUTPUT

3. Validation Rules:
Laravel provides a wide range of validation rules that you can apply to form fields. Common validation rules include required, string, email, unique, min, max, and more. You can also create custom validation rules.
4. Displaying Validation Errors:
If validation fails, Laravel automatically redirects the user back to the previous page with the validation errors flashed to the session. You can display these errors in your views using Blade directives.
Conclusion:
Forms and validation are fundamental aspects of web development, ensuring data integrity and security. In Laravel, handling forms and validation is made easy with built-in features like Blade templating, form submission handling, and validation rules. By understanding how to create forms, handle form submissions, define validation rules, and display validation errors, you can build robust and user-friendly web applications in Laravel.

PHP

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

OUTPUT

Building forms and validating user input:
Building forms and validating user input are common tasks in Laravel development. Laravel provides convenient tools for creating forms, handling form submissions, and validating user input. Here’s how you can build forms and validate user input in Laravel:
1. Creating Forms:
You can create HTML forms in your Laravel views using Blade templating syntax. For example, to create a form for user registration:

PHP

<form method="POST" action="{{ route('register') }}">
    @csrf
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Register</button>
</form>

OUTPUT

2. Handling Form Submissions:
In your controller, you can handle form submissions by accessing the incoming request data using the request() helper or type-hinting the Illuminate\Http\Request class. For example, to handle user registration:

PHP

use Illuminate\Http\Request;

public function register(Request $request)
{
    // Validate incoming data
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users|max:255',
        'password' => 'required|string|min:8',
    ]);

    // Create new user using validated data
    // ...
}

OUTPUT

3. Validation Rules:
Laravel provides a wide range of validation rules that you can apply to form fields. Common validation rules include required, string, email, unique, min, max, and more. You can also create custom validation rules.
4. Displaying Validation Errors:
If validation fails, Laravel automatically redirects the user back to the previous page with the validation errors flashed to the session. You can display these errors in your views using Blade directives.
Conclusion:
Building forms and validating user input are essential tasks in Laravel development. By using Laravel’s built-in form handling and validation features, you can create secure and user-friendly web applications with ease. Understanding how to create forms, handle form submissions, define validation rules, and display validation errors is crucial for building robust and reliable Laravel applications.

PHP

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

OUTPUT

Authentication and Authorization :
Authentication and authorization are critical aspects of web development, ensuring that users can securely access resources and perform actions within an application. In Laravel, authentication and authorization are made simple with built-in features. Here’s how you can implement authentication and authorization in Laravel:
Authentication:
Authentication verifies the identity of users and allows them to access protected areas of an application. Laravel provides a robust authentication system out of the box, including features such as user registration, login, logout, password reset, and more.
  1. Setup Authentication: Laravel includes an artisan command to scaffold all the necessary authentication routes and views:

PHP

php artisan make:auth

OUTPUT

Authentication Middleware:
Laravel’s built-in authentication middleware can be applied to routes to ensure that only authenticated users can access certain routes. For example: Protecting Routes: You can protect routes using the auth middleware to ensure that only authenticated users can access them. For example:

Authorization:

Authorization determines what actions a user is allowed to perform within an application. Laravel provides a flexible authorization system for defining and enforcing access control rules.
  1. Policies: Laravel’s policy feature allows you to define authorization logic for model actions. Policies are classes that encapsulate authorization logic for a particular model.
  2. Gates: Gates are another way to authorize actions in Laravel. Gates allow you to define simple authorization callbacks for various tasks.
  3. Authorization Middleware: Laravel also provides middleware for authorizing HTTP requests based on custom conditions. You can define and apply authorization middleware to routes as needed.

Conclusion:

Authentication and authorization are essential components of web applications, ensuring that users can securely access resources and perform actions according to their permissions. Laravel provides robust authentication and authorization features out of the box, making it easy to implement secure access control in your applications. By leveraging Laravel’s built-in authentication scaffolding, middleware, policies, and gates, you can build secure and reliable web applications with ease.

PHP

Route::get('/dashboard', function () {
    // Only authenticated users can access this route
})->middleware('auth');

Route::middleware(['auth'])->group(function () {
    // Protected routes
});

OUTPUT

Implementing user authentication :
Implementing user authentication in Laravel is a straightforward process thanks to Laravel’s built-in authentication scaffolding. Here’s a step-by-step guide to implementing user authentication in Laravel:
1. Generate Authentication Scaffolding:
Use the make:auth Artisan command to generate the authentication scaffolding, including routes, controllers, and views for registration, login, and password reset.

PHP

php artisan make:auth

OUTPUT

2. Database Configuration:
Ensure that your database connection is properly configured in the .env file. Laravel’s authentication system relies on a database table named users by default.
3. Run Migrations:
Run the database migrations to create the necessary users table in your database.

PHP

php artisan migrate

php

Models and Eloquent ORM:
In Laravel, models and the Eloquent ORM (Object-Relational Mapping) provide a convenient and expressive way to interact with your database tables. Models represent individual database tables, while the Eloquent ORM allows you to perform database operations using an object-oriented approach. Here’s an overview of models and Eloquent ORM in Laravel:
1. Creating Models:
You can create models using Artisan, Laravel’s command-line interface. Use the make:model command to generate a new model:

bash

php artisan make:model User

php

4. Authenticate Routes:
Laravel’s authentication scaffolding automatically adds routes for registration, login, and password reset. You can find these routes in the routes/web.php file.
5. Protect Routes:
Use the auth middleware to protect routes that should only be accessible to authenticated users. For example, to protect the dashboard route:

PHP

Route::get('/dashboard', function () {
    // Only authenticated users can access this route
})->middleware('auth');

php

6. Display Authentication Links:
In your views, you can display authentication links such as login and register links using Blade directives. For example:
Conclusion:
By following these steps, you can quickly implement user authentication in your Laravel application. Laravel’s built-in authentication scaffolding provides a robust foundation for user authentication, making it easy to get started with authentication features such as registration, login, and password reset. With Laravel, you can build secure and user-friendly authentication systems for your web applications with minimal effort.

PHP

@if (Route::has('login'))
    <div>
        @auth
            <a href="{{ url('/dashboard') }}">Dashboard</a>
        @else
            <a href="{{ route('login') }}">Login</a>

            @if (Route::has('register'))
                <a href="{{ route('register') }}">Register</a>
            @endif
        @endauth
    </div>
@endif

php

Managing user roles and permissions :
Managing user roles and permissions in Laravel involves creating a system where users can be assigned specific roles, and each role has certain permissions associated with it. Here’s a step-by-step guide on how to implement user roles and permissions in Laravel:
1. Install Laravel Permission Package:
You can use packages like spatie/laravel-permission to manage roles and permissions in Laravel. Install the package via Composer:

bash

composer require spatie/laravel-permission

php

2. Publish Configuration File:
Publish the configuration file to customize the settings:
3. Configure Models:
Ensure that your User model uses the HasRoles trait provided by the package:

bash

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"

php

use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
}
4. Define Roles and Permissions:
Define roles and permissions in your application. You can do this using Laravel’s Seeder classes:

PHP

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Create roles
        Role::create(['name' => 'admin']);
        Role::create(['name' => 'editor']);
        
        // Create permissions
        Permission::create(['name' => 'create post']);
        Permission::create(['name' => 'edit post']);
        
        // Assign permissions to roles
        Role::findByName('admin')->givePermissionTo(['create post', 'edit post']);
        Role::findByName('editor')->givePermissionTo('create post');
    }
}

php

5. Assign Roles to Users:
You can assign roles to users using their model instances:
6. Check Permissions:
You can check if a user has a certain permission using the hasPermissionTo method:
Conclusion:
By following these steps, you can implement user roles and permissions in your Laravel application using the spatie/laravel-permission package. This allows you to easily manage user roles, assign permissions, and control access to different parts of your application based on user roles and permissions.

PHP

$user = User::find(1);
$user->assignRole('admin');

if ($user->hasPermissionTo('edit post')) {
    // User has permission to edit posts
}

php

Error Handling and Logging :
Error handling and logging are crucial aspects of web development, allowing you to identify and debug issues in your application effectively. In Laravel, error handling and logging are managed through robust mechanisms. Here’s how you can handle errors and logging in Laravel:
1. Error Handling:
a. Exception Handling:
Laravel provides an App\Exceptions\Handler class for managing exceptions thrown by your application. You can customize this class to handle exceptions in various ways, such as rendering custom error pages or logging errors.

PHP

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
}

php

b. Custom Error Pages:

You can customize the error pages returned by your application for specific HTTP error codes. Laravel’s resources/views/errors directory contains Blade templates for various error pages, which you can modify to suit your application’s design and branding.
2. Logging:
Laravel provides a powerful logging mechanism that allows you to log messages and errors to various channels, such as files, databases, Slack, and more.
a. Log Configuration:
Logging configuration is defined in the config/logging.php file. You can specify different log channels and their configurations, including the log storage location and the log level.
b. Logging Messages:
You can log messages and errors using Laravel’s Log facade. For example:

PHP

use Illuminate\Support\Facades\Log;

Log::info('This is an informational message.');
Log::error('An error occurred: Something went wrong.');

php

Handling errors gracefully :
Handling errors gracefully in Laravel involves providing users with meaningful error messages and responses, as well as logging errors for debugging purposes. Here’s how you can handle errors gracefully in Laravel:
1. Custom Error Pages:
Laravel allows you to create custom error pages for different HTTP error codes. You can modify the default error pages or create your own Blade templates in the resources/views/errors directory.

PHP

// resources/views/errors/404.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>404 Not Found</h1>
        <p>Sorry, the page you are looking for could not be found.</p>
    </div>
@endsection

php

2. Exception Handling:
Laravel’s App\Exceptions\Handler class is responsible for handling exceptions thrown by your application. You can customize this class to handle exceptions gracefully, such as rendering custom error pages or returning JSON responses. For example, you can modify the render method to return a custom error response for specific exceptions:

PHP

public function render($request, Exception $exception)
{
    if ($exception instanceof NotFoundHttpException) {
        return response()->view('errors.404', [], 404);
    }

    return parent::render($request, $exception);
}

php

3. Logging Errors:
It’s essential to log errors for debugging and monitoring purposes. Laravel’s logging mechanism allows you to log messages and errors to various channels, such as files, databases, or external services. You can log errors using Laravel’s Log facade within your application’s code:
Conclusion:
By customizing error pages, handling exceptions gracefully, and logging errors effectively, you can ensure that your Laravel application provides a smooth and user-friendly experience even when errors occur. Graceful error handling improves user satisfaction, helps in troubleshooting, and enhances the overall reliability of your application.

PHP

use Illuminate\Support\Facades\Log;

try {
    // Code that may throw an exception
} catch (Exception $e) {
    Log::error('An error occurred: ' . $e->getMessage());
}

php

Setting up and using Laravel’s logging features :
Setting up and using Laravel’s logging features is crucial for monitoring and debugging your application effectively. Laravel provides a flexible logging system that allows you to log messages and errors to various channels, such as files, databases, or external services. Here’s how you can set up and use Laravel’s logging features:
1. Configuration:
Logging configuration is defined in the config/logging.php file. You can specify different log channels and their configurations, including the log storage location and the log level. By default, Laravel logs messages to the storage/logs directory. You can specify different log files and locations for each log channel.
2. Logging Messages:
You can log messages and errors using Laravel’s Log facade. The info, debug, warning, error, and critical methods are available to log messages with different log levels.

php

use Illuminate\Support\Facades\Log;

Log::info('This is an informational message.');
Log::error('An error occurred: Something went wrong.');

php

3. Custom Context:
You can include additional context data when logging messages. This can be helpful for providing more information about the logged events.
4. Logging Exceptions:
Laravel automatically logs exceptions that are not caught by your application’s exception handlers. Exceptions are logged at the error level by default.
5. Viewing Logs:
You can view logs using the storage/logs directory in your Laravel application. Log files are organized by date, and you can inspect them to troubleshoot issues and monitor application behavior.
6. Log Channels:
You can define multiple log channels in your configuration file, each with its own configuration settings. Channels can write logs to different destinations, such as files, databases, or external services.
7. Logging to External Services:
Laravel supports logging to external services like Slack, Papertrail, or Loggly. You can configure log channels to send log messages to these services for centralized logging and monitoring.
Conclusion:
By leveraging Laravel’s logging features, you can effectively monitor and debug your application, identify issues, and track important events. Logging provides valuable insights into your application’s behavior and helps you ensure that your application runs smoothly and reliably in production environments.

php

Log::info('User logged in', ['user_id' => $user->id]);

bash

Testing:

Testing in Laravel is an essential aspect of ensuring the reliability and stability of your application. Laravel provides robust support for writing automated tests using PHPUnit, allowing you to test various parts of your application, including routes, controllers, models, and more. Here’s an overview of testing in Laravel:
1. Testing Environment:
Laravel provides a dedicated testing environment that mirrors your application’s configuration but uses a separate database. This ensures that your tests do not affect your production or development databases.
2. Test Types:
Laravel supports different types of tests, including:
  • Feature Tests: These tests simulate user interactions with your application’s features. They typically test multiple parts of your application together, such as routes, controllers, and views.
  • Unit Tests: Unit tests focus on testing individual units of code, such as methods in controllers, models, or services. They help ensure that each unit of code behaves as expected in isolation.
3. Writing Tests:
You can write tests using Laravel’s testing helpers and assertions provided by PHPUnit. Laravel’s testing environment sets up the application and database automatically, allowing you to focus on writing tests.

php

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

php

4. Running Tests:
You can run tests using the php artisan test command. Laravel automatically discovers and runs tests located in the tests directory.
5. Mocking:
Laravel provides convenient methods for mocking dependencies in tests. This allows you to isolate the code under test and simulate behavior without interacting with external services or databases.
6. Continuous Integration:
You can integrate testing into your development workflow using continuous integration (CI) services like GitHub Actions, Travis CI, or CircleCI. These services automatically run your tests whenever you push code changes, ensuring that your application remains stable.
Conclusion:
Testing is a critical aspect of Laravel development, helping you ensure the reliability, stability, and maintainability of your application. By writing tests for your code and running them regularly, you can catch bugs early, refactor with confidence, and deliver high-quality software to your users. Laravel’s built-in testing features make it easy to write and run tests, allowing you to build robust applications with ease.

bash

php artisan test --filter ExampleTest

bash

Basics of testing in Laravel using PHPUnit:

Testing in Laravel using PHPUnit involves writing automated tests to verify that your application behaves as expected. PHPUnit is a popular testing framework for PHP, and Laravel provides built-in support for writing and running tests using PHPUnit. Here’s a basic overview of testing in Laravel using PHPUnit:
1. Directory Structure:
Laravel organizes tests in the tests directory. Within this directory, you’ll find the following subdirectories:
  • Feature: Contains feature tests that simulate user interactions with your application’s features.
  • Unit: Contains unit tests that focus on testing individual units of code in isolation.
  • Browser: Contains Dusk tests for browser automation testing.
2. Writing Tests:
a. Feature Tests:
Feature tests simulate user interactions with your application’s features. You can use Laravel’s testing helpers to interact with routes and HTTP requests and make assertions about the responses.

php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

php

b. Unit Tests:
Unit tests focus on testing individual units of code, such as methods in controllers, models, or services. You can use PHPUnit’s assertion methods to test the behavior of your code in isolation.

php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;

class ExampleTest extends TestCase
{
    public function testBasicTest()
    {
        $result = 1 + 1;

        $this->assertEquals(2, $result);
    }
}

php

3. Running Tests:
You can run tests using the php artisan test command. By default, Laravel runs all tests located in the tests directory.
4. Assertions:
PHPUnit provides a wide range of assertion methods for verifying the behavior of your code. Common assertion methods include assertEquals, assertTrue, assertFalse, assertArrayHasKey, and more.
Conclusion:
Writing tests using PHPUnit in Laravel allows you to ensure that your application behaves as expected and catches bugs early in the development process. By organizing tests into feature and unit tests and using PHPUnit’s assertion methods, you can build robust and reliable applications with confidence.

bash

php artisan test --filter ExampleTest

bash

CRUD Operations :
CRUD (Create, Read, Update, Delete) operations are fundamental to most web applications, allowing users to interact with and manipulate data. In Laravel, you can implement CRUD operations easily using the Eloquent ORM and Laravel’s built-in features. Here’s a basic overview of implementing CRUD operations in Laravel:
1. Create (Insert) Operation:
To create a new record in the database, follow these steps:

php

use App\Models\Post;

$post = new Post();
$post->title = 'New Post';
$post->content = 'Lorem ipsum dolor sit amet';
$post->save();

php

use App\Models\Post;

$post = Post::create([
    'title' => 'New Post',
    'content' => 'Lorem ipsum dolor sit amet',
]);
2. Read (Retrieve) Operation:
To retrieve records from the database, you can use various methods provided by Eloquent:

php

use App\Models\Post;

// Retrieve all posts
$posts = Post::all();

// Retrieve a single post by ID
$post = Post::find($id);

// Retrieve posts based on conditions
$posts = Post::where('category', 'news')->get();

php

3. Update Operation:
To update existing records in the database, follow these steps:

php

use App\Models\Post;

$post = Post::find($id);
$post->title = 'Updated Post';
$post->save();

use App\Models\Post;

Post::where('category', 'news')->update(['category' => 'updates']);

php

4. Delete Operation:
To delete records from the database, use the delete method:
Conclusion:
Implementing CRUD operations in Laravel is straightforward thanks to the Eloquent ORM and Laravel’s intuitive syntax. By following these basic examples, you can create, read, update, and delete records in your Laravel application with ease.

php

use App\Models\Post;

$post = Post::find($id);
$post->delete();


use App\Models\Post;

Post::destroy($id);

php

Dear learners, Are you interested in assessing your progress?
Request your mentor to give you access and start your Test.