简体   繁体   中英

Laravel/PHP JSON format from existing mySQL databse

I'm getting started with Laravel and PHP and I am using the 'Query Builder' methods in Laravel to query an existing mySQL database.

    public function showApi($id)
    {   
    $data = DB::table('Customers')->where('ID', $id)->get(); //Gets specific records

    return $data;
    }

This produces an Array of objects and the following JSON preview:

I am really looking for (and actually use to consuming) the following format:

Any help would be greatly appreciated.

The best way to change the properties of your models when they get converted into arrays (or json objects) is to override the toArray() method in your model. So if you don't already, you will have to start working with Eloquent models .

Your model - Customer.php

class Customer extends Eloquent {
    protected $table = 'Customer' // you'll need that because you're table differs from the convention ('customer')

    public function toArray(){
        $attributes = parent::toArray();
        $array = array();

        foreach($attributes as $key => $value){
            $newKey = snake_case($key);
            $array[$newKey] = $value;
        }

        return $array;
    }
}

What we're doing here is just getting the array of attributes from your parent and then looping through it and changing the key from StudlyCase to snake_case

If you need this functionality in all your models, it would be best to create a BaseModel which has this method and then let all the others extend from it.

In the end, your controller method would look like this:

public function showApi($id)
{   
    $customers = Customer::where('ID', $id)->get(); //Gets specific records

    return Response::json($customers);
}

Edit

As Marcin Nabiałek pointed out in the comments, your column ID is kind of special. Laravel would convert it into i_d . So to avoid that we need to exclude it

foreach($attributes as $key => $value){
    if($key == 'ID'){
        $array['id'] = $value;
    }
    else {
        $newKey = snake_case($key);
        $array[$newKey] = $value;
    }
}

If you have more of these "special cases" you can use the same method to handle them separately too...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM