0

im using Laravel 6.2

I want to make a inventory database system. i have 2 modals Produk and Stock. in that case, i want to input data p_name and sku from ProdukTable and place it into StockTable using Eloquent ORM.

I tried using belongsTo(),

Here's my modal Produk code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Produk extends Model
{
    public $table = 'produk';
    protected $primaryKey = 'pid';
    protected $fillable = [
        'pid',
        'p_nama',
        'sku',
        'p_harga',
        'status'
    ];
}

Here's my modal Stock code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Stock extends Model
{
    public $table = 'stock';
    protected $primaryKey = 'sid';
    protected $fillable = [
        'sid',
        'p_nama',
        'sku',
        'p_stock_min',
        'p_stock',
        'status'
    ];

    public function produk()
    {
        return $this->belongsTo('App\Produk', 'pid');
    }
}

My StockController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Stock;
use App\Produk;
use RealRashid\SweetAlert\Facades\Alert;

class StockController extends Controller
{
    public function index()
    {
        $datas = Stock::paginate(5); // 5 record per pages
        return view('stock.list', compact('datas'));

        // $datas  = Stock::all();
        // return $datas;
    }

    . . . .
}

My View stock.blade

            <div class="body">
                <div>
                    <a href="{{ route('stock.create')}}" class="btn btn-success btn-round" data-type="confirm"> <i class="zmdi zmdi-account-add"></i>&nbsp;Tambah Stock</a>
                    <a style="margin: 2px;" href="{{ route('stock.index')}}" class="btn btn-primary btn-sm"><i class="zmdi zmdi-refresh"></i></a>
                </div>
                <div class="col-sm-12">
                    @if(session()->get('success'))
                        <div class="alert alert-success">
                            {{ session()->get('success') }}
                        </div>
                    @endif
                </div>
                <table class="table table-bordered table-striped table-hover dataTable js-exportable">
                    <thead>
                        <tr>
                            <th class="text-center" style="width:5%">#</th>
                            <th class="text-center" style="width:25%">Nama Produk</th>
                            <th class="text-center" style="width:10%">SKU Produk</th>
                            <th class="text-center" style="width:8%">Min. Stock</th>
                            <th class="text-center" style="width:8%">Stock</th>
                            <th class="text-center" style="width:10%">Status</th>
                            <th class="text-center" style="width:10%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @if(!empty($datas) && $datas->count())
                            @foreach($datas as $data)
                            <tr>
                                <th class="text-center">{{ $loop->iteration }}</th>
                                <td>{{ $data->produk }}</td>
                                <td>{{ $data->p_nama }}</td>
                                <td>{{ $data->p_stock_min }}<code> pcs</code></td>
                                <td>{{ $data->p_stock }}<code> pcs</code></td>
                                <td class="text-center">{{ $data->status }}</td>
                                <td class="text-center">
                                    <a href="{{ route('stock.edit', $data->sid)}}" title="Ubah" class="btn btn-warning btn-icon btn-icon-mini btn-round"> <i class="zmdi zmdi-edit"></i></span></a>&nbsp;
                                    <a href="{{ route('stock.delete', $data->sid)}}" title="Hapus" class="btn btn-danger btn-icon btn-icon-mini btn-round" data-type="success"> <i class="zmdi zmdi-delete"></i></span></a>
                                </td>
                            </tr>
                            @endforeach
                        @else
                            <tr>
                                <td colspan="8">Data tidak ditemukan! Silahkan buat data Stock terlebih dahulu.</td>
                            </tr>
                        @endif
                    </tbody>
                </table>
                {!! $datas->links() !!}
            </div>

Migration Stock

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStocksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stock', function (Blueprint $table) {
            $table->bigIncrements('sid');
            $table->bigInteger('produk_id')->unsigned();
            $table->string('p_nama');
            $table->string('sku');
            $table->integer('p_stock_min');
            $table->integer('p_stock')->nullable();
            $table->string('status');
            $table->timestamps();
        });

        Schema::table('stock', function (Blueprint $table) {

            $table->foreign('produk_id')->references('pid')->on('produk')
            ->onDelete('cascade')->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('stock');
    }
}

Response when i add data direct from PMA

