Lompat ke konten Lompat ke sidebar Lompat ke footer

Cara Menggunakan Controller dan Input Data Livewire Laravel 10

 sebagai cacatan


pada route web.php

use App\Livewire\Dashboard\Guru\Siswa;
Route::get('/dashboard/data-siswa', Siswa::class)->name('dashboard.siswa');


buat blade & controller dengan livewire

php artisan make:livewire Dashboard/Guru/Siswa


otomatis terbuat controller dan blade layout di dalam Dashboard/Guru/Siswa

isikan blade 

@section('siswa-active') active @endsection

@section('breadcrumb')
<ol class="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5">
  <li class="breadcrumb-item text-sm"><a class="text-white opacity-7" href="javascript:;">Dashboard</a></li>
  <li class="breadcrumb-item text-sm text-white active" aria-current="page">Data Siswa</li>
</ol>
@endsection

@section('css')
<style>
  tbody tr td
  {
    vertical-align: middle;
  }  
</style>
@endsection

<div id="background" class="dark-shadow-r4 mt-5 py-2">

  {{-- Toast Notification --}}
    {{-- Failed Notification --}}
      <button type="button" class="btn btn-primary d-none" id="failedToastBtn">Show live toast</button>

      <div wire:ignore class="toast-container position-fixed end-0 px-4">
        <div id="failedToast" class="toast dark-shadow-r0 p-1" role="alert" aria-live="assertive" aria-atomic="true">
          <div class="toast-body bg-white"
          style="border-left: 5px solid #d75452;">
            <div class="d-flex align-items-start">

              <div class="font-poppins ms-2" style="color: #48484896;">
                <div class="d-flex flex-column align-items-start">

                  <div class="d-flex align-items-center">
                    <div class="font-poppins me-2 text-danger"
                    style="font-size: 18px;">
                      Failed
                    </div>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="#d75452" style="height: 25px; width: 25px;">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </div>

                  <div style="font-size: 14px;" style="white-space: normal; word-wrap: break-word">
                    <textarea wire:model.live="notification_message" style="resize: none;" class="border-0 bg-white" cols="30" rows="{{ $notification_row }}" disabled></textarea>
                  </div>
                </div>
              </div>

              <button type="button" class="btn text-dark p-0 ms-auto" data-bs-dismiss="toast" aria-label="Close">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="height: 25px; width: 25px;">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          </div>
        </div>

      </div>
    {{-- End --}}

    {{--  Success Notification --}}
      <button type="button" class="btn btn-primary d-none" id="successToastBtn">Show live toast</button>

      <div wire:ignore class="toast-container position-fixed end-0 px-4">
        <div id="successToast" class="toast dark-shadow-r0 p-1" role="alert" aria-live="assertive" aria-atomic="true">
          <div class="toast-body bg-white"
          style="border-left: 5px solid #64BF6A;">
            <div class="d-flex align-items-start">

              <div class="font-poppins ms-2" style="color: #48484896;">
                <div class="d-flex flex-column align-items-start">

                  <div class="d-flex align-items-center">
                    <div class="font-poppins me-2 text-success"
                    style="font-size: 18px;">
                      Success
                    </div>

                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="#64BF6A" style="height: 25px; width: 25px;">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </div>

                  <div style="font-size: 14px;" style="white-space: normal; word-wrap: break-word">
                    <textarea wire:model.live="notification_message" style="resize: none;" class="border-0 bg-white" cols="30" rows="{{ $notification_row }}" disabled></textarea>
                  </div>
                </div>
              </div>

              <button type="button" class="btn text-dark p-0 ms-auto" data-bs-dismiss="toast" aria-label="Close">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="height: 25px; width: 25px;">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    {{-- End --}}
  {{-- End --}}

  <div class="px-3">
    <div class="d-flex justify-content-between align-items-center">
      <button type="button" class="btn btn-success mt-2" data-bs-toggle="modal" data-bs-target="#tambahData">
        Tambah Data
      </button>
    </div>
  </div>

  <!-- Isi -->
  <div class="px-3">
    <div class="table-responsive table-responsive-sm table-responsive-md table-responsive-lg table-responsive-xl border border-dark">
      <table class="table text-center">
        <thead class="bg-secondary text-white">
          <tr>
            <td>No</td>
            <td>NIS</td>
            <td>NISN</td>
            <td>Nama Siswa</td>
            <td>Tahun Masuk</td>
            <td>Tahun keluar</td>
            <td>No Telp</td>
            <td>status</td>
            <td>alamat</td>

            <td>Opsi</td>
          </tr>
        </thead>
     
        <tbody>
          @if($siswadata->count() > 0)
            @foreach($siswadata as $data)
              <tr>
                <td>{{ $loop->index + 1 }}.</td>
                <td>{{ $data->nis }}</td>
                <td>{{ $data->nisn }}</td>
                <td>{{ $data->nama_siswa }}</td>
                <td>{{ $data->tahun_masuk }}</td>
                <td>{{ $data->tahun_keluar }}</td>
                <td>{{ $data->no_telp }}</td>
                <td>{{ $data->status }}</td>
                <td>{{ $data->alamat }}</td>
                <td>
                  <div class="d-flex align-items-center justify-content-center">
                    <button type="button" class="btn btn-sm btn-danger mt-2 me-2" data-bs-toggle="modal" data-bs-target="#deleteData" wire:click="edit({{ $data->id }})">
                      Hapus Data
                    </button>
                    <button type="button" class="btn btn-sm btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#editData" wire:click="edit({{ $data->id }})">
                      Edit Data
                    </button>
                  </div>                
                </td>
              </tr>
            @endforeach
          @else
            <tr>
              <td colspan="3">
                Data Kosong  
              </td>
            </tr>
          @endif
        </tbody>
      </table>
    </div>
  </div>

  <!-- Modal Tambah Data -->
    <div wire:ignore.self class="modal fade" id="tambahData" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header bg-success text-white">
            <h5 class="modal-title text-white" id="exampleModalLabel">Tambah Data</h5>

            <button type="button" id="closeAdd" class="btn-close" data-bs-dismiss="modal" aria-label="Close">  
            </button>
          </div>
          <div class="modal-body">
            <div class="form-group">

            <div class="mb-3">
                <label class="font-weight-bold">NIS</label>
                <input type="text" class="form-control border border-dark" wire:model="nis">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">NISN</label>
              <input type="text" class="form-control border border-dark" wire:model="nisn">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">Nama Siswa</label>
              <input type="text" class="form-control border border-dark" wire:model="nama_siswa">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">Tahun Masuk</label>
              <input type="text" class="form-control border border-dark" wire:model="tahun_masuk">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">No Telp</label>
              <input type="text" class="form-control border border-dark" wire:model="no_telp">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">Status</label>
              <input type="text" class="form-control border border-dark" wire:model="status">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">Alamat</label>
              <input type="text" class="form-control border border-dark" wire:model="alamat">
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="reset" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-success" wire:click="store">Tambah</button>          
          </div>
        </div>
      </div>
    </div>
  <!-- End -->

  <!-- Modal Hapus Data -->
    <div wire:ignore.self class="modal fade" id="deleteData" aria-hidden="true" aria-labelledby="exampleModalToggleLabel" tabindex="-1">
      <div class="modal-dialog modal-dialog-scrollable">

        <center>
        <div class="p-3 bg-danger text-white" style="width: fit-content; border-radius: 100%;">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="height: 35px; width: 35px;">
            <path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
          </svg>
        </div>
        </center>

        <div class="modal-content" style="margin-top: -2.2em; z-index: -99;">
          <div class="p-1 btn-danger"></div>


          <div class="modal-body" style="margin-top: 1.5em;">
            <center>
              <div class="font-poppins text-danger" style="font-size: 22px;"> Hapus Data ? </div>
              <div class="font-poppins text-grey"> Apakah Anda Yakin <br> Ingin Menghapus Data Ini ? </div>
            </center>
          </div>

          <div class="p-3">
            <div class="d-flex align-items-center">
              <button type="button" id="closeDelete" class="btn btn-secondary w-100 me-2" data-bs-dismiss="modal">Tutup</button>
              <button type="button" class="btn btn-danger w-100" wire:click="delete">Hapus Data</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  <!-- End -->

  <!-- Modal Edit Data -->
  <div wire:ignore.self class="modal fade" id="editData" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header bg-primary text-white">
            <h5 class="modal-title text-white" id="exampleModalLabel">Edit Data</h5>

            <button type="button" id="closeEdit" class="btn-close" data-bs-dismiss="modal" aria-label="Close">  
            </button>
          </div>
          <div class="modal-body">
            <div class="form-group">

              <div class="mb-3">
              <label class="font-weight-bold">Tahun Keluar</label>
              <input type="text" class="form-control border border-dark" wire:model="tahun_keluar">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">No Telp</label>
              <input type="text" class="form-control border border-dark" wire:model="no_telp">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">Status</label>
              <input type="text" class="form-control border border-dark" wire:model="status">
              </div>

              <div class="mb-3">
              <label class="font-weight-bold">Alamat</label>
              <input type="text" class="form-control border border-dark" wire:model="alamat">
              </div>
             
            </div>
          </div>
          <div class="modal-footer">
            <button type="reset" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary" wire:click="update">Update</button>          
          </div>
        </div>
      </div>
    </div>
  <!-- End -->  
