get data from another table matching with name laravel - php

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();

Related

Get the the average of the data in laravel

I have two eloquent tables, vendor and work, in the work table there is a total score column and I want to get the average of the total score based on the vendor ID (foreign Key) and save it to the vendor table. May I know how to achieve this?
Here is my vendor table blade file
<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 Penilaian Penyedia</h3>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive">
<table id="tabelpenyedia" class="table table-bordered">
<thead>
<tr>
<th style="width: 10px">No.</th>
<th>Nama Penyedia</th>
<th>Nilai</th>
<th style="width: 120px">Aksi</th>
</tr>
</thead>
<tbody>
#php $no = 1; #endphp
#foreach ($penyedia as $penyedias)
<tr>
<td>{{$no++}}</td>
<td>{{$penyedias->nama}}</td>
<td></td>
<td>
Beri Penilaian
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</section>
Here is the AdminController
public function update_nilaipekerjaan(Request $request, $id){
$pekerjaan = Pekerjaan::find($id);
//$pekerjaan->update($request->all());
//$total = Pekerjaan::select(DB::raw('avg(nilai_1 + nilai_2 + nilai_3 + nilai_4) as nilai_total'))->get();
$pekerjaan->nilai_1=$request->nilai_1;
$pekerjaan->nilai_2=$request->nilai_2;
$pekerjaan->nilai_3=$request->nilai_3;
$pekerjaan->nilai_4=$request->nilai_4;
$pekerjaan->nilai_total=$request->nilai_1+$request->nilai_2+$request->nilai_3+$request->nilai_4;
$pekerjaan->update();
return redirect()->back()->with('message','Nilai Pekerjaan Berhasil diupdate!');
}
public function tabelnilai_penyedia(){
$penyedia = Penyedia::all();
$pekerjaan = Pekerjaan::all();
return view('admin.datanilai_penyedia', compact('penyedia', 'pekerjaan'));
} //I WANT TO SHOW THE AVERAGE OF THE TOTAL SCORE HERE.
Database https://imgur.com/a/N6NlcwJ
Here is what I want to achieve https://imgur.com/a/fk4Yq92
what I have tried
updating the AdminController
public function tabelnilai_penyedia($id){
$penyedia = Penyedia::all();
$pekerjaan = Pekerjaan::all();
$average = Pekerjaan::where('penyedia_id', $id)->avg('nilai_total');
Penyedia::where('id', $id)->update(['nilai'=>$average]);
return view('admin.datanilai_penyedia', compact('penyedia', 'pekerjaan'));
}
But it got me an error,
Too few arguments to function App\Http\Controllers\AdminController::tabelnilai_penyedia(), 0 passed in C:\Users\ASUS TUF\webpenyedia\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 1 expected
You can use the MySQL AVG function to get the average of a column, which in Eloquent is neatly wrapped in an aggregate function
Assuming your models are called "Work" and "Vendor"
// Get average of 'nilai' based on Vendor ID
$average = Work::where('penyedia_id', $vendorId) // Assuming this is the right column
->avg('nilai_total');
// Update Vendor directly in database (No model events)
Vendor::where('id', $vendorId)->update(['nilai' => $average]);

How to show/get all data by the foreign_key

