• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Jaranguda

Belajar Mengajar

  • Home
  • Sponsor/Jasa
  • Tentang

laravel 5

Contoh Script PHP CRUD di Laravel 5.5

Last Updated on 30 November 2017 By tommy 1 Comment

Untuk pembejalaran pembuat aplikasi CRUD (Create, Read, Update, Delete) di Laravel 5.5 kita akan membuat contoh database karyawan. Kita tidak akan mengunakan HTML/Form helper di Laravel.

Kebutuhan

– LAMP/LEMP yang sudah berjalan
– composer
– text editor (Sublime Text)
– koneksi internet

Buat Database

Saya menggunakan MySQL/MariaDB, login ke MySQL

mysql -u root -p

buat database baru dengan nama crudlaravel55

create database crudlaravel55;

Install Laravel

Install laravel dengan composer

composer create-project --prefer-dist laravel/laravel crudlaravel5

Edit file .env
Untuk koneksi ke database, ubah file .env

DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

contoh

DB_DATABASE=crudlaravel55
DB_USERNAME=crudlaravel55
DB_PASSWORD=crudlaravel55123

Membuat Tabel Database

Kita akan membuat satu tabel dengan nama karyawan

php artisan make:migration tabel_karyawan
## outputnya
Created Migration: 2017_11_10_033011_tabel_karyawan

Edit file di migration yang baru dibuat, letaknya ada di folder database/migrations/, di contoh nama filenya database/migrations/2017_11_10_033011_tabel_karyawan.php

