I have two related tables and I need to fetch some data using laravel's eloquent. Here's my table. I have created two models: User and UserCurrentPosition defining relation between those two.
User.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
public function position()
{
return $this->hasOne('App\UserCurrentPosition', 'user_id', 'id');
}
}
UserCurrentPosition.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class UserCurrentPosition extends Model
{
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
public function scopeDistance($query, $dist, $location)
{
return $query->select(DB::raw('ST_X(location) AS longitude, ST_Y(location) AS latitude, ST_DISTANCE_SPHERE(location, POINT('.$location.')) AS dist'))
->havingRaw('dist < '.$dist)
->orderBy('dist', 'ASC');
}
}
I intended to get name and phone from users table and longitude, latitude, and distance from the other table. Here's what i've done:
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\UserCurrentPosition;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Dingo\Api\Routing\Helpers;
class DriverController extends Controller
{
use Helpers;
public function __construct(User $user, UserCurrentPosition $userpos, UserDetail $userdetail)
{
$this->user = $user;
$this->userdetail = $userdetail;
$this->userpos = $userpos;
}
public function getNearby(Request $request)
{
$dist = $request->get('dist');
$lon = $request->get('lon');
$lat = $request->get('lat');
return $this->userpos
->with('user')
->distance($dist, $lon.', '.$lat)
->take(3)
->get()
->toJson();
}
}
But the output goes like this:
[
{
"longitude": 112.745978,
"latitude": -7.286319,
"dist": 5824.995681344659,
"user": null
},
{
"longitude": 112.744166,
"latitude": -7.310827,
"dist": 6862.04670609193,
"user": null
},
{
"longitude": 112.73957,
"latitude": -7.249031,
"dist": 7394.147599012171,
"user": null
}
]
I want to get user data along with longitude, latitude, and dist instead of "null". How do I do it?
Thanks in advance.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire