vendredi 26 mai 2017

Laravel create and update model with foreign relationship

I currently have two tables namely storing users and clients. A client is related to a User in a one-to-one relationship.

I am currently storing and updating the models like so but it feels rather clunky...

 public function store(Request $request)
    {
        $requestData = $request->all();

        $user = new User();
        $user->fill($requestData);
        $user->save();

        $client = new Client;
        $client->fill($requestData);
        $client->user()->associate($user);
        $client->save();

        return response()->json($client->toArray(), 201, ['id' => $client->id]);
    }

    public function update(Request $request, $id)
    {
        try {
            $client = Client::findOrFail($id);
            $user = User::findOrFail($client->fk_user);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'error' => [
                    'message'   =>  'Client not found',
                ]
            ], 404);
        }

        $requestData = $request->all();

        $user->fill($requestData);
        $user->save();
        $client->fill($requestData);
        $client->user()->associate($user);
        $client->save();

        return response()->json($client->toArray(), 200);
    }

Is there a way to refactor this to avoid having to work with both users and clients as separate models. Is there a way to perhaps fill a client and in turn fill the parent user model?

Just wondering, thanks!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2r6UYa3
via IFTTT

Aucun commentaire:

Enregistrer un commentaire