Coder Social home page Coder Social logo

laravelpostcodes's Introduction

LaravelPostcodes

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

A service wrapper around postcodes.io with validation rule and macro

Install

Via Composer

$ composer require juststeveking/laravel-postcodes

After installation, merge configuration for services using:

$ php artisan vendor:publish --provider="JustSteveKing\LaravelPostcodes\PostcodesServiceProvider"

If, for some reason, this doesn't work please use the following steps:

  • Add the following into the config/services.php configuration file:
<?php

'postcodes' => [
    'url' => env('POSTCODES_URL', 'https://api.postcodes.io/')
],
  • Add POSTCODES_URL to your .env file and add https://api.postcodes.io/ as the value.

Basic Usage

You can use the validation rule:

<?php

$this->validate($request, [
    'postcode' => [
        'required',
        'string',
        new Postcode(resolve(PostcodeService::class))
    ]
]);

Or you can use the validation Macro:

$this->validate($request, [
    'postcode' => [
        'required',
        'string',
        Rule::postcode()
    ]
]);

If you want to interact with the service itself:

<?php 

use JustSteveKing\LaravelPostcodes\Service\PostcodeService;

class SomeController extends Controller
{
    protected $postcodes;

    public function __construct(PostcodeService $service)
    {
        $this->postcodes = $service;
    }

    public function store(Request $request)
    {
        // validation using example above
        $location = $this->postcodes->getPostcode($request->postcode);
    }
}

Or use the facade:

<?php 

class SomeController extends Controller
{
    public function store(Request $request)
    {
        // validation using example above
        $location = Postcode::getPostcode($request->postcode);
    }
}

Validate

<?php

$service = resolve(PostcodeService::class);

$service->validate('AB10 1AB');

// You can also use the facade:
Postcode::validate('AB10 1AB');

Validate Postcode

<?php

$service = resolve(PostcodeService::class);

$service->validate('AB10 1AB');

// You can also use the facade:
Postcode::validate('AB10 1AB');

Get Postcode information

<?php

$service = resolve(PostcodeService::class);

$service->getPostcode('AB10 1AB');

// You can also use the facade:
Postcode::getPostcode('AB10 1AB');

Bulk Lookup Postcodes

<?php

$service = resolve(PostcodeService::class);

$service->getPostcodes([
    'AB10 1AB',
    'AB10 1AF',
    'AB10 1AG',
]);

// You can also use the facade:
Postcode::getPostcodes([
    'AB10 1AB',
    'AB10 1AF',
    'AB10 1AG',
]);

Get nearest postcodes for a given longitude & latitude

<?php

$service = resolve(PostcodeService::class);

$service->nearestPostcodesForGivenLngAndLat(
    0.629806,
    51.792326
);

// You can also use the facade:
Postcode::nearestPostcodesForGivenLngAndLat(
    0.629806,
    51.792326
);

Nearest postcodes for postcode

<?php

$service = resolve(PostcodeService::class);

$service->nearest('AB10 1AB');

// You can also use the facade:
Postcode::nearest('AB10 1AB');

Autocomplete a postcode partial

<?php

$service = resolve(PostcodeService::class);

$service->autocomplete('AB10');

// You can also use the facade:
Postcode::autocomplete('AB10');

Query for postcode

<?php

$service = resolve(PostcodeService::class);

$service->query('AB10 1AB');

// You can also use the facade:
Postcode::query('AB10 1AB');

Lookup terminated postcode

<?php

$service = resolve(PostcodeService::class);

$service->getTerminatedPostcode('AB1 0AA');

// You can also use the facade:
Postcode::getTerminatedPostcode('AB1 0AA');

Lookup Outward Code

<?php

$service = resolve(PostcodeService::class);

$service->getOutwardCode('N11');

// You can also use the facade:
Postcode::getOutwardCode('N11');

Nearest outward code for outward code

<?php

$service = resolve(PostcodeService::class);

$limit = 80; // Limit needs to be less than 100
$radius = 15000; // Radius needs to be less than 25000
$service->getNearestOutwardCode('N11', $limit, $radius);

// You can also use the facade:
Postcode::getNearestOutwardCode('N11', $limit, $radius);

Get nearest outward codes for a given longitude & latitude

<?php

$service = resolve(PostcodeService::class);

$service->nearestOutwardCodesForGivenLngAndLat(
    0.629806,
    51.792326
);

// You can also use the facade:
Postcode::nearestOutwardCodesForGivenLngAndLat(
    0.629806,
    51.792326
);

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravelpostcodes's People

Contributors

ahosker avatar benjam-es avatar cmanish049 avatar ddziaduch avatar dnwjn avatar gemidio avatar jamesking56 avatar jamieshiers avatar jaybizzle avatar juststeveking avatar koenhoeijmakers avatar laravel-shift avatar nathandaly avatar simonbrahan avatar thinkverse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

laravelpostcodes's Issues

Is it possible to move the logic into a Request?

Working well with the following in my controller:

    //validate postcode first
    $service = resolve(PostcodeService::class);
    $this->validate($request, [
        'site_postcode' => [
            'required',
            'string',
            new Postcode($service),
        ],
    ]);

I'm trying to follow best practice and keep my request validation in a separate Request file, which i I call in my store method with dependency injection. Eg:

public function store(StoreProjectRequest $request) { ... }

Is there a good practice here for me to move the Postcode validation into this Request? Perhaps as a rule or as a separate function? Advice appreciated - thanks 👍

Convert all returns to return Collection instead off Array where appropriate

Detailed description

Looks like some of the functions return Laravel Collection and others return array or null if multiple results are returned. I propose we use one or another for consistency.