Similiar to Post and Category, I have a database tables Penyedia and Pekerjaan. Whereby Penyedia is similiar to Category, and Pekerjaan similiar to Post. Penyedia hasMany Pekerjaans and Pekerjaan belongsTo Penyedia.
Here is the model:
Pekerjaan.php
<?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(Penyedia::class);
}
}
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 pekerjaans(){
return $this->hasMany(Pekerjaan::class);
}
}
Here is the Table that shows Penyedia: (There is a button that will redirect the user to show the list of datas Pekerjaan specific to that Penyedia)
<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 Penilaian Penyedia</h3>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive">
<table id="tabelpenyedia" class="table table-bordered">
<thead>
<tr>
<th style="width: 10px">No.</th>
<th>Nama Penyedia</th>
<th>Nilai</th>
<th style="width: 120px">Aksi</th>
</tr>
</thead>
<tbody>
#php $no = 1; #endphp
#foreach ($penyedia as $penyedias)
<tr>
<td>{{$no++}}</td>
<td>{{$penyedias->nama}}</td>
<td>{{number_format($penyedias->nilai,1)}}</td>
<td>
Beri Penilaian
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</section>
From that table I have a button that will redirect the user to show the list of datas Pekerjaan specific to that Penyedia. Similiar to this tinker:
php artisan tinker
Psy Shell v0.11.5 (PHP 8.1.0 — cli) by Justin Hileman
>>> $a = Penyedia::first();
[!] Aliasing 'Penyedia' to 'App\Models\Penyedia' for this Tinker session.
=> App\Models\Penyedia {#4473
id: 1,
nama: "CV. KONIRISA",
npwp: "01.453.410.1-701.000",
alamat: "Jl. Prof. DR. Hamka No. 29 A Pontianak",
lati: -0.0225449,
longi: 109.324,
nilai: 0.0,
}
>>> $a->pekerjaans
=> Illuminate\Database\Eloquent\Collection {#4722
all: [
App\Models\Pekerjaan {#4720
id: 7,
pekerjaan: "tes",
lokasi: "tes",
hps: 199902994.72,
nilai_kontrak: 199419622.92,
lati: -0.00677621,
longi: 109.375,
gambar: null,
penyedia_id: 1,
nilai: 0.0,
created_at: "2022-06-22 11:12:55",
updated_at: "2022-06-22 12:20:09",
},
App\Models\Pekerjaan {#3790
id: 8,
pekerjaan: "tes",
lokasi: "asdnasjdasd",
hps: 1023123.0,
nilai_kontrak: 12301203.0,
lati: 1231.0,
longi: 123.0,
gambar: null,
penyedia_id: 1,
nilai: 0.0,
created_at: "2022-06-23 00:10:59",
updated_at: "2022-06-23 00:10:59",
],
}
I have tried these two methods below in the AdminController:
//Show all Penyedia from database
public function tabelnilai_penyedia(){
$penyedia = penyedia::all();
return view('admin.datanilai_penyedia', compact('penyedia'));
}
//Get Pekerjaan specific to the Penyedia
public function showpekerjaan(Penyedia $penyedia){
$pekerjaans = Penyedia::where('id', $penyedia->id)->get();
$penyedia = Penyedia::with('pekerjaans')->get();
return view('admin.showpekerjaan', compact('penyedia'))->with('pekerjaans',$pekerjaans);
}
tabelnilai_pekerjaan.php (This is the table that I want to show, it's get data based on the 'Penyedia')
<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 ($pekerjaan as $pekerjaans)
<tr>
<td>{{$no++}}</td>
<td>{{$pekerjaans->pekerjaan}}</td>
<td>{{$pekerjaans->penyedia->nama}}</td>
<td>{{$pekerjaans->lokasi}}</td>
<td>Rp. {{number_format($pekerjaans->hps,0,',',',')}}</td>
<td>Rp. {{number_format($pekerjaans->nilai_kontrak,0,',',',')}}</td>
<td>
Edit
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</section>
Database
Assumption : You want to find all pekerjaans assosicated to penyedia and you get the correct id of penyedia in $penyedia->id
Hope this help you
inside AdminController:
public function showpekerjaan(Penyedia $penyedia){
$pekerjaan = Penyedia::with('pekerjaans')->where('id',$penyedia->id)->get()
return view('admin.showpekerjaan',['pekerjaan' => $pekerjaan]);
}
for view you can put id of penyedia like:
Beri Penilaian

Tried to using belongsTo in Laravel but its not working

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

Laravel get All with Relationships and Paginate relationship data

I am trying to get all users and their associated (1:n) journals. However I want to add pagination to the associated journals, not the users
My Controller:
public function index()
{
$users = User::with(['journal'])->orderBy('name', 'asc')->get();
return view('journals/journals', ['users' => $users]);
}
My Blade:
#foreach($users as $user)
<a class="list-group-item list-group-item-action" data-toggle="collapse" href="#collapse{{$user->id}}" role="button" aria-expanded="false" aria-controls="collapse{{$user->id}}">
{{$user->name}}
</a>
<div class="collapse mt-1" id="collapse{{$user->id}}">
<div class="card card-body">
<div class="list-group">
<table class="table table-sm table-hover">
<thead>
<tr>
<th scope="col">Kunde</th>
<th scope="col">Betreff</th>
<th scope="col">Leistungsart</th>
<th scope="col">Beginn</th>
<th scope="col">Ende</th>
<th scope="col">Dauer</th>
<th scope="col">Arbeitszeit</th>
</tr>
</thead>
<tbody>
#foreach($user->journal as $journal)
<tr onclick="window.location='{{route('journal.show', [$journal->id])}}'">
<th scope="row">{{$journal->customer->name}}</th>
<td>{{$journal->title}}</td>
<td>{{$journal->type}}</td>
<td>{{$journal->started}}</td>
<td>{{$journal->ended}}</td>
<td>{{$journal->duration}}</td>
<td>{{$journal->worked}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endforeach
My Journal Model:
public function user(){
return $this->belongsTo('App\User', 'user_id', 'id');
}
My User Model:
public function journal(){
return $this->hasMany('App\Journal', 'user_id', 'id');
}
Again, what I am trying to achieve is that I can print out every user and paginate their journals, not paginate the users
I really hope someone can help me there
Render in blade
Above your journals for-each loop in your blade, try and put something like this:
#php
$paginated_journals = $user->journal()->paginate(10);
#endphp
And then, your for-each loop should look like this:
#foreach($paginated_journals as $journal)
...
#endforeach
After the for-each loop you can just put:
$paginated_journals->links()
to get the links for pagination
Pre-load data in controller
You can do the same thing server-side. Create a custom array that is empty, go through each user, and add sub array to that custom array:
array_push($custom_array, ['user' => $user, 'journals' => $user->journal()->paginate(10)])
This way you can send the custom array to your blade, loop through it, and render user data and paginated journals.

Error While Fetching db using eloquent

I have Tried to fetch data from MySQL db using eloquent in my laravel application it shows Parse Error here my code :
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class design extends Model {
//Table Name
protected $table='designs';
//Primary key
public $primarykey='id';
// TimeStamp
public $timestamps=true;
}
Controller Page:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\design;
class designController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$design=design::all();
//$design = design::select('Design No','Design Name','Chain Weight/Length','status')->where('status','=','Active')->get();
return view('pages.design')->with('design',$design);
}
}
page for listing:
the error occurring while using for-each
#extends('layouts.layout')
#section('content')
<div class="main">
<div class="container col-md-12 col-sm-12 col-xs-12">
<h2 class="text-center">Designs</h2>
#if(count($design)>=1)
<h2>Done</h2>
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Design No</th>
<th>Design Name</th>
<th>Weight/Lenght</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($design as $design)
<tr>
<td>{{$design->Design No}}</td>
<td>{{$design->Design Name}}</td>
<td>{{$design->Chain Weight/Length}}</td>
<td>
<button type="button" class="btn btn-warning">Edit</button>
<button type="button" class="btn btn-danger">{{$design->status}}</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
#endsection
it doesn't allow space in column name it should be in lower cases as design_no , design_name in your DB
and then fetch as
#foreach($design as $new_designs)
<td>{{$new_designs->design_no }}</td>
// and so on
#endforeach
Hope it will work.
try this
{{$design->{'Design No'} }}
Yous should try this:
Controller Page
public function index()
{
//
$designs=design::all();
return view('pages.design',compact('designs'));
}
View Page
#foreach($designs as $design)
<tr>
<td>{{$design->Design_No}}</td>
<td>{{$design->Design_Name}}</td>
<td>{{$design->Chain_Weight/Length}}</td>
<td>
<button type="button" class="btn btn-warning">Edit</button>
<button type="button" class="btn btn-danger">{{$design->status}}</button>
</td>
</tr>
#endforeach

Categories