[{"sid":1,"produk_id":6,"p_nama":"kopi1","sku":"12345678","p_stock_min":20,"p_stock":800,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"},
{"sid":2,"produk_id":7,"p_nama":"kopi2","sku":"87654321","p_stock_min":20,"p_stock":600,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"}]

i dunno where's my mistake ? just want to add data p_produk into stock table using select form, and when i select it sku data will be generate as same as data on table Produk.

Vhanz Lulz
  • 19
  • 8

3 Answers3

2

In your Stock model you should put the foreign key in the belongsTo relation. Edit the method like so:

  public function produk()
    {
        return $this->belongsTo('App\Produk', 'produk_id');
    }
ml59
  • 1,495
  • 1
  • 9
  • 10
  • ah, okay it works fine now. `{{ $data->produk->p_nama }}` but another problem is how to make it looks like : when i select `p_name` on view `create.blade.php` it will automatic generated as same as `sku` in produk table ? here's my code for `create.blade.php` https://pastebin.com/zp4gtFxw – Vhanz Lulz Nov 24 '20 at 11:12
  • Signature of `belongsTo(RelatedClass, foreign_key, owner_key)` . In this case the foreign_key is produk_id and the owner_key is pid. So declaration should be `public function produk() { return $this->belongsTo(Produk::class, 'produk_id', 'pid');}` – Donkarnash Nov 24 '20 at 11:17
  • okay, but how do i make call in view create.blade.php ? `` the callback process is `Error Exception Undefined variable: $data is undefined` – Vhanz Lulz Nov 24 '20 at 11:30
  • Your create.blade.php code on pastebin shows that you have $sku and $produk variables only. Check in the controller method which passes data and returns create.blade.php what data is being passed to the view from ther – Donkarnash Nov 24 '20 at 11:35
  • sorry, they removed it . i put it on top `https://*pastebin*.com/zp4gtFxw` – Vhanz Lulz Nov 24 '20 at 11:42
  • I can browse to pastebin.com/zp4gtFxw and see your create.blade.php file but where's the controller code – Donkarnash Nov 24 '20 at 11:47
  • `pastebin.com/151KU5CV` – Vhanz Lulz Nov 24 '20 at 11:50
  • Your are passing `$produk` to the view so you can do `$produk->sku` and not `$data->produk->sku` – Donkarnash Nov 24 '20 at 11:54
  • `` the callback is `ErrorException Undefined variable: produk` – Vhanz Lulz Nov 24 '20 at 12:00
  • Because the `' is outside foreach so there's no $produk variable outside foreach. If you want the sku value to dynamically change when a select option of $produk->p_nama is selected then you will need to use javascript – Donkarnash Nov 24 '20 at 12:20
  • `code` pastebin.com/jE2siJMR `image` prnt.sc/vp46sl it feels weird. i don't know how to use it – Vhanz Lulz Nov 24 '20 at 12:48
  • If the answer has solved your problem please mark as resolved. For other issues, please open a new issue – ml59 Nov 24 '20 at 13:35
0

because you are not naming your columns on the laravel naming conventions

you have to define it all by yourself if you want to use this naming like this :

 public function produk()
    {
        return $this->belongsTo('App\Produk', 'pid' , 'id');
    }

as belongsTo takes $relatedModel , $foreignKey , $ownerKey in a row

Ahmed Osama
  • 672
  • 1
  • 8
  • 15
  • okay thankyou, but how to fix my another problem in `create.blade.php` `` the callback is `ErrorException Undefined variable: produk `. link to `view/create`: https://pastebin.com/bBN9nvKX, and `controller` pastebin.com/151KU5CV – Vhanz Lulz Nov 24 '20 at 12:24
  • the line of input is outside the @foreach loop .. move the loop opening to the top to include everything you need $produk for .. – Ahmed Osama Nov 24 '20 at 12:29
  • or create a separate loop but it's not efficient !! – Ahmed Osama Nov 24 '20 at 12:30
  • `code:` pastebin.com/jE2siJMR `image:` prnt.sc/vp46sl it feels weird. i don't know how to use it. i just want to add 1 `sku` as same as when input `p_name`. how do it properly ? – Vhanz Lulz Nov 24 '20 at 12:52
  • I don't sure I understood your question ,, but if you mean a drop down you can do something like this .. https://pastebin.com/NwSQLep8 – Ahmed Osama Nov 26 '20 at 13:17
0

Using Laravel conventions the relationship produk should be defined as

public function produk()
{
    return $this->belongsTo(Produk::class, 'produk_id', 'pid');
}

To dynamically change the value of sky in the readonly input on create.blade.php based on the option selected by the user in select control showing $produk->p_nama:

Give an id to the readonly input for sku

<div class="form-group">
    <label for="sku">SKU:</label>
    <input type="text" class="form-control  form-control-lg" name="sku" id="skuSelected" readonly/>
</div>

Track the option selected in select control

<select class="form-control select2" name="p_name" onChange="setSku(this);">
    @foreach($produks as $produk)
        <option value="{{ $produk->pid }}">{{ $produk->p_nama }}</option>
    @endforeach
</select>

Handle the change in selection via javascript

<script>
 function setSku(sel) {
    const sku = sel.options[sel.selectedIndex].text;
    document.getElementById('skuSelected').value = sku;
 }
</script>
Donkarnash
  • 12,433
  • 5
  • 26
  • 37