Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Json encode and decode in livewire application

JSON Encode and Decode in Livewire application

Do you want to use JSON Encode and Decode in Livewire Laravel application?

insert record as JSON  database in livewire
store data as json fromat in livewire
json decode in livewire blade file
JSON encode and decode in livewire

This step-by-step tutorial helps you learn how to Insert and update records using JSON with Livewire in the Laravel application with the help of the JSON.

Why you should JSON Encode and Decode in Livewire

Sometimes we have more columns in our table in the database, and we don’t want to create a new table for storing the related data in the other table on behalf of a primary key.

So, we have simple or easiest options to store multiple text field data into a single column in JSON format.

We simply store all of the request parameters into a single variable as an associative array in the pair of keys and values and store it in JSON Format in the database table in the Livewire Laravel application.

routes\web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Livewire\Admin\CmsPages\ExhibitionProfilePage;


#Manage Echibition Profile page content
Route::get('/exhibitors-profile',ExhibitionProfilePage::class)->name('exhibitors.profile');

app\Http\Livewire\Admin\CmsPages

<?php

namespace App\Http\Livewire\Admin\CmsPages;

use Livewire\Component;
use App\Models\CmsPage;

class ExhibitionProfilePage extends Component
{
    public $state = [];

    public function mount()
    {
        $this->state = CmsPage::select('exhibition_profile_page_content')->first()->toArray();
        #Decode Json Content
        $jsonData = json_decode($this->state['exhibition_profile_page_content'], TRUE);
        #Set and return Json keys in array
        $content['contentSection1'] =  $jsonData['contentSection1'] ?? '';
        $content['contentSection2'] =  $jsonData['contentSection2'] ?? '';
        $this->state = $content;
    }

    public function updateExhibitorProfilePageDetails(){
        
        #Encode request parameters in Json 
        $collectionData  = json_encode([

            "contentSection1"  => $this->state['contentSection1'] ?? '',
            "contentSection2"  => $this->state['contentSection2'] ?? '',
        ]);

        $data = CmsPage::first();
        $data->exh_id  = '1';
        $data->exhibition_profile_page_content = $collectionData;
        $data->save();
        $this->dispatchBrowserEvent('hide-exhibition-form');
    }

    public function render()
    {
        return view('livewire.admin.cms-pages.exhibition-profile-page');
    }
}

resources\views\livewire\admin\exhibition-profile-page.blade.php

<div>
  <div class="row">
    <div class="col-md-12">
      <form wire:submit.prevent="updateExhibitorProfilePageDetails">
        <div class="card">
          <div class="card-body">
            <p>Fill Exhibition Profile page Content</p>
            <div class="row">
              <div class="col-md-6">
                <div wire:ignore class="form-group">
                  <label>AGRICULTURE</label>
                  <textarea wire:model.defer="state.contentSection1" id="contentSection1">
{!! $state['contentSection1'] ?? '' !!}</textarea>
                </div>
              </div>
              <div class="col-md-6">
                <div wire:ignore class="form-group">
                  <label>DAIRY & POULTRY</label>
                  <textarea wire:model.defer="state.contentSection2" id="contentSection2">
{!! $state['contentSection2'] ?? '' !!}</textarea>
                </div>
              </div>
            </div>
            <div class="d-flex">
              <button type="submit">Save Changes</button>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div> @push('js') <script>
  $('#contentSection1').summernote({
    placeholder: 'Input your text here...',
    tabsize: 2,
    height: 380,
    toolbar: [
      ['style', ['style']],
      ['font', ['bold', 'underline', 'clear']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['table', ['table']],
      ['insert', ['link', 'picture', 'video']],
      ['view', ['fullscreen', 'codeview', 'help']]
    ],
    callbacks: {
      onChange: function(contents, $editable) {
        console.log('onChange:', contents, $editable);
        @this.set('state.contentSection1', contents);
      }
    }
  });
  $('#contentSection2').summernote({
    placeholder: 'Input your text here...',
    tabsize: 2,
    height: 380,
    toolbar: [
      ['style', ['style']],
      ['font', ['bold', 'underline', 'clear']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['table', ['table']],
      ['insert', ['link', 'picture', 'video']],
      ['view', ['fullscreen', 'codeview', 'help']]
    ],
    callbacks: {
      onChange: function(contents, $editable) {
        console.log('onChange:', contents, $editable);
        @this.set('state.contentSection2', contents);
      }
    }
  });
</script> @endpush

Recomended article: How to use Summernote-editor in Livewire.

I hope that this article helped you learn to use of JSON in Livewire with an Example in Laravel. You may also want to check out our guide on Sweetalert2 delete confirmation in Livewire Example in the Laravel application.