</div>

@section('js')
<script>
  document.addEventListener('livewire:initialized', () =>
  {
    @this.on('dataSuccess', (event) =>
    {
      document.getElementById("closeAdd").click();
      document.getElementById("closeDelete").click();
      document.getElementById("closeEdit").click();
      document.getElementById("successToastBtn").click();
    });

    @this.on('dataFailed', (event) =>
    {
      document.getElementById("closeAdd").click();
      document.getElementById("closeDelete").click();
      document.getElementById("closeEdit").click();
      document.getElementById("failedToastBtn").click();
    });
  });
</script>
@endsection


fungsi dari @section('siswa-active') active @endsection

mengambil dari route layout blade sidebar yg di hubungkan ke web.php 

pada sidebar <a class="nav-link @yield('siswa-active')" href="{{ route('dashboard.siswa') }}">

pada web.php dashboard.siswa

Route::get('/dashboard/data-siswa', Siswa::class)->name('dashboard.siswa');


pada @section('breadcrumb')

agar bredcrum berubah mengambil layout dari folder layout/dashboard

pada

@section('css')
<style>
  tbody tr td
  {
    vertical-align: middle;
  }  
</style>
@endsection

untuk menaruh css pada 1 link/layout itu saja, tidak gabung

pada {{ $notification_row }}

