Tried to using belongsTo in Laravel but its not working - php

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>
<i class="zmdi zmdi-account-add"></i> Tambah Stock
<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">
<i class="zmdi zmdi-edit"></i></span>
<i class="zmdi zmdi-delete"></i></span>
</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.

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');
}

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>

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

Related

How to show images in a datatable after submitting them in a form?

I made a form where I add a product with fields like name, price, image and its category. Now I would like to display them in a datatable and I was able to do that. The problem is that for the display, all the fields are displayed but the images alone do not come and shows an icon of an image not loaded. Here's a bit of that in the capture I submitted.
The blade.php:
#extends('layouts.appadmin')
#section('title')
Livres
#endsection
#section('contenu')
<div class="card">
<div class="card-body">
<h4 class="card-title">Livres</h4>
<div class="row">
<div class="col-12">
<div class="table-responsive">
<table id="order-listing" class="table">
<thead>
<tr>
<th>Order #</th>
<th>Nom du livre</th>
<th>Prix</th>
<th>Image</th>
<th>Statut</th>
<th>Catégorie</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($livres as $livre)
<tr>
<td>{{$livre->id}}</td>
<td>{{$livre->nomLivre}}</td>
<td>{{$livre->prixLivre}}</td>
<td><img src="/storage/{{$livre->image}}" alt=""></td>
<td>
#if ($livre->statusLivre ==1)
<label class="badge badge-success">Activé</label>
#else
<label class="badge badge-success">Désactivé</label>
#endif
</td>
<td>{{$livre->categorie->category_name}}</td>
<td>
<button class="btn btn-outline-primary">View</button>
<button class="btn btn-outline-danger">Delete</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script src="Administrateur/js/data-table.js"></script>
#endsection
</body>
</html>
Just below, It's the controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Categorie;
use App\Models\Livre;
class LivreController extends Controller
{
//
public function ajouterlivre()
{
$categories = Categorie::all();
return view('admin.ajouterlivre', [
'categories' => $categories,
]);
}
public function sauverlivre(Request $request)
{
$request->validate([
'nomLivre' => 'required|unique:livres',
'prixLivre' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'categorie_id' => 'required',
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'storage/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
Livre::create($input);
return redirect('/ajouterlivre')->with('status', 'Un livre a été ajouté avec succès');
}
public function livre()
{
$livres = Livre::get();
return view('admin.livres')->with('livres', $livres);
}
The migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLivresTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('livres', function (Blueprint $table) {
$table->increments('id');
$table->string('nomLivre')->unique();
$table->integer('prixLivre');
$table->string('image');
$table->integer('statusLivre')->default(0)->nullable();
$table->integer('categorie_id')->unsigned();
$table->foreign('categorie_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('livres');
}
}
You see that the images are not loaded, right? What could have caused this? Thank you for your attention.

get data from another table matching with name laravel

Before I start here are some translation, since I'm not using english for my code:
Penyedia = Vendor
Pekerjaan = Work
So I have two table, Vendor Table and Work Table. Each Vendor can have multiple of Works, and each Work can be own by only one Vendor. It supposed to be one to many relationship. Here is my table
Vendor Table
Work Table
So, I'm using LARAVEL as my framework. I have created a vendor table with an action button, that I want it to function which if click, it will show the work (pekerjaan) list owned by the exact vendor name. As you can see from the table above I added the vendor name (nama) to the "Work Table" in my database. How could I do this function to work? I'm new to this "Eloquent" in Laravel.
Here is my model files:
Pekerjaan.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Pekerjaan extends Eloquent
{
use HasFactory;
protected $guarded = [];
public function penyedia(){
return $this->belongsTo('App\Models\Penyedia');
}
}
Penyedia.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Penyedia extends Eloquent
{
use HasFactory;
protected $guarded = [];
public $timestamps = false;
public function pekerjaan(){
return $this->hasMany('App\Models\Pekerjaan');
}
}
AdminController.php
public function showpekerjaan(){
$penyedia = penyedia::all();
return view('admin.showpekerjaan', compact('penyedia'));
}
tabelnilai_pekerjaan.blade.php (I want to show this work table according to the vendor)
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Tabel Nilai Pekerjaan</h3>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive">
<table id="tabelpekerjaan" class="table table-bordered">
<thead>
<tr>
<th style="width: 10px">No.</th>
<th>Paket Pekerjaan</th>
<th>Nama Perusahaan</th>
<th>Lokasi Pekerjaan</th>
<th>HPS</th>
<th>Nilai Kontrak</th>
<th style="width: 120px">Aksi</th>
</tr>
</thead>
<tbody>
#php $no = 1; #endphp
#foreach ($penyedia as $penyedias)
<tr>
<td>{{$no++}}</td>
<td>{{$penyedias->pekerjaan->pekerjaan}}</td>
<td>{{$penyedias->pekerjaan->nama}}</td>
<td>{{$penyedias->pekerjaan->lokasi}}</td>
<td>Rp. {{number_format($pekerjaans->pekerjaan->hps,0,',',',')}}</td>
<td>Rp. {{number_format($pekerjaans->pekerjaan->nilai_kontrak,0,',',',')}}</td>
<td>
Edit
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</section>
Is there anything that I need to add or edit or change? Thank you
You are trying to print array as string. Your pekerjaan() relation has hasmany property and it returns array. If you like to display all pekerjaan, you need to run a second loop inside a loop. and if you need to display only one, you can simply do
<td>{{$penyedias->pekerjaan[0]->pekerjaan}}</td>
To display all pekerjaan, you can loop on $penyedias->pekerjaan like:
#php $no = 1; #endphp
#foreach ($penyedia as $penyedias)
#foreach($penyedias->pekerjaan as $pekerjaan)
<tr>
<td>{{$no++}}</td>
<td>{{$pekerjaan->pekerjaan}}</td>
<td>{{$penyedias->nama}}</td>
<td>{{$pekerjaan->lokasi}}</td>
<td>Rp. {{number_format($pekerjaan->hps,0,',',',')}}</td>
<td>Rp. {{number_format($pekerjaan->nilai_kontrak,0,',',',')}}</td>
<td>
Edit
</td>
</tr>
#endforeach
#endforeach
And change $penyedia = penyedia::all(); on your controller to $penyedia = Penyedia::all();

hide action button if roles have relationship with users

Hi I am working on Role Based authentication in Laravel and every thing works fine but I have problem in Role section.
I want to hide action buttons like Edit and Delete from my Roles List Page those roles which have been assigned to users can't be delete but other roles which haven't assigned to user yet can be deleted.
Role Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('role_typ');
$table->string('role_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
User migration
class AddColumnsToUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
});
}
user model
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
Role Controller
// Role Management
public function Rolelist()
{
$roles = Role::paginate(10);
return view('admin.roles', compact('roles'));
}
Role list blade page
<div class="card">
<div class="card-header">
<h3 class="card-title">All Role List</h3>
<div class="card-tools">
<a href="{{ route('roleform') }}" class="btn btn-block btn-success btn-sm">Add Role <i
class="fas fa-user-plus"></i></a>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>ID</th>
<th>Role Name</th>
<th>Role Type</th>
<th>Created</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($roles as $role)
<tr>
<td>{{ $role->id }}</td>
<td>{{ $role->role_name }}</td>
<td>{{ $role->role_typ }}</td>
<td> {{ \Carbon\Carbon::createFromTimeStamp(strtotime($role->created_at))->diffForHumans() }}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
In the Role model you should have users method which contains HasMany relationship to User model. After that when you get the roles you should use Role::withCount('users');
Then in the blade file you can use $role->users_count to check how many users you have attached to this role.
https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models

Eloquent query on relationship table

Hello i have two models Adress and Kontokorrent they have a one to one relationship. I would like to make a search function and search after Adress and Kontokorrent columns
My models:
Adress Model
class Adress extends Model
{
protected $table = "Adressen";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchAdress($query, $searchTerm)
{
return $query->where('LieferOrt', 'LIKE', '%'.$searchTerm.'%')
->orWhere('Name1', 'LIKE', '%'.$searchTerm.'%')
->orWhere('LieferStrasse', 'LIKE', '%'.$searchTerm.'%');
}
public function kontokorrent()
{
return $this->hasOne(Kontokorrent::class, 'Adresse');
}
}
Kontokorrent Model
class Kontokorrent extends Model
{
protected $table = "Kontokorrent";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchKto($query, $searchTerm)
{
return $query->where('Kto', 'LIKE', '%'.$searchTerm.'%');
}
public function adress()
{
return $this->belongsTo(Adress::class, 'Adresse');
}
}
Controller
class AdressesController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$adresses = Adress::whereHas('kontokorrent', function($query) use($searchTerm) {
$query->where('KtoArt', 'D')
->searchKto('K75688'); // this is working
// -> searchKto($searchTerm); this is NOT working
})->orderBy('Name1')
->searchAdress($searchTerm)
->paginate(60);
return view('adresse.index', compact('adresses', 'searchTerm'));
}
}
The search function in Adress model is working. Now i would like to search after the customer ID (Kto) in Kontokorrent. So i made a scope in Kontokorrent and chain it to the contoller search function.
->searchKto('K75688') .... this is working i get a result
->searchKto($searchTerm) .... this is not working when i entry the customer id in my input field and hit enter. I get a 0 row table.
View
#section('content')
<div class="row">
<div class="col-xs-12 col-md-12">
<form role="search" method="GET" action="/adresses">
<div class="input-group">
<input type="text" class="form-control" name="searchTerm" value="{{ isset($searchTerm) ? $searchTerm : '' }}" placeholder="Suche nach Name, Straße, Ort">
<div class="input-group-btn">
<button type="submit" class="btn btn-search btn-default">
Suchen...
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Straße</th>
<th>Ort</th>
<th>PLZ</th>
<th>Land</th>
</tr>
</thead>
<tbody>
#if(count($adresses) > 0)
#foreach($adresses as $adress)
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>
{{$adress->Anrede}} {{ $adress->Name1}}
#if($adress->kontokorrent)
<small>{{ $adress->kontokorrent->Kto }}</small>
#endif
</td>
<td>{{ $adress->LieferStrasse }}</td>
<td>{{ $adress->LieferOrt }}</td>
<td>{{ $adress->LieferPLZ }}</td>
<td>{{ $adress->LieferLand }}</td>
</tr>
#endforeach
#else
<tr><td colspan="6" class="text-center">Kein Eintrag gefunden.</td></tr>
#endif
</tbody>
</table>
</div>
</div>
{{ $adresses->appends(['searchTerm' => $searchTerm])->links() }}
#endsection
I don't understand why I get an empty table.

