select desired column from pivot table and show in view - php

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>

Related

Laravel - PDOException::("SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vestibulare.app\models\telefone' doesn't exist

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.

How to check if a Model connected to the table

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

getting an Invalid argument supplied for foreach() in laravel 5.4

I am trying to access an api but unfortunately I am getting an invalid argument.
Below is my code in the view.
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>Career</th>
</tr>
</thead>
<tbody>
#foreach ($students as $student)
<tr>
<td>{{$student->id}}</td>
<td>{{$student->name}}</td>
<td>{{$student->address}}</td>
<td>{{$student->career}}</td>
</tr>
#endforeach
</tbody>
Below is my controller for the students.
class StudentController extends ClientController
{
public function getAllStudents()
{
$students = $this->obtainAllStudents();
return view('students/all-students', ['students' => $students]);
}
}
The obtain allAllStudents function is taken from the ClientController class
protected function obtainAllStudents()
{
$this->performGetRequest('https://lumenapi.juandmegon.com/students');
}
You need to parse data which should be like
return view('students/all-students', ['students' => $students->data]);
As much I able to see your response from
'https://lumenapi.juandmegon.com/students'
you are getting object which contains array, to traverse array your must first get the object.
Or you can directly use in blade file like
#foreach ($students->data as $student)
and you haven't return in function
protected function obtainAllStudents()
{
//you missed return here
return $this->performGetRequest('https://lumenapi.juandmegon.com/students');
}

Laravel - sorting table by column titles, results not being sorted

I am using Kyslik/column-sortable in my Laravel 5.4 CRUD project for added sortable column headers.
the model:
use Sortable;
//
public $sortable = ['id', 'name', 'email', 'created_at', 'updated_at'];
the view:
<table class="table table-hover">
<thead>
<tr>
<th> #sortablelink('id','#') </th>
<th> #sortablelink('name') </th>
...
</tr>
</thead>
<tbody>
</tbody>
</table>
and the controller:
public function index(Request $request)
{
$keyword = $request->get('search');
//dd($request);
if (!empty($keyword)) {
$customers = Customer::where('name', 'LIKE', "%$keyword%")
->orWhere('email', 'LIKE', "%$keyword%")
->sortable()
->paginate(config('settings.perPage'));
} else {
$customers = Customer::paginate(config('settings.perPage'));
}
return view('admin.customers.index', compact('customers'));
}
The view and the column header links show up and work exactly as expected, but the results aren't sorted at all... What am I missing?
In your view page
#sortablelink should have two arguments
Column name in Database
Column heading in table
So,
#sortablelink('name','Name')
This might help you.

Display name instead of id. Laravel

I have two tables; Students and Grade. Students contains foreign key grade_id referencing Grade.
For viewing students, I have used following code;
Controller:
public function viewStudent()
{
$students=Student::all();
return $students('grade_id');
$grade = Grade::find($id, ['id', 'grade_name']);
return view('students.view',compact('students'));
}
View:
<tbody>
#foreach($students as $student)
<tr class="info">
<td>{{$student->first_name}}</td>
<td>{{$student->middle_name}}</td>
<td>{{$student->last_name}}</td>
<td>{{$student->grade_id}}</td>
</tr>
#endforeach
</tbody>
Model:
class student extends Model
{
//
protected $fillable = ['first_name','middle_name','last_name','grade_id'];
}
It shows grade_id as i have called it. But I want grade_name instead of that. Can anyone help me?
First you need to define a relation to Grade in your student model:
class student extends Model
{
public function grade() {
return $this->belongsTo(Grade::class);
}
}
Then you should be able to eagerly load grades for students with
$students = Student::with('grade')->get();
and access student's grade name with
$student->grade->name
In Model
class student extends Model
{
protected $fillable = ['first_name', 'middle_name', 'last_name', 'grade_id'];
public function grade()
{
return $this->belongsTo('Grade');
}
}
In Controller
$students = Student::with('grade')->get();
In View
#foreach ($students as $student)
$studentGradeName = $student->grade->name;
#endforeach

Categories