Context

Reasoning for moving to collections:

  • It is Laravel package and Collection is what most of API returns
  • Collections are easier to use
  • Collection can handle null response without braking code that uses Collection

Possible implementation

Turn:

    public function autocomplete(string $partialPostcode): ?array
    {
        return $this->getResponse("postcodes/$partialPostcode/autocomplete");
    }

Into

    public function autocomplete(string $partialPostcode): object
    {
        return collect($this->getResponse("postcodes/$partialPostcode/autocomplete"));
    }

Your environment

Update Postcode Service

Provide the ability to send GET or POST requests from the PostcodeService.

For this to be considered done, code quality and test coverage must be kept.

Make tests more stringent

Detailed description

Given that the tests don't actually make a request to the API—and I'm not suggesting they should, for what it's worth—it might be a good idea to make the tests a bit more stringent.

Context

It can be easy to add a new feature and add a typo to the endpoint without realising, and the tests would never be able to flag up an issue with it.

Possible implementation

In a package that I've created before, I make sure that the request URI also matches an expectation, by storing the last request ($this->lastRequest = $mock->getLastRequest())

public function testServiceCanGetPostcode()
{
    $service = $this->service(200, json_encode(['reuslt' => ['postcode' => $this->postcode]]));
    $result = $service->getPostcode($this->postcode);

    $this->assertEquals($result->postcode, $this->postcode);
    $this->assertEquals('postcode/N11 1QZ', (string) $this->lastRequest->getUri());
}

Array to string conversion warning on getPoscodes method

Detailed description

When calling getPostcodes without providing the second argument ($filter), an "Array to string conversion" warning is raised.

<warning>PHP Warning:  Array to string conversion in vendor/juststeveking/laravel-postcodes/src/Service/PostcodeService.php on line 97</warning>

Possible implementation

In the file

if (!empty($filter)) {
$filter = build_query(['filter' => implode(',', $filter)]);
}

Add the following:

} else {
    $filter = '';
}

So that $filter can be used as a string in the call below

return collect($this->getResponse(
'postcodes?' . $filter,
'POST',
['postcodes' => array_values($postcodes)]

Your environment

Include as many relevant details about the environment you experienced the bug in and how to reproduce it.

  • Version used (e.g. PHP 5.6, HHVM 3): PHP 8.0
  • Operating system and version (e.g. Ubuntu 16.04, Windows 7): macOS Monterey (12)
  • Link to your project: N/A
php artisan tinker
>>> $postcode_service = resolve(JustSteveKing\LaravelPostcodes\Service\PostcodeService::class);
>>> $postcode_service->getPostcodes(['SW1A 2AA']);
<warning>PHP Warning:  Array to string conversion in /Users/marcomarassi/Projects/car-parks-api-laravel/vendor/juststeveking/laravel-postcodes/src/Service/PostcodeService.php on line 97</warning>
...

Add support for PHP 8

Currently there is support for Laravel 8 in this package, but it doesn't support Laravel 8 running on PHP 8.

Whenever I am running composer commands, the platform requirement issues flash up.

A possible solution for this would be to add the |8.0 next to the current PHP version present in the composer.json

Query builder problem with Laravel 8

Hello and thanks for the awesome package!

I seem to have a problem with the query builder in Laravel 8.

I remember before it worked to search for a postcode as LE27HS or LE2 7HS, since the Laravel 8 upgrade it is only working if I search for it with proper formatting. Code below maybe you can have a suggestion for me.

Thanks,
Mihai

return $this->builder->whereHas('location', function ($query) use ($name) { $query->where('postcode', 'like', '%'.$name.'%') ->orWhere('city', $name) ->orWhere('region', $name); });

Unit tests make API calls

Detailed description

PostcodeServiceTest seems to make actual API calls, which is a bad practice for unit tests. We shouldn't need to hit an external API to test the project.

Context

If, for example, I wanted to run the unit tests offline, I can't because that test requires external access. Same for if the API went down.

Possible implementation

Create a mock for Guzzle client that responds in the same way the API would and give that to PostcodeService

Your environment

Irrelevant

Get Street from Postcode - Is this possible?

Hi,

When I use :

$postcodeService->getPostcode($request['site_postcode']);

I don't get the street and address. The nearest I get is admin_ward. Any thoughts on getting more granular data about the address or is this a limitation of the postcodes api?

Example returned:

{#440 ▼
  +"postcode": "SW7 1DL"
  +"quality": 1
  +"eastings": 527605
  +"northings": 179623
  +"country": "England"
  +"nhs_ha": "London"
  +"longitude": -0.162978
  +"latitude": 51.501148
  +"european_electoral_region": "London"
  +"primary_care_trust": "Westminster"
  +"region": "London"
  +"lsoa": "Westminster 019C"
  +"msoa": "Westminster 019"
  +"incode": "1DL"
  +"outcode": "SW7"
  +"parliamentary_constituency": "Cities of London and Westminster"
  +"admin_district": "Westminster"
  +"parish": "Westminster, unparished area"
  +"admin_county": null
  +"admin_ward": "Knightsbridge and Belgravia"
  +"ced": null
  +"ccg": "NHS Central London (Westminster)"
  +"nuts": "Westminster"
  +"codes": {#370 ▼
    +"admin_district": "E09000033"
    +"admin_county": "E99999999"
    +"admin_ward": "E05000637"
    +"parish": "E43000236"
    +"parliamentary_constituency": "E14000639"
    +"ccg": "E38000031"
    +"ccg_id": "09A"
    +"ced": "E99999999"
    +"nuts": "UKI32"
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.