Ubah menjadi

    public function up()
    {
        Schema::create('karyawan', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nama_lengkap');
            $table->string('NIK');
            $table->string('Jabatan');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('karyawan');
    }

Buka file app/Providers/AppServiceProvider.php ubah function boot() menjadi

    public function boot()
    {
        \Schema::defaultStringLength(191);
    }

Sekarang jalankan php artisan migrate agar tabel tersebut dibuat di database

php artisan migrate

Routes

Buka file routes/web.php tambahkan

Route::resource('karyawan', 'KaryawanController');

Coding CRUD

Disini baru kita mulai proses kodingnya.

1. Model

Buat model untuk tabel karyawan yang tadi dibuat

php artisan make:model Karyawan

file model yang baru dibuat ada di app/Karyawan.php, ubah menjadi

class Karyawan extends Model
{
    protected $table = 'karyawan';
    protected $fillable = ['nama_lengkap', 'NIK', 'jabatan'];
}

2. Controller

Buat controller untuk Karyawan

php artisan make:controller KaryawanController

File controller tersebut berada di app/Http/Controllers/KaryawanController.php, isi lengkap file KaryawanController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Karyawan;
 
class KaryawanController extends Controller
{
    public function index() {
        $karyawan = Karyawan::all();
        return view('karyawan.index', compact('karyawan'));
    }
 
    public function create() {
        return view('karyawan.create');
    }
 
    public function edit($id) {
        $karyawan = Karyawan::findOrFail($id);
        return view('karyawan.edit', compact('karyawan'));
    }
 
    public function store(Request $request) {
        Karyawan::create($request->all());
        \Session::flash('notifikasi', 'Karyawan berhasil ditambah.');
        return redirect('karyawan');
    }
 
    public function update(Request $request, $id) {
        $karyawan = Karyawan::findOrFail($id);
        $karyawan->update($request->all());
        \Session::flash('notifikasi', 'Karyawan berhasil diubah.');
        return redirect('karyawan');
    }
 
    public function destroy($id) {
        Karyawan::destroy($id);
        \Session::flash('notifikasi', 'Karyawan berhasil dihapus.');
        return redirect('karyawan');
    }
}

3. View

Buat file resources/views/template.blade.php yang akan digunakan sebagai master template untuk web. Isi file template.blade.php

<!doctype html>
<html lang="en">
<head>
    <title>CRUD Laravel 5.5 - jaranguda.com</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <style type="text/css">
    body {
      padding-top: 2rem;
    }
    </style>
</head>
<body>
 
    <main role="main">
 
        <div class="container">
 
            <div class="row">
                <div class="col-md-12">
 
                @if (session('notifikasi'))
                    <div class="alert alert-success">
                        {{ session('notifikasi') }}
                    </div>
                @endif
 
                @yield('content')
 
                </div>
            </div>
        </div>
 
    </main>
 
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>

Untuk menampilkan data dari controller karyawan, kita akan membuat satu folder karyawan dan beberapa file. Buat folder karyawan di resources/views/.

Index dan Delete

isi file index.blade.php (resources/views/karyawan/index.blade.php)

@extends('template')
 
@section('content')
 
<h3>Data Karyawan</h3>
<hr>
Tambah Karyawan
<hr>
@if(count($karyawan) > 0)
 
    <table class="table">
        <thead>
            <tr>
                <th>Nama Lengkap</th>
                <th>NIK</th>
                <th>Jabatan</th>
                <th>#</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($karyawan as $data)
            <tr>
                <td>{{ $data->nama_lengkap }}</td>
                <td>{{ $data->NIK}}</td>
                <td>{{ $data->jabatan }}</td>
                <td>
                    <a href="{{ URL::route('karyawan.edit',$data->id) }}" class="btn btn-info btn-sm"></i> Edit</a>
                    <form action="{{action('[email protected]', $data->id)}}" method="post" class="hapus" style="display:inline">
                    {{csrf_field()}}
                    <input name="_method" type="hidden" value="DELETE">
                    <button class="btn btn-danger" type="submit">Delete</button>
                    </form>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
@else
belum ada data
@endif
 
 
@stop

Create

isi file create.blade.php (resources/views/karyawan/create.blade.php)

@extends('template')
 
@section('content')
 
<h3>Data Karyawan</h3>
<hr>
 
    <form class="form-horizontal" role="form" method="POST" action="{{ url('/karyawan') }}">
        {{ csrf_field() }}
        <div class="form-group{{ $errors->has('nama_lengkap') ? ' has-error' : '' }}">
            <label for="nama_lengkap" class="col-md-4 control-label">Nama</label>
            <div class="col-md-6">
                <input id="nama_lengkap" type="text" class="form-control" name="nama_lengkap" value="{{ old('nama_lengkap') }}" required="required">
                @if ($errors->has('nama_lengkap'))
                <span class="help-block">
                    <strong>{{ $errors->first('nama_lengkap') }}</strong>
                </span>
                @endif
            </div>
        </div>
 
        <div class="form-group{{ $errors->has('NIK') ? ' has-error' : '' }}">
            <label for="NIK" class="col-md-4 control-label">NIK</label>
            <div class="col-md-6">
                <input id="NIK" type="text" class="form-control" name="NIK" value="{{ old('NIK') }}" required="required">
                @if ($errors->has('NIK'))
                <span class="help-block">
                    <strong>{{ $errors->first('NIK') }}</strong>
                </span>
                @endif
            </div>
        </div>
 
        <div class="form-group{{ $errors->has('jabatan') ? ' has-error' : '' }}">
            <label for="jabatan" class="col-md-4 control-label">Jabatan</label>
            <div class="col-md-6">
                <input id="jabatan" type="text" class="form-control" name="jabatan" value="{{ old('jabatan') }}" required="required">
                @if ($errors->has('jabatan'))
                <span class="help-block">
                    <strong>{{ $errors->first('jabatan') }}</strong>
                </span>
                @endif
            </div>
        </div>
 
 
        <div class="form-group">
            <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary">
                    <i class="fa fa-btn fa-user"></i> Simpan
                </button>
            </div>
        </div>
    </form>
 
@stop

Edit

isi file edit.blade.php (resources/views/karyawan/edit.blade.php)

@extends('template')
 
@section('content')
 
<h3>Data Karyawan</h3>
<hr>
 
@if(isset($karyawan))
        <form class="form-horizontal" role="form" method="POST" action="{{ url('/karyawan/' . $karyawan->id) }}">
        <input name="_method" type="hidden" value="PATCH">
        {{ csrf_field() }}
        <div class="form-group{{ $errors->has('nama_lengkap') ? ' has-error' : '' }}">
            <label for="nama_lengkap" class="col-md-4 control-label">Nama</label>
            <div class="col-md-6">
                <input id="nama_lengkap" type="text" class="form-control" name="nama_lengkap" value="{{ old('nama_lengkap', $karyawan->nama_lengkap) }}" required="required">
                @if ($errors->has('nama_lengkap'))
                <span class="help-block">
                    <strong>{{ $errors->first('nama_lengkap') }}</strong>
                </span>
                @endif
            </div>
        </div>
 
        <div class="form-group{{ $errors->has('NIK') ? ' has-error' : '' }}">
            <label for="NIK" class="col-md-4 control-label">NIK</label>
            <div class="col-md-6">
                <input id="NIK" type="text" class="form-control" name="NIK" value="{{ old('NIK', $karyawan->NIK) }}" required="required">
                @if ($errors->has('NIK'))
                <span class="help-block">
                    <strong>{{ $errors->first('NIK') }}</strong>
                </span>
                @endif
            </div>
        </div>
 
        <div class="form-group{{ $errors->has('jabatan') ? ' has-error' : '' }}">
            <label for="jabatan" class="col-md-4 control-label">Jabatan</label>
            <div class="col-md-6">
                <input id="jabatan" type="text" class="form-control" name="jabatan" value="{{ old('jabatan', $karyawan->Jabatan) }}" required="required">
                @if ($errors->has('jabatan'))
                <span class="help-block">
                    <strong>{{ $errors->first('jabatan') }}</strong>
                </span>
                @endif
            </div>
        </div>
 
        <div class="form-group">
            <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary">
                    <i class="fa fa-btn fa-user"></i> Simpan
                </button>
            </div>
        </div>
    </form>
 
@endif
 
 
@stop

Filed Under: PHP Tagged With: laravel 5

Laravel Database Join Tabel Error Unknown column

Last Updated on 11 October 2017 By tommy Leave a Comment

Ketika melakukan pencarian di datatables muncul error seperti dibawah ini

DataTables warning: table id=datatables – Exception Message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘db_jaranguda.client_name’ in ‘where clause’ (SQL: select count(*) as aggregate from (select ‘1’ as `row_count` from `db_jaranguda` left join `lab` on `lab_id` = `lab`.`id`

Solusi

Error tersebut muncul karena anda tidak menyertakan nama tabel di nama kolom yang diambil dari relasi antar tabel, padah contoh diatas hanya client_name harusnya clients.client_name.

Filed Under: PHP Tagged With: Datatables, laravel 5

Laravel Relationship method must return an object

Last Updated on 5 August 2016 By tommy Leave a Comment

Error lengkapnya

LogicException in Model.php line 2702: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

Relationship method must return an object of type Illuminate

Solusi

Ubah save menjadi save(), contoh

$po = Po::find($request->po_id);
$po->status = 'Dikirim';
$po->save;

menjadi

$po = Po::find($request->po_id);
$po->status = 'Dikirim';
$po->save();

Filed Under: PHP Tagged With: laravel 5, Laravel 5.2

Laravel Mengatasi Error services.json failed to open stream

Last Updated on 15 June 2015 By tommy 1 Comment

Setelah upgrade dari Larave 5.0.x ke 5.1 LTS muncul error

 
  [ErrorException]                                                                                                          
  file_put_contents(/var/www/html/laravel/bootstrap/cache/services.json): failed to open stream: No such file or directory  
 
 
 
Script php artisan clear-compiled handling the post-update-cmd event returned with an error
 
 
 
  [RuntimeException]  
  Error Output:

solusinya buat folder cache tersebut ;).

mkdir /var/www/html/laravel/bootstrap/cache

Ingat untuk menyesuaikan path folder laravel anda. Setelah di buat folder cache, jalankan composer update sekali lagi

Filed Under: PHP Tagged With: error, laravel 5

Membuat Pagination di Laravel 5

Last Updated on 1 June 2015 By tommy 5 Comments

Pertama kita akan membuat database dummy (contoh), buat database baru dengan nama Tutorial, import data di bawah ini, bisa lewat phpMyAdmin atau Adminer

CREATE TABLE IF NOT EXISTS `dborang` (
  `id` mediumint(8) unsigned NOT NULL,
  `Name` varchar(255) DEFAULT NULL,
  `Country` varchar(100) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1;
 
--
-- Dumping data for table `dborang`
--
 
INSERT INTO `dborang` (`id`, `Name`, `Country`) VALUES
(1, 'Aubrey', 'Cambodia'),
(2, 'Gloria', 'Saint Pierre and Miquelon'),
(3, 'Amery', 'Turkmenistan'),
(4, 'Robert', 'Zimbabwe'),
(5, 'Ifeoma', 'Namibia'),
(6, 'Hoyt', 'Chile'),
(7, 'Yeo', 'Brunei'),
(8, 'Erich', 'Marshall Islands'),
(9, 'Amber', 'Finland'),
(10, 'Ifeoma', 'Curaçao'),
(11, 'Sybill', 'Antigua and Barbuda'),
(12, 'Alice', 'Saint Lucia'),
(13, 'Edan', 'Bermuda'),
(14, 'Keely', 'Nicaragua'),
(15, 'Lee', 'Antigua and Barbuda'),
(16, 'Brenda', 'Tanzania'),
(17, 'Nell', 'Romania'),
(18, 'Meghan', 'Serbia'),
(19, 'Lisandra', 'Japan'),
(20, 'Aimee', 'Korea, South'),
(21, 'Cassidy', 'Egypt'),
(22, 'Reagan', 'Mayotte'),
(23, 'Medge', 'Mauritius'),
(24, 'Leo', 'Guam'),
(25, 'Aidan', 'Rwanda'),
(26, 'Eugenia', 'El Salvador'),
(27, 'Grace', 'Burkina Faso'),
(28, 'Vernon', 'Nicaragua'),
(29, 'Barry', 'Sierra Leone'),
(30, 'Amber', 'Liberia'),
(31, 'Renee', 'Togo'),
(32, 'Ivan', 'Azerbaijan'),
(33, 'Brynne', 'Cambodia'),
(34, 'Shaeleigh', 'Oman'),
(35, 'Patrick', 'Tuvalu'),
(36, 'Avram', 'Macedonia'),
(37, 'Uma', 'Georgia'),
(38, 'Valentine', 'El Salvador'),
(39, 'Susan', 'Cape Verde'),
(40, 'Hanna', 'Malawi');
 
ALTER TABLE `dborang`
  ADD PRIMARY KEY (`id`);

Edit file app/Http/routes.php tambahkan di baris paling bawah

Route::get('orang', '[email protected]');

Buat Model (app), contoh kita beri nama Orang.php

<?php namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class Orang extends Model {
 
	protected $table = 'dborang';
	protected $primaryKeys = 'id';
 
}

Buat Controller (app/Http/Controllers), contoh kita beri nama OrangController.php

	public function index()
	{
		$orang = \App\Orang::paginate(10);
		return view('orang', compact('orang'));
	}

Buat View (resources/views), contoh kita beri nama Orang.blade.php

<!DOCTYPE html>
<html lang="">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Membuat Pagination di Laravel 5</title>
		<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
	</head>
 
	<body>
 
<div class="container">
	<h4>Table Data</h4>
	<table class="table table-hover table-bordered">
	<thead>
		<tr>
			<th>#</th>
			<th>Name</th>
			<th>Country</th>
		</tr>
	</thead>
	<tbody>
	<?php $no = $orang->firstItem() - 1 ; ?>
	@foreach ($orang as $data)
	<?php $no++ ;?>
		<tr>
			<td>{{ $no }}</td>
			<td>{{ $data->Name}}</td>
			<td>{{ $data->Country}}</td>
		</tr>
	@endforeach
	</tbody>
</table>
<?php echo str_replace('/?', '?', $orang->render()); ?>
</div>
 
	</body>
 
</html>

Setelah semua selesai akses URL http://[IP.SERVER]/[Folder Laravel]/public/orang contoh di tempat saya http://localhost/laravel/public/orang

Tampilan script Pagination

table data
hasil rendering table

Filed Under: PHP Tagged With: laravel 5

Cara Mengatasi Error getCachedCompilePath Laravel 5

Last Updated on 22 May 2015 By tommy Leave a Comment

Error yang muncul

PHP Fatal error:  Call to undefined method Illuminate\Foundation\Application::getCachedCompilePath() in /var/www/html/sastra/vendor/laravel/framework/src/Illuminate/Foundation/Console/ClearCompiledCommand.php on line 28
 
  [Symfony\Component\Debug\Exception\FatalErrorException]                             
  Call to undefined method Illuminate\Foundation\Application::getCachedCompilePath()  
 Script php artisan clear-compiled handling the post-update-cmd event returned with an error
                                                                                                                                                            [RuntimeException]                                                                                                                                                 
  Error Output: PHP Fatal error:  Call to undefined method Illuminate\Foundation\Application::getCachedCompilePath() in /var/www/html/sastra/vendor/laravel/framewo  
  rk/src/Illuminate/Foundation/Console/ClearCompiledCommand.php on line 28

atau

 [Symfony\Component\Debug\Exception\FatalErrorException]                             
  Call to undefined method Illuminate\Foundation\Application::getCachedCompilePath()

Solusinya hapus file vendor/compiled.php

Filed Under: PHP Tagged With: laravel 5

  • Go to page 1
  • Go to page 2
  • Go to Next Page »

Primary Sidebar

Pencarian

Tanya Jawab tentang DevOps SRE CPE, gabung di https://t.me/devopsindonesia

Terbaru

  • Solusi helm Upgrade Failed
  • macOS package is untrusted
  • Cara Mengganti Port Screen Sharing macOS
  • Cara Menonaktifkan Pager di macOS
  • Cara Mengupdate Nama Apple silicon-as-a-Service Scaleway

Komentar

  • Beritalogi on Cara Redirect Domain di Cloudflare
  • Putu on Cara Setting TP-LINK EN020-F5 Sebagai Range Extender
  • Budi on Solusi Simple Queue Mikrotik Tidak Berjalan
  • mazda on Tutorial Lengkap Install Mail Server Postfix Dovecot MariaDB di CentOS 7
  • adi on Menggunakan Mikrotik Sebagai SSH Client

Tulisan Populer

  • Password Router Huawei HG8245H5 Indihome 1.2m views
  • Password Terbaru ZTE F609 Indihome 785k views
  • Password Superadmin Huawei HG8245A 322.5k views
  • Cara Setting Manual Modem GPON ZTE F609 Indihome 273.9k views
  • Cara Setting Wireless ZTE F609 Indihome 258.2k views
  • Mengaktifkan Port LAN di Huawei HG8245 Indihome 170.7k views
  • Akses UseeTV Indihome via Wireless ZTE F609 157.1k views
  • Kemana Menghilangnya Saldo BCA 50 ribu 156k views
  • Cara Reset Password ZTE F609 Indihome 147.9k views
  • Cara Setting DHCP Server Modem/Router ZTE F609 114.3k views

Kategori

  • Delphi
  • dll
  • Gambas
  • Internet
  • Java
  • Lazarus
  • Linux
  • PHP
  • Review
  • Teknologi

Sponsor

kadal.id
carakami.com
kuotabisa.com
Untuk jadi sponsor, hubungi kita lewat halaman sponsor
© 2021. Jaranguda
  • Linux
  • PHP
  • Internet
  • Teknologi
  • Delphi
  • Gambas
  • Java