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');
Related
Try access to show method in VehicleController() and return error: Attempt to read property 'customer' on null.
*ERROR: Property [full_name] does not exist on this collection instance
VEHICLE MODEL
class Vehicle extends Model
{
use HasFactory;
protected $table = 'vehicles';
protected $fillable = ['customer_id', 'model_name', 'brand',
'color', 'year', 'plate_number','engine_number', 'mileage', 'license_number',
'vehicle_type', 'photo_cover'
];
public function customer ()
{
return $this->hasMany(Customer::class);
}
}
CUSTOMER MODEL
class Customer extends Model
{
use HasFactory;
protected $table = 'customers';
protected $fillable = ['full_name', 'customer_type', 'email',
'phone_main', 'phone_mobile', 'doc_cpf', 'doc_cnpj', 'city', 'state',
'address', 'neighborhoods', 'number', 'zip_code'
];
public function vehicle ()
{
return $this->hasOne(Vehicle::class);
}
}
VEHICLE CONTROLLER (show)
public function show(Vehicle $vehicle)
{
$vehicle = Vehicle::select(
'vehicles.id', 'vehicles.model_name', 'vehicles.brand', 'vehicles.year', 'vehicles.color', 'vehicles.mileage',
'customers.full_name', 'vehicles.plate_number', 'vehicles.vehicle_type', 'vehicles.photo_cover'
)
->join('customers', 'customers.id', '=', 'vehicles.customer_id')
->get();
return view('admin.cars.show')->with('v', $vehicle);
}
VIEW (show.blade.php)
<?php
<td>CUSTOMER:</td>
<td class="view-row">
{{ $v->customer->full_name }}
</td>
<td>MODEL:</td>
<td class="view-row">
{{ $v->model_name }}
</td>
<td>BRAND:</td>
<td class="view-row">
{{ $v->brand }}
</td>
I don't know how to solve this, I made this change, but it didn't work. See below:
<td>CUSTOMER:</td>
<td class="view-row">
{{ $v->customer->full_name ?? 'Customer Empty' }}
</td>
VEHICLE MODEL replace this
public function customer ()
{
return $this->hasMany(Customer::class);
}
to
public function customer ()
{
return $this->belongsTo(Customer::class);
}
and VEHICLE CONTROLLER (show) replace to
$vehicle = Vehicle::with('customer')
->paginate(10);
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.
I am trying to get data by using Laravel Eloquent HasMany (reverse) relationship but I am not getting access. Whenever I try, it shows Trying to get property 'name' of non-object
I have two models. Category and Article. Category hasMany Articles. Here are the models:
Category Model
protected $fillable = [
'user_id', 'name',
];
public function articles()
{
return $this->hasMany('App\Models\Article');
}
Article Model
protected $fillable = [
'user_id', 'headline', 'summary', 'body', 'status', 'cover_image', 'image_caption', 'image_credit', 'cover_video', 'video_caption', 'video_credit', 'category', 'meta', 'tags',
];
public function category()
{
return $this->belongsTo('App\Models\Category','category');
}
Article Controller
public function pendingposts()
{
$user = Auth::user();
$articles = Article::all();
return view('admin.article.pending-posts')->with(['user' => $user, 'articles' => $articles]);
}
View Blade (admin.article.pending-posts)
#foreach($articles->where('status', 'submitted')->sortByDesc('updated_at') as $article)
<tr>
<td >{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
#endforeach
here in blade, I can not access category through eloquent BelongsTo feature and I am not getting the reason behind getting the message:
ErrorException (E_ERROR)
Trying to get property 'name' of non-object (View:
C:\xampp\htdocs\joliadmin\resources\views\admin\article\pending-posts.blade.php)
You should try this:
public function pendingposts()
{
$user = Auth::user();
$articles = Article::with('category')
->where('status', 'submitted')
->sortByDesc('updated_at')
->get();
return view('admin.article.pending-posts')->with(compact('user', 'articles'));
}
#foreach($articles as $article)
<tr>
<td>{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
#endforeach
Updated Answer
Category Model
protected $fillable = [
'user_id', 'name',
];
public function article()
{
return $this->hasMany('App\Models\Article');
}
it worked after changing 'Article' tables 'category' column in 'category_id'. Thanks for helping.
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