How to joining Table in Laravel 5.8 - laravel

I have 2 table users and data .
in users table have :
id | name |email | etc
in data table have :
id | user_id | no_data | etc
i create model Data like this
public function users()
{
return $this->HasMany(\App\User::class ,'id');
}
my Controller :
public function pns()
{
$data = Data::get();
//DB::table('data')
//->join('users','data.user_id','=','users.id')
//->where(['user' => 'something', 'otherThing' =>
// 'otherThing'])
//->get(); // i trying to join this table but still error
return view('admin.data',['data' => $data]);
}
now i want to show view data in table :
on my view blade :
<th>No </th>
<th>id </th>
<th>Name </th>
<th>email </th>
#php
$no=0;
#endphp
#foreach ($data as $i)
<tr>
<td class=" ">{{ ++$no }}</td>
<td class=" ">{{ $i->user_id}}</td>
<td class=" ">{{ $i->users->name}}</td>
<td class=" ">{{ $i->email}}</td>
</tr>
this user_id is showed ,but this 'name' is cant showed and get error :
Property [name] does not exist on this collection instance.
edited my dd($data)
#attributes: array:18 [▼
"id" => 1
"user_id" => 6
"email" => 'q#gmail.com'
//etc
"created_at" => "2019-06-18 17:27:54"
"updated_at" => "2019-06-18 17:27:54"
]

Assuming, your one user can have multiple data. Here is my solution
For User Modal
class User extends Authenticatable
{
<YOUR OTHER CODES HERE>
public function datas(){
return $this->hasMany(Data::class,'user_id','id');
}
}
For Data.php [ Data modal]
class Data extends Model{
<YOUR OTHER CODE>
public function userDetail(){
return $this->belongsTo(User::class,'user_id','id');
}
}
From your controller:
$data = Data:with('userDetail')->get();
echo '<pre>';
print_r($data->toArray()); // This will give you an array of data with user details.

do this $data = Data::with('users')->get();

Use this Query
DB::table('data')
->join('users','data.user_id','=','users.id')
->where('user_id','=',1)
// Here you can also add more wheres
// But make sure where column exists in one of queried table i.e in
// users | data
->select([
'no',
'user_id as id',
'name',
'email'
])
->get(); // i trying to join this table but still error

You need to update your relationship in data model
public function users()
{
return $this->hasMany(\App\User::class ,'user_id');
}
it should be hasMany not HasMany and user_id not id
Then use this: $data = Data::with('users')->get();

use hasOne in your User model
public function data()
{
return $this->hasOne('App\Data', 'user_id');
}
//controller
return view('admin.data')->with($data);

Related

Laravel 9 Calling oldestOfMany() in Controller from Model

I have a Customer model and Customer hasMany Xray_machines. I am trying to select the oldest cert_date from the xray_machines table to populate a table in the view that lists the customer_name and the oldest cert_date. I found oldestOfMany() and it seems to be a good option but it is displaying the first cert_date rather than the oldest.
Customer Model
public function xray_machine()
{
return $this->hasMany(Xray_machine::class);
}
public function oldestCert(){
return $this->hasOne(Xray_machine::class)->oldestOfMany('cert_date','min');
}
Controller
public function xray_unscheduled(){
$due = Carbon::now()->addMonth(3)->endOfMonth()->toDateTimeString();
$customers = Customer::whereHas('Xray_machine', function ($query) use($due) {
$query->where('cert_date','<=', $due);
})
->whereNull('xray_scheduled')->orWhere('xray_scheduled','<>','')
->oldestCert()
->orderBy(
Xray_machine::select('cert_date')
->whereColumn('xray_machines.customer_id','customers.id')
->take(1),'asc'
)
->get()->all();
return view('work_orders/xray_unscheduled', compact('customers'));
}
View
#foreach ($customers as $customer)
<tr>
<td>
{{ $customer->customer_name}}
</td>
<td>
{{ \Carbon\Carbon::parse($customer->oldestCert()->cert_date)->format('Y-m-d')}}
</td>
</tr>
#endforeach