untuk menampikan notifikasi yg di kirimkan ke kontroller siswa

public $notification_message, $notification_row;

codingan dari ini 

$siswadata->count() > 0 yg artinya mulai dari 1, bukan default 0   

@foreach($siswadata as $data) mengambil dari kontroller variable siswadata    di kontroller $siswadata pada method public function render()

lalu diteruskan ke blade dengan menggunakan compact('siswadata')

yg di terruskan seperti ini 

    public function render()
    {
        $siswadata = SiswaModel::orderBy('created_at', 'DESC')->get();
        return view('livewire.dashboard.guru.siswa', compact('siswadata'))->layout('layouts.dashboard');
    }
full nya seperti dibawah

@if($siswadata->count() > 0)
            @foreach($siswadata as $data)
              <tr>
                <td>{{ $loop->index + 1 }}.</td>
                <td>{{ $data->nis }}</td>
                <td>{{ $data->nisn }}</td>
                <td>{{ $data->nama_siswa }}</td>
                <td>{{ $data->tahun_masuk }}</td>
                <td>{{ $data->tahun_keluar }}</td>
                <td>{{ $data->no_telp }}</td>
                <td>{{ $data->status }}</td>
                <td>{{ $data->alamat }}</td>
                <td>
                  <div class="d-flex align-items-center justify-content-center">
                    <button type="button" class="btn btn-sm btn-danger mt-2 me-2" data-bs-toggle="modal" data-bs-target="#deleteData" wire:click="edit({{ $data->id }})">
                      Hapus Data
                    </button>
                    <button type="button" class="btn btn-sm btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#editData" wire:click="edit({{ $data->id }})">
                      Edit Data
                    </button>
                  </div>                
                </td>
              </tr>
            @endforeach
          @else
            <tr>
              <td colspan="3">
                Data Kosong  
              </td>
            </tr>
          @endif

