在laravel雄辩的响应中包含其他自定义属性

时间:2013-07-17 20:37:52

标签: laravel laravel-4

模型

class Profile extends Eloquent {

     public function user(){ return $this->belongsTo('User'); }

     public function url(){
        return URL::Route('profile', array('city_slug' => $this->city_slug, 'slug'=> $this->slug));
     }

}

控制器

class ProfileController extends BaseController {
    public function show($user_id)
    {
         $profile = Profile::with('user')->where('user_id', $user_id);
         return Response::json($profile, 200);
    }
}

我希望响应包含来自Profile方法url(){}

的生成的URL
{
    "id" : 1,
    "url" : /profile/{city_slug}/{slug},
    ....
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

我会反过来说。

在您的用户模型中...

public function profile()
{
    return $this->belongsTo('Profiles','profile_id');
}

然后您可以使用$profile = User::find(user_id)->profile

$data = array(
    'id' => $profile->id,
    'url' => "/profile/".$profile->city_slug."/".profile->slug
);

最后 return Repsonse::json($data,200);