在Laravel中转换为字符串后保存纬度和经度

时间:2017-02-09 22:25:32

标签: laravel-5 geolocation

如何将lat和long正确转换为字符串并将其保存到db mysql?非常感谢任何帮助。

<?php namespace App\Http\Controllers;
        public function addLocation(Request $request){
            $address = NGO::all();
            $address->lat = $request['lat'];
            $address->lng = $request['lng'];
            $lat = $address->lat;
            $lng = $address->lng;
            $address = getaddress($lat,$lng);
            $address->save();

            return view('pages.Ngo.Add-New-Ngo-Scholar');
    }

    public function getaddress($lat,$lng)
    {
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
    $json = @file_get_contents($url);
    $data=json_decode($json);
    $status = $data->status;
    if($status=="OK")
    return $data->results[0]->formatted_address;
    else
    return false;
    }

1 个答案:

答案 0 :(得分:0)

您可以告诉Laravel始终将特定属性强制转换为字符串(或数组等)。你甚至可以转换为JSON(在db中它将json_encoded en保存为字符串)...

在模型中用于此用途:

protected $casts = [
        'attribute_name' => 'string'
    ];