modal 

<!-- Modal Tambah Data -->

berufngsi untuk menampilkan dalam 1 halaman saja. tanpa perlu menggunakan 2 controoler. (bawaan template argon)


dengan menggunakan livewire fungsi input tambah wire:model=

pada input seperti ini

            <div class="mb-3">
                <label class="font-weight-bold">NIS</label>
                <input type="text" class="form-control border border-dark" wire:model="nis">
              </div>

dan fungsi dari tombol popup delete seperti ini

wire:click="delete"

untuk js notifikasi setelah penggyunakan tombol 

@section('js')
<script>
  document.addEventListener('livewire:initialized', () =>
  {
    @this.on('dataSuccess', (event) =>
    {
      document.getElementById("closeAdd").click();
      document.getElementById("closeDelete").click();
      document.getElementById("closeEdit").click();
      document.getElementById("successToastBtn").click();
    });

    @this.on('dataFailed', (event) =>
    {
      document.getElementById("closeAdd").click();
      document.getElementById("closeDelete").click();
      document.getElementById("closeEdit").click();
      document.getElementById("failedToastBtn").click();
    });
  });
</script>
@endsection

SEKARANG BAHAS CONTROLLER

use App\Models\Siswa as SiswaModel;

fungsinya untuk membuat model "as" dari siswa jadi siswamodel karena "siswa" sudah terpakai sebagai nama file controller"siswa"

    public $notification_message, $notification_row;

untuk notifikasi setelah penggunaan tombol

    public $nis, $nisn, $nama_siswa, $tahun_masuk, $tahun_keluar, $no_telp, $status, $alamat;

variable untuk menampung yg akakn di pakai didalam controller nantinya

    public $data_siswa, $id;

variable yg akan digunakan untuk fitur edit 


    public function render()
    {
        $siswadata = SiswaModel::orderBy('created_at', 'DESC')->get();
        return view('livewire.dashboard.guru.siswa', compact('siswadata'))->layout('layouts.dashboard');
    }

fungsi untuk menampilkan. yg sudah di bahas tadi di atas

public function store()

untuk method tambah data

if(!SiswaModel::where('nama_siswa', $this->nama_siswa)->exists())

untuk kondisi "jika siswa belum ada" maka ..

