bhavin-gajjar/laravel-coder-lora-train huggingface dataset:
[Laravel 11] Explain mcp: Laravel MCP

- Introduction
- Installation
    - Publishing Routes
- Creating Servers
    - Server Registration
    - Web Servers
    - Local Servers
- Tools
    - Creating Tools
    - Tool Input Schemas
    - Validating Tool Arguments
    - Tool Dependency Injection
    - Tool Annotations
    - Conditional Tool Registration
    - Tool Responses
- Prompts
    - Creating Prompts
    - Prompt Arguments
    - Validating Prompt Arguments
    - Prompt Dependency Injection
    - Conditional Prompt Registration
    - Prompt Responses
- Resources
    - Creating Resources
    - Resource URI and MIME Type
    - Resource Request
    - Resource Dependency Injection
    - Conditional Resource Registration
    - Resource Responses
- Authentication
    - OAuth 2.1
    - Sanctum
- Authorization
- Testing Servers
    - MCP Inspector
    - Unit Tests

<a name="introduction"></a>
[Laravel 11] Explain mcp: Creating Servers

You can create an MCP server using the make:mcp-server Artisan command. Servers act as the central communication point that exposes MCP capabilities like tools, resources, and prompts to AI clients:

This command will create a new server class in the app/Mcp/Servers directory. The generated server class extends Laravel MCP's base Laravel\Mcp\Server class and provides properties for registering tools, resources, and prompts:

<a name="server-registration"></a>
[Laravel 11] Explain middleware: Introduction

Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Additional middleware can be written to perform a variety of tasks besides authentication. For example, a logging middleware might log all incoming requests to your application. A variety of middleware are included in Laravel, including middleware for authentication and CSRF protection; however, all user-defined middleware are typically located in your application's app/Http/Middleware directory.

<a name="defining-middleware"></a>
[Laravel 11] Explain middleware: Defining Middleware

To create a new middleware, use the make:middleware Artisan command:

This command will place a new EnsureTokenIsValid class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied token input matches a specified value. Otherwise, we will redirect the users back to the /home URI:

    <?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Http\Request;
    use Symfony\Component\HttpFoundation\Response;

    class EnsureTokenIsValid
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
         */
        public function handle(Request $request, Closure $next): Response
        {
            if ($request->input('token') !== 'my-secret-token') {
                return redirect('/home');
            }

            return $next($request);
        }
    }

As you can see, if the given token does not match our secret token, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), you should call the $next callback with the $request.

It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

> [!NOTE]  
> All middleware are resolved via the service container, so you may type-hint any dependencies you need within a middleware's constructor.

<a name="middleware-and-responses"></a>
[Laravel 11] Explain middleware: Middleware and Responses

Of course, a middleware can perform tasks before or after passing the request deeper into the application. For example, the following middleware would perform some task **before** the request is handled by the application:

    <?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Http\Request;
    use Symfony\Component\HttpFoundation\Response;

    class BeforeMiddleware
    {
        public function handle(Request $request, Closure $next): Response
        {
            // Perform action

            return $next($request);
        }
    }

However, this middleware would perform its task **after** the request is handled by the application:

    <?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Http\Request;
    use Symfony\Component\HttpFoundation\Response;

    class AfterMiddleware
    {
        public function handle(Request $request, Closure $next): Response
        {
            $response = $next($request);

            // Perform action

            return $response;
        }
    }

<a name="registering-middleware"></a>
[Laravel 11] Explain middleware: Global Middleware

If you want a middleware to run during every HTTP request to your application, you may append it to the global middleware stack in your application's bootstrap/app.php file:

    use App\Http\Middleware\EnsureTokenIsValid;

    ->withMiddleware(function (Middleware $middleware) {
         $middleware->append(EnsureTokenIsValid::class);
    })

The $middleware object provided to the withMiddleware closure is an instance of Illuminate\Foundation\Configuration\Middleware and is responsible for managing the middleware assigned to your application's routes. The append method adds the middleware to the end of the list of global middleware. If you would like to add a middleware to the beginning of the list, you should use the prepend method.

<a name="manually-managing-laravels-default-global-middleware"></a>
[Laravel 11] Explain migrations: Database: Migrations

- Introduction
- Generating Migrations
    - Squashing Migrations
- Migration Structure
- Running Migrations
    - Rolling Back Migrations
- Tables
    - Creating Tables
    - Updating Tables
    - Renaming / Dropping Tables
- Columns
    - Creating Columns
    - Available Column Types
    - Column Modifiers
    - Modifying Columns
    - Renaming Columns
    - Dropping Columns
- Indexes
    - Creating Indexes
    - Renaming Indexes
    - Dropping Indexes
    - Foreign Key Constraints
- Events

<a name="introduction"></a>
[Laravel 11] Explain migrations: Introduction

Migrations are like version control for your database, allowing your team to define and share the application's database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you've faced the problem that database migrations solve.

The Laravel Schema facade provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems. Typically, migrations will use this facade to create and modify database tables and columns.

<a name="generating-migrations"></a>
[Laravel 11] Explain migrations: Generating Migrations

You may use the make:migration Artisan command to generate a database migration. The new migration will be placed in your database/migrations directory. Each migration filename contains a timestamp that allows Laravel to determine the order of the migrations:

Laravel will use the name of the migration to attempt to guess the name of the table and whether or not the migration will be creating a new table. If Laravel is able to determine the table name from the migration name, Laravel will pre-fill the generated migration file with the specified table. Otherwise, you may simply specify the table in the migration file manually.

If you would like to specify a custom path for the generated migration, you may use the --path option when executing the make:migration command. The given path should be relative to your application's base path.

> [!NOTE]  
> Migration stubs may be customized using stub publishing.

<a name="squashing-migrations"></a>
[Laravel 11] Explain migrations: Dump the current database schema and prune all existing migrations...