get access to collection laravel

I am a new learner of the laravel framework working on 3 models
customer,
accidents,
License
where the relations are as follows:
public function License()
{
return $this->hasOne(license::class,'driver_id');
}
public function cars()
{
return $this->hasMany(car::class);
}
In the controller I do like this:
public function AdminCustomers()
{
$customers = Customer::with('cars')->with('License')->get();
return view('admin.AdminCustomers',compact('customers'));
}
now I want to display all 3 models' data on view.blade page
<tbody>
#foreach($customers as $customer)
<tr>
<td>{{$customer->id}}</td>
<td>{{$customer->name}}</td>
<td>{{$customer->adderss}}</td>
<td>{{$customer->mobileNo}}</td>
<th>{{$customer->License->id}}</th>
<th>{{$customer->License->Exp}}</th>
<td>{{$customer->cars->id}}</td>
<td>{{$customer->cars->color}}</td>
<td>{{$customer->cars->model_no}}</td>
<td>{{$customer->cars->company}}</td>
</tr>
#endforeach
</tbody>
But it doesn't work and I didn't know where is the problem
the error Exception
Property [id] does not exist on this collection instance.
$customer->cars will return a collection as the relationship is hasMany so you need to loop over the collection in the view
#foreach($customers as $customer)
<tr>
<td>{{$customer->id}}</td>
<td>{{$customer->name}}</td>
<td>{{$customer->adderss}}</td>
<td>{{$customer->mobileNo}}</td>
<th>{{$customer->License->id}}</th>
<th>{{$customer->License->Exp}}</th>
#foreach($customer->cars as $car)
<td>{{$car->id}}</td>
<td>{{$car->color}}</td>
<td>{{$car->model_no}}</td>
<td>{{$car->company}}</td>
#endforeach
</tr>
#endforeach
check the name in the corrisponding table on db, and if its different from "id" specify it into the model, as
protected $primaryKey = 'xxx';

Laravel, how to get selected, db fields