$save = SiswaModel::create([

simpan data ke model di cocokkan dan di buat sesuai dengan apa yg di array & layout input blade

            'nis' => $this->nis,
            'nisn' => $this->nisn,
            'nama_siswa' => $this->nama_siswa,
            'tahun_masuk' => $this->tahun_masuk,
            'no_telp' => $this->no_telp,
            'status' => $this->status,
            'alamat' => $this->alamat,

yg coklat = ambil dari modal siswa yg sudah di buat

yg biru = ambil dari blade layout yg tadi dibuat cth :

<input type="text" class="form-control border border-dark" wire:model="nis">


$this->notification_message = 'Data Siswa Berhasil Dibuat !';
        $this->dispatch('dataSuccess');

inisialisasi notifikasi popup yg di ambil dari variable tadi di atas public $notification_message, $notification_row;

else
      {

else kondisi lainnya

$this->notification_message = 'Data Siswa Gagal Dibuat !';
          $this->dispatch('dataFailed');

sama,inisialisasi notifikasi popup yg di ambil dari variable tadi di atas public $notification_message, $notification_row;

$this->resetInput();

jika sudah input. reset data yg ada

    public function resetinput()
    {
      $this->reset(['nis', 'nisn', 'nama_siswa', 'tahun_masuk', 'tahun_keluar', 'no_telp', 'status', 'alamat']);
    }

method untuk reset input yg bisa di reset sesuai apa yg ada pada array nis', 'nisn', 'nama_siswa', 'tahun_masuk', 'tahun_keluar', 'no_telp', 'status', 'alamat']

public function edit($id)

method edit fungsinya untuk edit

$data_siswa = SiswaModel::find($id);

variable data_siswa ngambil dari model yg di cocokkan dari id

      $this->id = $id;

      $this->tahun_keluar = $data_siswa->tahun_keluar;
      $this->no_telp = $data_siswa->no_telp;
      $this->status = $data_siswa->status;
      $this->alamat = $data_siswa->alamat;

apa saja yg akan di edit pada field table siswa

public function delete()

method delete

$data_siswa = SiswaModel::where('id', $this->id)->delete();

ngambil dari variable, dari model sesuaikan dengan id lalu delete

$this->notification_message = 'Data Siswa Berhasil Dihapus !';
      $this->dispatch('dataSuccess');

notifikasi popup, inisialisasi notifikasi popup yg di ambil dari variable tadi di atas public $notification_message, $notification_row;


public function update()

metjod update

$data_siswa = SiswaModel::where('id', $this->id)->first();

variable $data_siswa  , cocokkan dengan model field table yg ada pada model dengan id dan apakah sesuai dengan array dibawah

$data_siswa->update([
        'tahun_keluar' => $this->tahun_keluar,
        'no_telp' => $this->no_telp,
        'status' => $this->status,
        'alamat' => $this->alamat,
      ]);

yg coklat = ambil dari modal siswa yg sudah di buat

yg biru = ambil dari blade layout yg tadi dibuat cth :

<input type="text" class="form-control border border-dark" wire:model="nis">


      $this->notification_message = 'Data Siswa Berhasil Diupdate!';
      $this->dispatch('dataSuccess');

notifikasi popup, inisialisasi notifikasi popup yg di ambil dari variable tadi di atas public $notification_message, $notification_row;


codingan controller siswa fullnya : 

<?php

namespace App\Livewire\Dashboard\Guru;

use Livewire\Component;
use App\Models\Siswa as SiswaModel;

class Siswa extends Component
{
    public $notification_message, $notification_row;
    public $nis, $nisn, $nama_siswa, $tahun_masuk, $tahun_keluar, $no_telp, $status, $alamat;
    public $data_siswa, $id;

    public function render()
    {
        $siswadata = SiswaModel::orderBy('created_at', 'DESC')->get();
        return view('livewire.dashboard.guru.siswa', compact('siswadata'))->layout('layouts.dashboard');
    }

    public function store()
    {
      if(!SiswaModel::where('nama_siswa', $this->nama_siswa)->exists())
      {
        $save = SiswaModel::create([
            'nis' => $this->nis,
            'nisn' => $this->nisn,
            'nama_siswa' => $this->nama_siswa,
            'tahun_masuk' => $this->tahun_masuk,
            'no_telp' => $this->no_telp,
            'status' => $this->status,
            'alamat' => $this->alamat,
        ]);

        $this->notification_message = 'Data Siswa Berhasil Dibuat !';
        $this->dispatch('dataSuccess');
     
      }
      else
      {
          $this->notification_message = 'Data Siswa Gagal Dibuat !';
          $this->dispatch('dataFailed');
      }
 
      $this->resetInput();
    }

    public function resetinput()
    {
      $this->reset(['nis', 'nisn', 'nama_siswa', 'tahun_masuk', 'tahun_keluar', 'no_telp', 'status', 'alamat']);
    }

    public function edit($id)
    {
      $data_siswa = SiswaModel::find($id);
      $this->id = $id;

      $this->tahun_keluar = $data_siswa->tahun_keluar;
      $this->no_telp = $data_siswa->no_telp;
      $this->status = $data_siswa->status;
      $this->alamat = $data_siswa->alamat;
     
    }

    public function delete()
    {
      $data_siswa = SiswaModel::where('id', $this->id)->delete();

      $this->notification_message = 'Data Siswa Berhasil Dihapus !';
      $this->dispatch('dataSuccess');
    }

    public function update()
    {
      $data_siswa = SiswaModel::where('id', $this->id)->first();
      $data_siswa->update([
        'tahun_keluar' => $this->tahun_keluar,
        'no_telp' => $this->no_telp,
        'status' => $this->status,
        'alamat' => $this->alamat,
      ]);

      $this->notification_message = 'Data Siswa Berhasil Diupdate!';
      $this->dispatch('dataSuccess');
    }

    // public function render()
    // {
    //     $siswa = SiswaModel::all();
    //     return view('livewire.dashboard.guru.siswa', compact('siswa'))->layout('layouts.dashboard');
    // }

}






close