1

Using Laravel 5.6, we are currently writing an API that will accept input from various sources. Some sources expect to pass data in certain ways, other than the rest. I'd like our API to be as flexible as possible so we're willing to accept more than one name for a field.

For instance, if we store a first name in our table, we would store it as first_name. However some apis might pass it as firstname, or even firstName.

I can, (and currently am), on Input checking for the existence of the other field names, and if they exist, copying the contents of the other field name into the expected field name.

Here's a rough example (not exactly how we're doing it but close enough):

if (Input::has('firstname')) {
    Input::merge(['first_name'=>Input::get('firstname')]);
}

As you can see, that's pretty dirty and overtime will result in issues and become unwieldy.

One option that helps, esp with columns that have multiple possible names is to do something like the following:

$first_names = ['firstname', 'firstName', 'name1'];
foreach ($first_names as $name) {
    if (Input::has($name)) {
        Input::merge(['firstname'=>$name]);
        break;
    }    
}

I don't see any methods that might make it much easier (we can even wrap a wrapper around it so we can pass an array of possible names and the expected field name), however it's always possible to overlook a much easier solution or not know about certain functionality.

Is there an easier/more robust way of doing the above?

1 Answer 1

1

The "null coalescing operator", new to PHP 7.0, enables you to do something like this. I.e. if the first input is set, use that, if not use the second one.

$firstname = Input::get('firstname') ?? Input::get('firstName');

From the docs...

Coalescing can be chained: this will return the first defined value out of $_GET['user'], $_POST['user'], and 'nobody'.

$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';

You can either put the null coalescing operator inside the merge(), if that's possible, or you can do something like this...

$firstname = Input::get('firstname') ?? Input::get('firstName') ?? Input::get('name1');
Input::merge(['first_name'=>$firstname]);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, thanks! I didn't realize they had added this :). Unfortunately since I'm a new user I can't upvote you. I'll keep it open for a couple of days and then accept your answer, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.