php artisan schema:dump --prune
shell
php artisan schema:dump
php artisan schema:dump --database=testing --prune
```

You should commit your database schema file to source control so that other new developers on your team may quickly create your application's initial database structure.

> [!WARNING]  
> Migration squashing is only available for the MariaDB, MySQL, PostgreSQL, and SQLite databases and utilizes the database's command-line client.

<a name="migration-structure"></a>
[Laravel 11] Explain mix: Introduction

Laravel Mix, a package developed by Laracasts creator Jeffrey Way, provides a fluent API for defining webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors.

In other words, Mix makes it a cinch to compile and minify your application's CSS and JavaScript files. Through simple method chaining, you can fluently define your asset pipeline. For example:

If you've ever been confused and overwhelmed about getting started with webpack and asset compilation, you will love Laravel Mix. However, you are not required to use it while developing your application; you are free to use any asset pipeline tool you wish, or even none at all.

> [!NOTE]  
> Vite has replaced Laravel Mix in new Laravel installations. For Mix documentation, please visit the official Laravel Mix website. If you would like to switch to Vite, please see our Vite migration guide.
[Laravel 11] Explain mocking: Introduction

When testing Laravel applications, you may wish to "mock" certain aspects of your application so they are not actually executed during a given test. For example, when testing a controller that dispatches an event, you may wish to mock the event listeners so they are not actually executed during the test. This allows you to only test the controller's HTTP response without worrying about the execution of the event listeners since the event listeners can be tested in their own test case.

Laravel provides helpful methods for mocking events, jobs, and other facades out of the box. These helpers primarily provide a convenience layer over Mockery so you do not have to manually make complicated Mockery method calls.

<a name="mocking-objects"></a>
[Laravel 11] Explain mocking: Mocking Objects

When mocking an object that is going to be injected into your application via Laravel's service container, you will need to bind your mocked instance into the container as an instance binding. This will instruct the container to use your mocked instance of the object instead of constructing the object itself:

In order to make this more convenient, you may use the mock method that is provided by Laravel's base test case class. For example, the following example is equivalent to the example above:

    use App\Service;
    use Mockery\MockInterface;

    $mock = $this->mock(Service::class, function (MockInterface $mock) {
        $mock->shouldReceive('process')->once();
    });

You may use the partialMock method when you only need to mock a few methods of an object. The methods that are not mocked will be executed normally when called:

    use App\Service;
    use Mockery\MockInterface;

    $mock = $this->partialMock(Service::class, function (MockInterface $mock) {
        $mock->shouldReceive('process')->once();
    });

Similarly, if you want to spy on an object, Laravel's base test case class offers a spy method as a convenient wrapper around the Mockery::spy method. Spies are similar to mocks; however, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed:

    use App\Service;

    $spy = $this->spy(Service::class);

    // ...

    $spy->shouldHaveReceived('process');

<a name="mocking-facades"></a>
[Laravel 11] Explain mocking: Mocking Facades

Unlike traditional static method calls, facades (including real-time facades) may be mocked. This provides a great advantage over traditional static methods and grants you the same testability that you would have if you were using traditional dependency injection. When testing, you may often want to mock a call to a Laravel facade that occurs in one of your controllers. For example, consider the following controller action:

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Support\Facades\Cache;

    class UserController extends Controller
    {
        /**
         * Retrieve a list of all users of the application.
         */
        public function index(): array
        {
            $value = Cache::get('key');

            return [
                // ...
            ];
        }
    }

We can mock the call to the Cache facade by using the shouldReceive method, which will return an instance of a Mockery mock. Since facades are actually resolved and managed by the Laravel service container, they have much more testability than a typical static class. For example, let's mock our call to the Cache facade's get method:

> [!WARNING]  
> You should not mock the Request facade. Instead, pass the input you desire into the HTTP testing methods such as get and post when running your test. Likewise, instead of mocking the Config facade, call the Config::set method in your tests.

<a name="facade-spies"></a>
[Laravel 11] Explain mongodb: Introduction

MongoDB is one of the most popular NoSQL document-oriented database, used for its high write load (useful for analytics or IoT) and high availability (easy to set replica sets with automatic failover). It can also shard the database easily for horizontal scalability and has a powerful query language for doing aggregation, text search or geospatial queries.

Instead of storing data in tables of rows or columns like SQL databases, each record in a MongoDB database is a document described in BSON, a binary representation of the data. Applications can then retrieve this information in a JSON format. It supports a wide variety of data types, including documents, arrays, embedded documents, and binary data.

Before using MongoDB with Laravel, we recommend installing and using the mongodb/laravel-mongodb package via Composer. The laravel-mongodb package is officially maintained by MongoDB, and while MongoDB is natively supported by PHP through the MongoDB driver, the Laravel MongoDB package provides a richer integration with Eloquent and other Laravel features:

<a name="installation"></a>
[Laravel 11] Explain mongodb: MongoDB Driver

To connect to a MongoDB database, the mongodb PHP extension is required. If you are developing locally using Laravel Herd or installed PHP via php.new, you already have this extension installed on your system. However, if you need to install the extension manually, you may do so via PECL:

For more information on installing the MongoDB PHP extension, check out the MongoDB PHP extension installation instructions.

<a name="starting-a-mongodb-server"></a>
[Laravel 11] Explain mongodb: Starting a MongoDB Server

The MongoDB Community Server can be used to run MongoDB locally and is available for installation on Windows, macOS, Linux, or as a Docker container. To learn how to install MongoDB, please refer to the official MongoDB Community installation guide.

The connection string for the MongoDB server can be set in your .env file:

For hosting MongoDB in the cloud, consider using MongoDB Atlas.
To access a MongoDB Atlas cluster locally from your application, you will need to add your own IP address in the cluster's network settings to the project's IP Access List.

The connection string for MongoDB Atlas can also be set in your .env file:

<a name="install-the-laravel-mongodb-package"></a>
[Laravel 11] Explain notifications: Notifications

- Introduction
- Generating Notifications
- Sending Notifications
    - Using the Notifiable Trait
    - Using the Notification Facade
    - Specifying Delivery Channels
    - Queueing Notifications
    - On-Demand Notifications
- Mail Notifications
    - Formatting Mail Messages
    - Customizing the Sender
    - Customizing the Recipient
    - Customizing the Subject
    - Customizing the Mailer
    - Customizing the Templates
    - Attachments
    - Adding Tags and Metadata
    - Customizing the Symfony Message
    - Using Mailables
    - Previewing Mail Notifications
- Markdown Mail Notifications
    - Generating the Message
    - Writing the Message
    - Customizing the Components
- Database Notifications
    - Prerequisites
    - Formatting Database Notifications
    - Accessing the Notifications
    - Marking Notifications as Read
- Broadcast Notifications
    - Prerequisites
    - Formatting Broadcast Notifications
    - Listening for Notifications
- SMS Notifications
    - Prerequisites
    - Formatting SMS Notifications
    - Unicode Content
    - Customizing the "From" Number
    - Adding a Client Reference
    - Routing SMS Notifications
- Slack Notifications
    - Prerequisites
    - Formatting Slack Notifications
    - Slack Interactivity
    - Routing Slack Notifications
    - Notifying External Slack Workspaces
- Localizing Notifications
- Testing
- Notification Events
- Custom Channels

<a name="introduction"></a>
[Laravel 11] Explain notifications: Introduction

In addition to support for sending email, Laravel provides support for sending notifications across a variety of delivery channels, including email, SMS (via Vonage, formerly known as Nexmo), and Slack. In addition, a variety of community built notification channels have been created to send notifications over dozens of different channels! Notifications may also be stored in a database so they may be displayed in your web interface.

Typically, notifications should be short, informational messages that notify users of something that occurred in your application. For example, if you are writing a billing application, you might send an "Invoice Paid" notification to your users via the email and SMS channels.

<a name="generating-notifications"></a>
[Laravel 11] Explain notifications: Generating Notifications

In Laravel, each notification is represented by a single class that is typically stored in the app/Notifications directory. Don't worry if you don't see this directory in your application - it will be created for you when you run the make:notification Artisan command:

This command will place a fresh notification class in your app/Notifications directory. Each notification class contains a via method and a variable number of message building methods, such as toMail or toDatabase, that convert the notification to a message tailored for that particular channel.

<a name="sending-notifications"></a>
[Laravel 11] Explain notifications: Using the Notifiable Trait

Notifications may be sent in two ways: using the notify method of the Notifiable trait or using the Notification facade. The Notifiable trait is included on your application's App\Models\User model by default:

    <?php

    namespace App\Models;

    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;

    class User extends Authenticatable
    {
        use Notifiable;
    }

The notify method that is provided by this trait expects to receive a notification instance:

    use App\Notifications\InvoicePaid;

    $user->notify(new InvoicePaid($invoice));

> [!NOTE]
> Remember, you may use the Notifiable trait on any of your models. You are not limited to only including it on your User model.

<a name="using-the-notification-facade"></a>
[Laravel 11] Explain notifications: Using the Notification Facade

Alternatively, you may send notifications via the Notification facade. This approach is useful when you need to send a notification to multiple notifiable entities such as a collection of users. To send notifications using the facade, pass all of the notifiable entities and the notification instance to the send method:

    use Illuminate\Support\Facades\Notification;

    Notification::send($users, new InvoicePaid($invoice));

You can also send notifications immediately using the sendNow method. This method will send the notification immediately even if the notification implements the ShouldQueue interface:

    Notification::sendNow($developers, new DeploymentCompleted($deployment));

<a name="specifying-delivery-channels"></a>
[Laravel 11] Explain octane: Laravel Octane

- Introduction
- Installation
- Server Prerequisites
    - FrankenPHP
    - RoadRunner
    - Swoole
- Serving Your Application
    - Serving Your Application via HTTPS
    - Serving Your Application via Nginx
    - Watching for File Changes
    - Specifying the Worker Count
    - Specifying the Max Request Count
    - Reloading the Workers
    - Stopping the Server
- Dependency Injection and Octane
    - Container Injection
    - Request Injection
    - Configuration Repository Injection
- Managing Memory Leaks
- Concurrent Tasks
- Ticks and Intervals
- The Octane Cache
- Tables

<a name="introduction"></a>
[Laravel 11] Explain octane: FrankenPHP

FrankenPHP is a PHP application server, written in Go, that supports modern web features like early hints, Brotli, and Zstandard compression. When you install Octane and choose FrankenPHP as your server, Octane will automatically download and install the FrankenPHP binary for you.

<a name="frankenphp-via-laravel-sail"></a>
[Laravel 11] Explain octane: FrankenPHP via Laravel Sail

If you plan to develop your application using Laravel Sail, you should run the following commands to install Octane and FrankenPHP:

Next, you should use the octane:install Artisan command to install the FrankenPHP binary:

Finally, add a SUPERVISOR_PHP_COMMAND environment variable to the laravel.test service definition in your application's docker-compose.yml file. This environment variable will contain the command that Sail will use to serve your application using Octane instead of the PHP development server:

To enable HTTPS, HTTP/2, and HTTP/3, apply these modifications instead:

Typically, you should access your FrankenPHP Sail application via https://localhost, as using https://127.0.0.1 requires additional configuration and is discouraged.

<a name="frankenphp-via-docker"></a>
[Laravel 11] Explain packages: Introduction

Packages are the primary way of adding functionality to Laravel. Packages might be anything from a great way to work with dates like Carbon or a package that allows you to associate files with Eloquent models like Spatie's Laravel Media Library.

There are different types of packages. Some packages are stand-alone, meaning they work with any PHP framework. Carbon and Pest are examples of stand-alone packages. Any of these packages may be used with Laravel by requiring them in your composer.json file.

On the other hand, other packages are specifically intended for use with Laravel. These packages may have routes, controllers, views, and configuration specifically intended to enhance a Laravel application. This guide primarily covers the development of those packages that are Laravel specific.

<a name="a-note-on-facades"></a>
[Laravel 11] Explain packages: A Note on Facades

When writing a Laravel application, it generally does not matter if you use contracts or facades since both provide essentially equal levels of testability. However, when writing packages, your package will not typically have access to all of Laravel's testing helpers. If you would like to be able to write your package tests as if the package were installed inside a typical Laravel application, you may use the Orchestral Testbench package.

<a name="package-discovery"></a>