Laravel: Eloquent returning an object I can't iterate over

I have a mySQL DB schema like this:
table RECIPES:
int id, PK;
int salesman_id;
int doctor_id;
date order_date;
int status;
table RECIPE_STATUS:
int id, PK;
int recipe_status_code;
varchar recipe_status_name;
In Laravel I have the following php classes:
AdminRecipesController.php
namespace RatCMS\Controllers;
use App\Http\Controllers\Controller;
use Auth;
use RatCMS\Models\Recipes;
use RatCMS\Models\RecipeStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AdminRecipesController extends Controller
{
public function index()
{
$recipes = Recipes::with('recipeStatus')->get();
return view('admin.recipes.news', compact('recipes'));
}
}
Recipes.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class Recipes extends Model
{
protected $table = 'RECIPES';
protected $fillable = ['salesman_id', 'doctor_id', 'order_date', 'status'];
public function recipeStatus() {
return $this->hasOne(\RatCMS\Models\RecipeStatus::class, 'recipe_status_code', 'status');
}
}
RecipeStatus.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class RecipeStatus extends Model
{
protected $table = 'RECIPE_STATUS';
protected $fillable = [];
public function recipes() {
return $this->belongsTo(\RatCMS\Models\Recipes::class);
}
}
blade view
<div class="box-body">
#include('admin.partials.session_success')
#if($recipes->isEmpty())
<p class="text-center">No recipes available.</p>
#else
<table class="table table-bordered">
<tr>
<th style="width: 10px">#</th>
<th>Salesman</th>
<th>Doctor</th>
<th>Date</th>
<th>Status</th>
<th style="width:100px">Actions</th>
</tr>
#foreach($recipes as $recipe)
{{ $recipe }}
<tr>
<td>{{ $recipe->id }}</td>
<td>{{ $recipe->salesman_id }}</td>
<td>{{ $recipe->doctor_id }}</td>
<td>{{ $recipe->order_date }}</td>
<td>{{ $recipe->recipe_status->recipe_status_name }}</td>
<td>
<form style="display: inline-block" action="{{ url('admin/recipes/' . $recipe->id) }}" method="POST">
{{ csrf_field() }}
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger"><i class="fa fa-close" aria-hidden="true"></i> Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
#endif
</div>
When I do {{ $recipe }} in the view, I get the following result:
{"id":1,"salesman_id":"4","doctor_id":"3","order_date":null,"status":"0","recipe_status":{"id":1,"recipe_status_code":"0","recipe_status_name":"Not Recieved"}}
so there is some data being return by Eloquent regarding the recipe status (Not Recieved text), but when I do {{ $recipe->recipe_status }} it fails every time. Even $recipes['recipe_status'] is no help.
Could someone help? Thanks
Relationship should be belongsTo():
public function recipeStatus() {
return $this->belongsTo(\RatCMS\Models\RecipeStatus::class, 'status', 'recipe_status_code');
}
With correct relationship your code will add relationship data to collection, so you'll be able to get status:
$recipe->recipeStatus->recipe_status_name

Categories