vendredi 27 avril 2018

Get and updating JSON arrays

In a Laravel application, I store details about a user in another table called profiles and I decided it would be a good idea to store one column as a simple JSON array.

This column is called socialProfiles

Here is my index method of ProfilesController

public function index()
{
    $user = auth()->user(); 

    if($user)
    {
        $profile = $user->profile;

        if(!$profile)
        {

            // Define the social profiles array
            $socialProfiles = [
                'Facebook' => '',
                'Twitter' => ''
            ];

            $profile = new Profile();
            $profile->user_username = $user->username;
            $profile->mangedByUsername = $user->managedByUsername;
            $profile->socialProfiles = json_encode($socialProfiles);

            $profile->save();
        }

        $socialProfiles = json_decode($user->profile->socialProfiles, true);

        return view('editable.people.profile', compact('user', 'socialProfiles'));
    }

}

I set default values of nothing for both Facebook and Twitter and encode them as a JSON string, I then return the user and the profiles to the view.

In the view I have individual forms (within modals) that update different parts of a user profile, and they all go to the same method, because of this, my update function looks like this:

public function update(Request $request)
{
    // TODO: Add validation before updating or adding the profile
    $this->validate(request(), [
        'background' => 'min:1',
        'skills' => 'min:1',
    ]);

    $user = auth()->user();

    if($user)
    {
        // Only proceed if there is a logged in user
        $profile = $user->profile;

        // If there is no profile, create one for this user as they'll need one.
        if (!empty(request()->get('background')))
        {
            $profile->background = $request->get('background');
        } 

        if (!empty(request()->get('skills')))
        {
            $profile->skills = $request->get('skills');
        }

        if (!empty(request()->get('filepath')))
        {
            $profile->displayPicture = $request->get('filepath');
        }

        $profile->user_username = $user->username;

        $profile->save();

        return redirect()->back()->withSuccess('Your profile has been successfully updated');;
    }
}

If I'm going to be updating the social profile JSON array would i need to recreate the array, encode it and then save it?

The reason for the separate modals is because the design looks like this:

enter image description here

enter image description here

Should I have many separate update methods?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire