bhavin-gajjar/laravel-coder-lora-train huggingface dataset:
[Laravel 10] 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:

    use App\Service;
    use Mockery;
    use Mockery\MockInterface;

    public function test_something_can_be_mocked(): void
    {
        $this->instance(
            Service::class,
            Mockery::mock(Service::class, function (MockInterface $mock) {
                $mock->shouldReceive('process')->once();
            })
        );
    }

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 10] 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:

    <?php

    namespace Tests\Feature;

    use Illuminate\Support\Facades\Cache;
    use Tests\TestCase;

    class UserControllerTest extends TestCase
    {
        public function test_get_index(): void
        {
            Cache::shouldReceive('get')
                        ->once()
                        ->with('key')
                        ->andReturn('value');

            $response = $this->get('/users');

            // ...
        }
    }

> [!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 10] Explain mocking: Facade Spies

If you would like to spy on a facade, you may call the spy method on the corresponding facade. 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 Illuminate\Support\Facades\Cache;

    public function test_values_are_be_stored_in_cache(): void
    {
        Cache::spy();

        $response = $this->get('/');

        $response->assertStatus(200);

        Cache::shouldHaveReceived('put')->once()->with('name', 'Taylor', 10);
    }

<a name="interacting-with-time"></a>
[Laravel 10] 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 10] 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 10] 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 10] 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 10] 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 10] 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 10] Explain octane: FrankenPHP

> [!WARNING]  
> FrankenPHP's Octane integration is in beta and should be used with caution in production.

FrankenPHP is a PHP application server, written in Go, that supports modern web features like early hints 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 10] 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 10] 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 PHPUnit 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 10] 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>
[Laravel 10] Explain packages: Package Discovery

In a Laravel application's config/app.php configuration file, the providers option defines a list of service providers that should be loaded by Laravel. When someone installs your package, you will typically want your service provider to be included in this list. Instead of requiring users to manually add your service provider to the list, you may define the provider in the extra section of your package's composer.json file. In addition to service providers, you may also list any facades you would like to be registered:

Once your package has been configured for discovery, Laravel will automatically register its service providers and facades when it is installed, creating a convenient installation experience for your package's users.

<a name="opting-out-of-package-discovery"></a>
[Laravel 10] Explain pagination: Database: Pagination

- Introduction
- Basic Usage
    - Paginating Query Builder Results
    - Paginating Eloquent Results
    - Cursor Pagination
    - Manually Creating a Paginator
    - Customizing Pagination URLs
- Displaying Pagination Results
    - Adjusting the Pagination Link Window
    - Converting Results to JSON
- Customizing the Pagination View
    - Using Bootstrap
- Paginator and LengthAwarePaginator Instance Methods
- Cursor Paginator Instance Methods

<a name="introduction"></a>
[Laravel 10] Explain pagination: Introduction

In other frameworks, pagination can be very painful. We hope Laravel's approach to pagination will be a breath of fresh air. Laravel's paginator is integrated with the query builder and Eloquent ORM and provides convenient, easy-to-use pagination of database records with zero configuration.

By default, the HTML generated by the paginator is compatible with the Tailwind CSS framework; however, Bootstrap pagination support is also available.

<a name="tailwind-jit"></a>
[Laravel 10] Explain pagination: Paginating Query Builder Results

There are several ways to paginate items. The simplest is by using the paginate method on the query builder or an Eloquent query. The paginate method automatically takes care of setting the query's "limit" and "offset" based on the current page being viewed by the user. By default, the current page is detected by the value of the page query string argument on the HTTP request. This value is automatically detected by Laravel, and is also automatically inserted into links generated by the paginator.

In this example, the only argument passed to the paginate method is the number of items you would like displayed "per page". In this case, let's specify that we would like to display 15 items per page:

    <?php

    namespace App\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\DB;
    use Illuminate\View\View;

    class UserController extends Controller
    {
        /**
         * Show all application users.
         */
        public function index(): View
        {
            return view('user.index', [
                'users' => DB::table('users')->paginate(15)
            ]);
        }
    }

<a name="simple-pagination"></a>
[Laravel 10] Explain pagination: Simple Pagination

The paginate method counts the total number of records matched by the query before retrieving the records from the database. This is done so that the paginator knows how many pages of records there are in total. However, if you do not plan to show the total number of pages in your application's UI then the record count query is unnecessary.

Therefore, if you only need to display simple "Next" and "Previous" links in your application's UI, you may use the simplePaginate method to perform a single, efficient query:

    $users = DB::table('users')->simplePaginate(15);

<a name="paginating-eloquent-results"></a>
[Laravel 10] Explain passport: Laravel Passport

- Introduction
    - Passport or Sanctum?
- Installation
    - Deploying Passport
    - Migration Customization
    - Upgrading Passport
- Configuration
    - Client Secret Hashing
    - Token Lifetimes
    - Overriding Default Models
    - Overriding Routes
- Issuing Access Tokens
    - Managing Clients
    - Requesting Tokens
    - Refreshing Tokens
    - Revoking Tokens
    - Purging Tokens