Have a model, from controller, I need access this Model db fields.
Code in controller:
$crud -> get() -> getAttributes();
//$crud->attributesToArray()
print_r($crud);
I was able to get entire table fields, but I need only fields, which are selected. Need dynamically show table with selected fields only, which can change during run time.
Assume you have a query:
$query = Crud::select('id as Id', 'name as Name', 'something')
->selectRaw('CONCAT(id, "-", name) as Serial')
->get();
Without knowing what the query is, to get a table that looks like this
Id
Name
something
Serial
1
A
lorem
1-A
..
....
.........
......
You need to use the Builder instance (before calling ->get()
$query = Crud::select('id as Id', 'name as Name', 'something')
->selectRaw('CONCAT(id, "-", name) as Serial');
$results = $query->get();
dump($query->getQuery()->columns);
/*
[
'id as Id',
'name as Name',
'something',
Illuminate\Database\Query\Expression
]
*/
dump(array_map(function ($column) {
return $column instanceof Illuminate\Database\Query\Expression
? Str::afterLast($column->getValue(), 'as ')
: Str::afterLast($column, 'as ');
}, $query->getQuery()->columns));
/*
[
'Id',
'Name',
'something',
'Serial'
]
*/
So you could that to a view.
$query = Crud::select('id as Id', 'name as Name', 'something')
->selectRaw('CONCAT(id, "-", name) as Serial')
->get();
$columns = array_map(function ($column) {
return $column instanceof Illuminate\Database\Query\Expression
? Str::afterLast($column->getValue(), 'as ')
: Str::afterLast($column, 'as ');
}, $query->getQuery()->columns);
$results = $query->get();
return view('view', compact('columns', 'results'));
And then in your view
<table>
<thead>
<tr>
#foreach ($columns as $column)
<th>{{ $column }}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach ($results as $result)
<tr>
#foreach ($columns as $column)
<td>{{ $result->{$column} }}</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
I'm not sure what you mean by 'selected' database fields. If this is a list of column names coming from a form, you can simply pass that to the get() method:
$crud->get([
'id',
'name',
'created_at',
]);
If instead you want a list of the available columns, you can't get that from the model itself (it is unaware of which columns exist). Instead you can use:
$table = (new Crud)->getTable();
$columns = DB::getSchemaBuilder()->getColumnListing($table);
You can use two methods, get() or all()
$crud -> get(['column1', 'column2'])
$crud -> all(['column1', 'column2'])

Display the connected customer information

I have 2 tables which are user and customer, The first table has the following fields: (id, name, email, password)
Then, the table customer has the following fields: (id, name, firstname).
In my Controller Customer, via my function index(), I have to retrieve id_user from my table user.
Question 1: Is my relationship correct between my 2 tables?
Model Customer
protected $fillable = ['name', 'firstname', 'user_id'];
public function user()
{
return $this->belongsTo('App\User');
}
Model User
public function customers()
{
return $this->hasOne('App\Customer');
}
Question 2: How do I retrieve ID of the user who is connected ?
I have for now this only...
public function index()
{
$customers = Customer::orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
Question 3: I want to understand the two answers, but I would also like to understand how I can adapt my file index.blade.php via my loop, please.
#foreach($customers as $customer)
<tr>
<td> {{$customer->name}}</td>
<td> {{$customer->firstname}}</td>
Thank you for your explanations.
Your models are good. If you want to return user relation for every customer you should try like this:
public function index()
{
$customers = Customer::with('user')->orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
And in your view you should have:
#foreach($customers as $customer)
<tr>
<td> {{$customer->name}}</td>
<td> {{$customer->firstname}}</td>
<td> {{$customer->user->id}}</td>
More about that here.
Question 1: Is my relationship correct between my 2 tables?
Yes, your relationship is correct.
Explanation:
For your customer table, you indicate that a customer profile belongs to one and only one user. This is an inverse one-to-one entity relationship.
For your user table, you indicate that a user has one and only one customer profile. This is a one-to-one entity relationship.
Question 2: How do I retrieve ID of the user who is connected?
Use Laravel's Eager Loading by calling the with() method to retrieve the customer data with the associated user data like this:
public function index()
{
$customers = Customer::with('user')->orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
Explanation:
The returned result can be visualized like this:
{Customer}
|
•id
•name
•firstname
•{user}
|
• id
• name
• email
Finally you can get the results including the user ID in your view like this:
#foreach($customers as $customer)
<tr>
<td>{{ $customer->user->id }}</td>
<td>{{ $customer->firstname }}</td>
<td>{{ $customer->name }</td>
</tr>
#endforeach
For more details on Laravel Entity Relationships see the relevant Laravel documentation.

Select query with relationship laravel one to many

I have a relational mode like this:
Model Siswa
public function kelengkapan()
{
return $this->belongsTo('Modules\PesertaDidik\Entities\SiswaKelengkapan');
}
Model SiswaKelengkapan
public function siswas()
{
return $this->hasMany('Modules\PesertaDidik\Entities\Siswa');
}
I want to use select query with relational
in this controller:
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
this is my blade...
<td>{{$data->kelengkapan->kelas_masuk}}</td>
but an error in the blade like this
Trying to get property 'kelas_masuk' of non-object
I want to show kelas_masuk in the table,
How to use the select query with relation eloquent?
There is no issue with your select query
You are trying to retrieve the data on null that's why you get Trying to get property 'kelas_masuk' of non-object
Controller
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
Blade file
Assume you are using foreach or forloop
<td>{{ $data->kelengkapan->kelas_masuk ?? '--' }}</td> //coalescing operator
Or
<td>
#if(!is_null($data->kelengkapan))
{{ $data->kelengkapan->kelas_masuk }}
#endif
</td>
Here you are used get() method so it's return all the rows
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
in your blade
<td>{{$siswa[0]->kelengkapan->kelas_masuk}}</td>
You can also use foreach loop.
#foreach($siswa as $data)
<tr>
<td>{{$data->kelengkapan->kelas_masuk}}</td>
</tr>
#endforeach

Resources