PHP code example of drewlabs / laravexists

1. Go to this page and download the library: Download drewlabs/laravexists library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

drewlabs / laravexists example snippets


use Drewlabs\LaravExists\Exists;

//...

class MyRequest extends FormRequest {

    public function rules()
    {
        return [
            // ... validation rules
            'post_id' => [new Exists('posts', 'id')]
            // Or using the factory function
            'post_id' => [Exists::create('posts', 'id')]
        ]
    }
}


// Import the exist validation rule
use Drewlabs\LaravExists\Exists;
// Import the http existance client class
use Drewlabs\LaravExists\HTTPExistanceClient;

//...

class MyRequest extends FormRequest {

    public function rules()
    {
        return [
            // ... validation rules
            'post_id' => [
                Exists::create(
                    HTTPExistanceClient::create(
                        'http://localhost:3000/api/posts',
                    )->withBearerToken($this->bearerToken()),
                    // The attribute used for check on the ressult from the HTTP server
                    'id'
                )
            ]
        ]
    }
}

// Import the http existance client class
use Drewlabs\LaravExists\HTTPExistanceClient;

// ...
HTTPExistanceClient::create(
    '<RESOURCE_URL>',
    [], // Http headers
    // The response is a PHP object or array (dictionary)
    // $key is the column or key passed to the Exists construction
    // $value is the value provided by the user
    function($response, $key, $value) {
        // TODO, check if the response contains the data
        return true; // true or false base on the result of the previous step
    }
)
// ...

use Drewlabs\LaravExists\ExistanceVerifier;

class MyCustomVerifier implements ExistanceVerifier
{
    public function exists(string $column, $value)
    {
        // TODO: Provide existance verification implementation
    }
}

use Drewlabs\LaravExists\Exists;

// ...

class MyFormRequest
{

    public function rules()
    {
        return [
            // ...
            'post_id' => [new Exists('table', 'column', 'The selected post_id is invalid')]

            // In case using existance verifier
            'comment_id' => [new Exists(new InstanceClass, 'column', 'The selected post_id is invalid')]
        ]
    }
}