- Authorization Code Grant With PKCE
    - Creating the Client
    - Requesting Tokens
- Password Grant Tokens
    - Creating a Password Grant Client
    - Requesting Tokens
    - Requesting All Scopes
    - Customizing the User Provider
    - Customizing the Username Field
    - Customizing the Password Validation
- Implicit Grant Tokens
- Client Credentials Grant Tokens
- Personal Access Tokens
    - Creating a Personal Access Client
    - Managing Personal Access Tokens
- Protecting Routes
    - Via Middleware
    - Passing the Access Token
- Token Scopes
    - Defining Scopes
    - Default Scope
    - Assigning Scopes to Tokens
    - Checking Scopes
- Consuming Your API With JavaScript
- Events
- Testing

<a name="introduction"></a>
[Laravel 10] Explain passport: Introduction

Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Andy Millington and Simon Hamp.

> [!WARNING]  
> This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general terminology and features of OAuth2 before continuing.

<a name="passport-or-sanctum"></a>
[Laravel 10] Explain passport: Passport or Sanctum?

Before getting started, you may wish to determine if your application would be better served by Laravel Passport or Laravel Sanctum. If your application absolutely needs to support OAuth2, then you should use Laravel Passport.

However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.

<a name="installation"></a>
[Laravel 10] Explain passport: Installation

To get started, install Passport via the Composer package manager:

Passport's service provider registers its own database migration directory, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store OAuth2 clients and access tokens:

Next, you should execute the passport:install Artisan command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens:

> [!NOTE]  
> If you would like to use UUIDs as the primary key value of the Passport Client model instead of auto-incrementing integers, please install Passport using the uuids option.

After running the passport:install command, add the Laravel\Passport\HasApiTokens trait to your App\Models\User model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes. If your model is already using the Laravel\Sanctum\HasApiTokens trait, you may remove that trait:

    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Passport\HasApiTokens;

    class User extends Authenticatable
    {
        use HasApiTokens, HasFactory, Notifiable;
    }

Finally, in your application's config/auth.php configuration file, you should define an api authentication guard and set the driver option to passport. This will instruct your application to use Passport's TokenGuard when authenticating incoming API requests:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

<a name="client-uuids"></a>
[Laravel 10] Explain passport: Client UUIDs

You may also run the passport:install command with the --uuids option present. This option will instruct Passport that you would like to use UUIDs instead of auto-incrementing integers as the Passport Client model's primary key values. After running the passport:install command with the --uuids option, you will be given additional instructions regarding disabling Passport's default migrations:

<a name="deploying-passport"></a>
[Laravel 10] Explain passwords: Introduction

Most web applications provide a way for users to reset their forgotten passwords. Rather than forcing you to re-implement this by hand for every application you create, Laravel provides convenient services for sending password reset links and secure resetting passwords.

> [!NOTE]  
> Want to get started fast? Install a Laravel application starter kit in a fresh Laravel application. Laravel's starter kits will take care of scaffolding your entire authentication system, including resetting forgotten passwords.

<a name="model-preparation"></a>
[Laravel 10] Explain passwords: Model Preparation

Before using the password reset features of Laravel, your application's App\Models\User model must use the Illuminate\Notifications\Notifiable trait. Typically, this trait is already included on the default App\Models\User model that is created with new Laravel applications.

Next, verify that your App\Models\User model implements the Illuminate\Contracts\Auth\CanResetPassword contract. The App\Models\User model included with the framework already implements this interface, and uses the Illuminate\Auth\Passwords\CanResetPassword trait to include the methods needed to implement the interface.

<a name="database-preparation"></a>
[Laravel 10] Explain passwords: Configuring Trusted Hosts

By default, Laravel will respond to all requests it receives regardless of the content of the HTTP request's Host header. In addition, the Host header's value will be used when generating absolute URLs to your application during a web request.

Typically, you should configure your web server, such as Nginx or Apache, to only send requests to your application that match a given host name. However, if you do not have the ability to customize your web server directly and need to instruct Laravel to only respond to certain host names, you may do so by enabling the App\Http\Middleware\TrustHosts middleware for your application. This is particularly important when your application offers password reset functionality.

To learn more about this middleware, please consult the TrustHosts middleware documentation.

<a name="routing"></a>
[Laravel 10] Explain pennant: Laravel Pennant

- Introduction
- Installation
- Configuration
- Defining Features
    - Class Based Features
- Checking Features
    - Conditional Execution
    - The HasFeatures Trait
    - Blade Directive
    - Middleware
    - In-Memory Cache
- Scope
    - Specifying the Scope
    - Default Scope
    - Nullable Scope
    - Identifying Scope
    - Serializing Scope
- Rich Feature Values
- Retrieving Multiple Features
- Eager Loading
- Updating Values
    - Bulk Updates
    - Purging Features
- Testing
- Adding Custom Pennant Drivers
    - Implementing the Driver
    - Registering the Driver
- Events

<a name="introduction"></a>