I have a custom Model which I generated with php artisan make:model.
I want to know if my custom model is connected to the table in my database because I try to show the field using Datatables but it doesn't show the field and I don't get any error.
My model
<?php
namespace App\Modules\Hr\Models;
use App\Models\Model;
use DB;
class Employee extends Model
{
protected $table = "employee";
protected $primaryKey = "nik";
public $incrementing = false;
public $timestamps = false;
protected $fillable = [
"nik",
"employee_name",
"idaddress",
"dom_address",
"hpno",
"email",
"gender",
"npwp",
"birthdate",
"identity_no",
"join_date",
"blood_type",
"is_active",
"end_date",
"birthplace",
"postalcode",
"districts",
"propcode",
"citycode",
"religioncode",
"statuscode",
"doc_npwp",
"photo",
"doc_id",
//
];
}
My controller
public function index(){
return view([
"model" => new Employee,
]);
}
public function data(){
return Datatables::of(Employee::select("*"))->make(true);
}
My view
<table class="table table-bordered" datatable="{{ url("hr/employee/data") }}">
<thead>
<tr>
<th dt-field="nik"> {{ $model->label("nik") }} </th>
{{-- <th dt-field="unit_kind"> {{ $model->label("unit_kind") }} </th> --}}
<th dt-field="employee_name"> {{ $model->label("employee_name") }} </th>
<th dt-field="idaddress"> {{ $model->label("idaddress") }} </th>
<th dt-field="dom_address"> {{ $model->label("dom_address") }} </th>
<th dt-col="#dt-action" sort="false" search="false"> </th>
</tr>
</thead>
</table>
Is there any way to check if my model is connected to the table?
Laravel by default will try to find a table whose name is snake case plural name of Model class..
for e.g :- for Model "Flight" , it will look for table "flights"
however you can prevent this default approach by specifying the table_name inside the model
for e.g:- protected $table_name = "my_flights"
hope this helps
Related
These are my model i want to show some desired column in my view as you can see but the issue is that the desired column like employ name employ no is getting from employ table but course name is not showing or displaying in view table. Is there a way to show the course name in course column in view.
This is my View
<table border="1">
<tr>
<th>Full name</th>
<th>Emp no</th>
<th>salary</th>
<th>course</th>
</tr>
#foreach($data as $item)
<tr>
<th>{{$item['Full_name']}} </th>
<th>{{$item['emp_no']}}</th>
<th>{{$item['salary']}}</th>
<th>
#foreach ($data->courses as $course)
{{$course->course_name}}
#endforeach
<th>
</tr>
#endforeach
</table>
This is my employ model class:
class employ extends Model
{
use HasFactory;
public $timestamps = false;
protected $guarded = [];
public function courses() {
return $this->belongsToMany(course::class, 'employ_course');
}
}
This is my course model class:
class course extends Model
{
use HasFactory;
public $timestamps = false;
protected $guarded = [];
public function employs() {
return $this->belongsToMany(employ::class, 'employ_course');
}
}
And this is my employ_course(pivot table) model class:
class employcourse extends Model
{
use HasFactory;
protected $guarded = [];
}
This is my controller:
public function show()
{
$datas = employ::with([('course')
=> function ($query) {
$query=course::select('course_name');
}])
->select('Full_name', 'salary', 'emp_no')
->get();
return view('teacher.teacher_data', ['datas' => $datas]);
}
in your nested #foreach in view $data should be $item to iterate over all courses from employee.
Then in your controller the $data could be like this:
$datas = employ::with('course')
->select('employ.Full_name', 'employ.salary', 'employ.emp_no', 'course.course_name')
->get();
Remember that class names must start with uppercase letters and database rows with lowercase.
You can achieve that goal with this:
public function show()
{
// you need the employ "id" column to retrieve the related courses
$datas = employ::with('courses:course_name')->get(['id', 'Full_name', 'salary', 'emp_no']);
return view('teacher.teacher_data', ['datas' => $datas]);
}
And your view, I think should be as following:
<table border="1">
<tr>
<th>Full name</th>
<th>Emp no</th>
<th>salary</th>
<th>courses</th>
</tr>
#foreach($data as $item)
<tr>
<td>{{$item['Full_name']}}</td>
<td>{{$item['emp_no']}}</td>
<td>{{$item['salary']}}</td>
<td>
#foreach ($data->courses as $course)
{{$course->course_name}}
#endforeach
</td>
</tr>
#endforeach
</table>
I'm new to Laravel.
I'm trying to access some data from within a partial view.
I tried to put my query inside the boot method of AppServiceProvider, but Im getting this error:
PDOException::("SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vestibulare.app\models\telefone' doesn't exist")
I can't even run php artisan serve.
Why is Laravel assuming my model's name is in the singular?
Here are my models:
class Usuario extends Model
{
protected $table = 'usuarios';
public $timestamps = false;
protected $fillable = [
'nome'
];
public function telefones()
{
return $this->hasMany(Telefone::class, 'id_usuario');
}
}
class Telefone extends Model
{
protected $table = 'telefones';
public $timestamps = false;
protected $casts = [
'id_usuario' => 'int'
];
protected $fillable = [
'id_usuario',
'numero'
];
public function usuario()
{
return $this->belongsTo(Usuario::class, 'id_usuario');
}
}
Here's the boot method inside app\Providers\AppServiceProvider class:
public function boot()
{
$data = Usuario::join(Telefone::class, "usuarios.id", "=", "telefones.id_usuario")
->select(
"usuarios.id as u.id",
"usuarios.nome as nome",
"telefones.numero as numero",
DB::raw("COUNT(numero) AS numero_count")
)
->groupBy("nome")
->orderBy("nome")
->get();
view()->with(["data" => $data]);
}
Initially, the query inside boot method was inside my controller's index method, like so:
class ContactListController extends Controller
{
public function index()
{
// $usuarios = Usuario::all();
// $telefones = Telefone::all();
$data = Usuario::join(Telefone::class, "usuarios.id", "=", "telefones.id_usuario")
->select(
"usuarios.id as u.id",
"usuarios.nome as nome",
"telefones.numero as numero",
DB::raw("COUNT(numero) AS numero_count")
)
->groupBy("nome")
->orderBy("nome")
->get();
return view("index", compact("data"));
}
{...}
}
Why am I getting this error?
How can I access the data I want from within the partial data?
Here are my views:
index.blade.php
<html>
#include("header")
#include("search_contact")
#include("contact_list")
#include("footer")
</html>
contact_list.blade.php <- I want to access data from here
<div class="col-lg-8">
<table id="myTable" class="table text-justify table-striped">
<thead class="tableh1">
<th class="">Name</th>
<th class="col-3">Nº of Phones</th>
<th class="">Phone</th>
</thead>
<tbody id="tableBody">
#foreach ($data as $item)
<tr>
<!-- Test -->
<td>{{ $item }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
I've been reading the docs, watching tutorials and searching for similar questions for over 6 hours. Please help me.
Thank you in advance.
Edit:
I've tried changing the query to the following:
$data = Usuario::join("telefones", "usuarios.id", "=", "telefones.id_usuario")
->select(
"usuarios.id as u.id",
"usuarios.nome as nome",
"telefones.numero as numero",
DB::raw("COUNT(telefones.numero) AS numero_count")
)
->groupBy("nome")
->orderBy("nome")
->get();
Where insteaad of using Telefone::class I'm now using telefones. I got a different error:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'vestibulare.usuarios.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select `usuarios`.`id` as `u.id`, `usuarios`.`nome` as `nome`, `telefones`.`numero` as `numero`, COUNT(telefones.numero) AS numero_count from `usuarios` inner join `telefones` on `usuarios`.`id` = `telefones`.`id_usuario` group by `nome` order by `nome` asc)
Edit 2:
I've changed the following line inside my database.php config file:
'mysql' => [
...
'strict' => true,
...
]
To:
'mysql' => [
...
'strict' => false,
...
]
Now I'm not getting the above error anymore, but there's something wrong with my query because it's coming back empty.
Maybe do you try with DB?
\DB::table('usuarios')->join('telefones', ....
This is what I will do
class Usuario extends Model {
public $timestamps = false;
protected $table = 'usuarios';
protected $with=['telefonos'];
protected $fillable = [
'nome'
];
public function telefones()
{
return $this->hasMany(Telefone::class);
}
}
class Telefone extends Model {
protected $table = 'telefones';
public $timestamps = false;
protected $fillable = [
'id_usuario',
'numero'
];
public function usuario()
{
return $this->belongsTo(Usuario::class);
}
}
//Here's the boot method inside app\Providers\AppServiceProvider class:
// do not use this for querys to database
public function boot()
{
}
class ContactListController extends Controller {
public function index()
{
$usuarios = Usuario::all();
return view("index", $usuarios);
}
{...}
}
// And your view
<div class="col-lg-8">
<table id="myTable" class="table text-justify table-striped">
<thead class="tableh1">
<th class="">Name</th>
<th class="col-3">Nº of Phones</th>
<th class="">Phone</th>
</thead>
<tbody id="tableBody">
#foreach ($usuarios as $usuario)
<tr>
#php
$telefono = $usuario->tefono ?? 'This user has no telephone';
#endphp
<td>Nome: {{$usuario->nome}} Telef: {{$telefono}} </td>
</tr>
#endforeach
</tbody>
</table>
</div>
And finally return mysql values to original state.
Whene i would right a name for a person who i have a secondly key he give me this probleme ,so i right this type of code in larvel 5 so i don't know this is a problem in laravel 8 when i would changed in more details or another problem for more explication this is my code :
<thead>
<tr>
<th scope="col">name</th>
<th scope="col">Adress</th>
<th scope="col">number</th>
<th scope="col">admin name</th>
</tr>
</thead>
#if($administrations)
#foreach($administrations as $administration)
<tbody>
<tr>
<th scope="row">{{$administration->name}}</th>
<td>{!!$administration->adress!!}</td>
<td>{{$administration->number}}</td>
<td>{{$administration->admins->name}}</td>
</tr>
</tbody>
#endforeach
#endif
And this is a code for my controller :
public function storefac(Request $request){
$this->validate($request,[
"name"=> 'required',
"number"=>'required',
"adress"=>'required',
]);
$id=Auth::user()->id;
$emps=new Administrations;
$emps->name=$request->input('name');
$emps->adress=$request->input('adress');
(integer)$emps->number=$request->input('number');
$emps->id_superAdmin=$id;
$emps->save();
return redirect()->back()->with('success','data saved');
And code for my two models ( admin and administration):
class Administrations extends Model
{
protected $fillable = [
'name',
'address',
'number',
'id_Admin'
];
public function admin()
{
return $this->belongsTo('Admin::class');
}
class Admin extends Model
{
protected $fillable = [
'name',
'grade',
'adress',
'number',
'id_user'
];
public function users()
{
return $this->belongsTo(User::class');
}
public function administrations ()
{
return $this->hasOne('Administrations::class');
}
Are Admin and Administration in the same file? If so they need to be in their own file. And I can see you don't close the Administrations class correctly. Also I can see that your foreign keys aren't compatible with laravel either you can rename them to 'user_id' and 'admin_id' or you can do this.
$this->belongsTo(Admin::class, 'id_admin');
And
$this->belongsTo(User::class, 'id_user');
I want to display data from multiple table to one view, first table is Transaction_in and second table is Transaction_in_detail but beside those two other table are involved.
This is Transcation_in Controller
class Transactions_inController extends Controller
{
public function show($id)
{
$supplierList = Supplier::where('id', 'nama')->first();
$transactionin = Transaction_in::where('id', $id)->first();
$deviceTypeList = DeviceType::where('id', 'nama_tipe_device')->first();
$deviceBrandList = DeviceBrand::where('id', 'nama_brand_device')->first();
$transactionindetail = Transaction_in_detail::where('id', 'Transansaction_in_id')->first();
//return view('transactionsin.show', compact('supplierList', 'transactionsin', 'deviceTypeList', 'deviceBrandList', 'transactionindetail'));
return view('transactionsin.show')->with('transactionsin', $transactionin);
return view('transactionsin.show')->with('transactionsindetail', $transactionindetail);
}
}
Transaction_in Model
class Transaction_in extends Model
{
protected $guarded = [];
public function get_suppliers()
{
return $this->belongsTo(Supplier::class, 'Supplier_id');
}
public function get_devicetypes()
{
return $this->belongsToMany(DeviceType::class, 'DeviceType_id');
}
public function get_devicebrands()
{
return $this->belongsToMany(DeviceBrand::class, 'DeviceBrand_id');
}
public function get_transactionindetail()
{
return $this->belongsToMany(Transaction_in_detail::class, 'Transaction_in_id');
}
}
Transaction_in_detail Model
class Transaction_in_detail extends Model
{
protected $guarded = [];
public function get_transction_in_id()
{
return $this->belongsTo(Transaction_in::class, 'Transaction_in_id');
}
public function get_devicetypes()
{
return $this->belongsToMany(DeviceType::class, 'DeviceType_id');
}
public function get_devicebrands()
{
return $this->belongsToMany(DeviceBrand::class, 'DeviceBrand_id');
}
}
I want to display data from Transaction_in_detail table to Transaction_in Controller, but i have this error
count(): Parameter must be an array or an object that implements
Countable (View:
C:\xampp\htdocs\inventory\resources\views\transactionsin\show.blade.php)
and this is transactionsin.show code https://hastebin.com/ilewesucej.xml
What does your table setup look like, specifically what is the relationship between Transaction_in and Transaction_in_detail? You have a One To Many relationship given in Transaction_in_detail::get_transaction_in_id and a Many to Many relationship given in Transaction_in::get_transactionindetail.
The belongsToMany relationship is for Many to Many relationships with a pivot table. Maybe this is supposed to be hasMany instead?
Start by clarifying that relationship correctly. See the docs on relationships in Laravel. Then you can pull the correct data.
Are you trying to get ONE Transaction_in instance with the id $id? In that case, no, you can't iterate over it. Maybe you're trying for something like this?
$transactionin = Transaction_in::find($id);
$transactionindetail = $transactionin->get_transactionindetail;
// $transactionindetail will now be a `Collection` which implements `Countable`.
Also note that you're (and some of the other answers) are mixing up transactionsin and transactionin (without the 's').
1.
You are using first() method which returns a single object , not array. Instead of returning a collection of models, first() method returns a single model instance. Rewrite your code as following -
$transactionin = Transaction_in::where('id', $id)->get();
For reference, Laravel Docs
2.
You don't have to return view and variables twice. Return once as following -
return view('transactionsin.show',compact('transactionsin','transactionsindetail'));
You don't need to return view two times. use compact for set multiple variable.
public function show($id)
{
$supplierList = Supplier::where('id', 'nama')->first();
$transactionin = Transaction_in::where('id', $id)->first();
$deviceTypeList = DeviceType::where('id', 'nama_tipe_device')->first();
$deviceBrandList = DeviceBrand::where('id', 'nama_brand_device')->first();
$transactionindetail = Transaction_in_detail::where('id', 'Transansaction_in_id')->first();
//return view('transactionsin.show', compact('supplierList', 'transactionsin', 'deviceTypeList', 'deviceBrandList', 'transactionindetail'));
return view('transactionsin.show',compact('transactionsin','transactionsindetail'));
}
In blade file check with empty condition.
#if (!empty($transactionsin))
<div class="tale-responsive">
<table class="table table-hover table-bordered">
<thead align="center">
<tr class="table-primary">
<th>Tipe Perangkat</th>
<th>Brand Perangkat</th>
<th>Spesifikasi</th>
<th>Jumlah</th>
<th>Harga</th>
<th>Total Harga</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ $transactionin->get_devicetypes->nama_tipe_device }}</td>
<td>{{ $transactionin->get_devicebrands->nama_brand_device }}</td>
<td>{{ $transactionin->get_transactionindetail->spek_device }}</td>
<td>{{ $transactionin->get_transactionindetail->harga_device }}</td>
<td>{{ $transactionin->get_transactionindetail->jumlah_device }}</td>
<td>{{ $transactionin->get_transactionindetail->total_harga_device }}</td>
</tr>
</tbody>
</table>
</div>
#else
<h6>No Data Found</h6>
#endif
if you want to make object countable you have to use $object->count()in your case $transactionin->count()
I have Laravel 5. framework for bacis e-shop, i try use relationship I have Order, Order_item, Product, Customer model
Order model has realationship with
class Order extends Model
{
protected $fillable = ['user_id', 'status'];
protected $dates = ['created_at'];
/**
* Get the items for the order.
*/
public function items()
{
return $this->hasMany('App\Order_item');
}
public function customer()
{
return $this->hasOne('App\Customer','id');
}
}
Order item
class Order_item extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function product()
{
return $this->hasOne('App\Product','id');
}
}
in controller
public function detail($id)
{
$order = Order::with('customer','items')->findOrFail($id);
return view('admin.detail', ['order' => $order]);
}
and in view I have
<h2>Objednávka č. {{ $order->id }}</h2>
<h3>Zákazník:</h3>
{{ $order->customer->firstname }} {{ $order->customer->lastname }}
<p>{{ $order->customer->email }}</p>
{{ $order->customer->phone }}
<h3>Adresa:</h3>
<p>{{ $order->customer->street }}</p>
<p>{{ $order->customer->city }}</p>
<p>{{ $order->customer->psc }}</p>
<h3>Položky:</h3>
<table class="table table-bordered table-striped">
<thead>
<th>Název</th>
<th>Počet</th>
<th>Cena</th>
</thead>
<tbody>
#foreach($order->items as $item)
<tr>
<th>{{ $item->product->name }}</th>
<th>{{ $item->quantity }}</th>
<th>{{ $item->price }}</th>
</tr>
#endforeach
</tbody>
</table>
and now when i test the code for someone order is function but for someone no, the problem is on {{ $item->product->name }}
is my realationship ok? Its a better solution for my e-shop relationship
i post my complete code to github https://github.com/mardon/MaMushashop
Your order item table is a pivot table. There for the relationships to order and product should be declared as belongsToMany.
belongsToMany is used in Many To Many.
hasMany is used in a One To Many
hasOne is used in One To One
The naming of your table Order_item should be order_product to better reflect what it actually contains.
class order_product extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function product()
{
return $this->belongsToMany('App\Product', 'order_product', 'order_id', 'product_id);
}
public function order()
{
return $this->belongsToMany('App\Order', 'order_product', 'product_id', 'order_id);
}
}
Do like this
$order = DB::table('order')
->join('customer', 'order.customer_id', '=', 'customer.id')
->select('order.*', 'customer.*')
->where('order.id', '=', $id)
->first();
$order_items = Order_item::where('order_id', $id)->get();
return view('admin.detail', ['order' => $order, 'order_items' => $order_items]);
And generate item like this
#foreach($order_items as $item)
<tr>
<th>{{ $item->product->name }}</th>
<th>{{ $item->quantity }}</th>
<th>{{ $item->price }}</th>
</tr>
#endforeach