Error While Fetching db using eloquent - php

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

Related

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

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

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

How to update record 'pay' laravel?

I'm trying to update my 'pay' record in the DB after pressing a button in a table row, but it shows this error when pressing the button:
ErrorException in 0db55b8fee884912074e1a4700061051aeb18bcc.php line
15: Undefined variable: users (View:
/Users/mauricio/code/cnr/resources/views/pages/users.blade.php)
I don't know why it gives me that error when I have use the users variable before in the blade file.
Here is my Registration Controller:
<?php
namespace App\Http\Controllers;
use DB;
use App\User;
class RegistrationController extends Controller
{
public function updatePay(User $id)
{
DB::table('users')->where('id', $id)->update(['pay' => 1]);
return view('pages.users');
}
}
Welcome controller:
public function usersAdmin()
{
$users = DB::table('users')->get();
return view('pages.users', compact('users'));
}
Routes file:
// for admin only
Route::get('/users', 'WelcomeController#usersAdmin');
Route::post('/users/{id}', 'RegistrationController#updatePay');
Here is my view
#extends('layouts.master')
#section('content')
<table class="highlight">
<thead>
<tr>
<th data-field="id" hidden="">ID</th>
<th data-field="name">Nombre</th>
<th data-field="last_name">Apellidos</th>
<th style="text-align: right;">Acciones</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->last_name}}</td>
<td style="text-align: right; width: 30em">
#if( $user->isAdmin )
{{"ADMINISTRADOR"}}
#elseif( $user->pay )
<a class="waves-effect waves-light btn yellow darken-2"><i class="material-icons left" style="margin:0">create</i></a>
<a class="waves-effect waves-light btn red darken-1"><i class="material-icons left" style="margin:0">delete</i></a>
#else
<form method="POST" action="/users/{{$user->id}}">
{{ csrf_field() }}
<button type="submit" class="waves-effect waves-light btn green lighten-1"><i class="material-icons left" style="margin:0">done</i></button>
</form>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
#endsection
You need to retrieve users and send it to the view similar like this:
Controllers:
public function methodName()
{
$users = User::all();
return view('path.to.view')->with(compact('users'));
}
Also, You have two choice to use:
First
public function updatePay($id)
Second
public function updatePay(User $user)
{
DB::table('users')->where('id', $user->id)->update(['pay' => 1]);
and instead of return view('pages.users'); use return redirect()->url('users'); in the updatePay method.

Call to a member function delete() on null / AdminHomeController.php line 26:

Using the multi_auth from laravel 5.3 im trying to make a delete/edit/update button.
Im trying to delete an user from the admin dashboard retrieving information from the users table.
Actually my first problem is with the destroy function.
This is my destroy route:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
This is my controller from admin:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AdminHomeController extends Controller
{
public function __construct()
{
$this->middleware('admin.user');
}
public function index()
{
$users = User::all();
return view("admin-home")->with('users', $users);
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
Flash::error('El usuario ' . $users->name . '$ ha sido eliminado con exito!');
return redirect()->route('admin-home');
}
}
View with delete button:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="col-sm-offset-2 col-sm-8">
#if (count($users) > 0)
<div class="panel panel-default">
<div class="panel-heading">
Todos los Usuarios
</div>
<div class="panel-body">
<table class="table table-striped user-table">
<thead>
<th>Nombre:</th>
<th> </th>
<th>Email:</th>
<th> </th>
<th>Acciones:</th>
<th> </th>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td> </td>
<td>{{ $user->name }}</td>
<td> </td>
<td>{{ $user->email }}</td>
<td> </td>
<td>
<i class="glyphicon glyphicon-trash" aria-hidden="true"></i>
</td >
<td>
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
</td>
<td> </td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
</div>
</div>
#endsection
Thank you!
Check $id in
$users = User::find($id);
$users->delete();
Object $users is null because user didn't found in database or $id is incorrect
After playing around with the code i found this usefull:
In the view i had 2 buttons the delete and the edit ones, i changed:
{{ route('users.destroy', $user->id) }}
{{ route('users.edit', $user->id) }}
for:
{{ url('users.destroy', $user->id) }}
{{ url('users.edit', $user->id) }}
And now i can see the buttons without any problems, the issue now is the same as before, the function destroy gives me an error.
This is the route that causes the error:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
Error: No query results for model [App\User].
This is my User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
And still can't find the issue.. #edwardstock

Categories