新创建的模型与相关的表输出,然后到json

时间:2016-09-26 03:40:06

标签: laravel laravel-5

如何获取新创建的Contact模型的相关用户表,然后在响应头内容长度输出中将它放到json()。

public function store(Request $request) {

    try {

        $contact = new Contact();
        $contact->email_address = Helper::strip_tags($request->get('email_address'));
        $contact->firstname = ucfirst($request->get('firstname'));
        $contact->lastname = ucfirst($request->get('lastname'));
        $contact->company = ucfirst($request->get('company'));
        $contact->phone = $request->get('phone');
        $contact->mobile = $request->get('mobile');
        $contact->description = Helper::strip_tags($request->get('description'));                   

        if($contact->save()) {                  

            // here is the part I'm having trouble with

            $contact = $contact->with('user')->get();       

            return response()->json($contact, 200, ['Content-Length' => strlen($contact->toJson())]);

        } else {

            return response()->json(array('error' => true, 'messages' => $contact->errors), 400);       
        }

    } catch(Exception $e) {
        return response()->json(array('error' => true, 'type' => 'exception', 'message' => $e->getMessage()), 500, ['Content-Length' => $e->getMessage()]);
    }               

1 个答案:

答案 0 :(得分:0)

由于您已经加载了模型(当您创建模型时),因此您不会使用with作为急切加载关系。

如果我理解你的问题是正确的,为了获得输出中包含的User关系,你会使用“懒惰的预先加载”,这样你就可以$contact->load('user');

希望这有帮助!