How to get data from different Model in one controller in laravel5.8? - laravel-5.8

I have Two Model
1. NewJob
2. ClientInfo
From NewJob model I inserted the data, fetched the data and displayed it nicely...
My question is - In my insert model I am using html dropdown, where all clients name should display dynamically using ClientInfo model. How to do this?
NewJobController code -
public function index(Request $request)
{
$posts = NewJob::orderBy('won', 'desc')->paginate(5);
$clients = ClientInfo::orderBy('id', 'asc');
if ($request->ajax())
{
return view('Admin.NewJob.ajax', compact('posts', 'clients'));
}
else
{
return view('Admin.NewJob.newjob', compact('posts' , 'clients'));
}
}
In view file
#foreach($posts as $post)
<tr>
<td>{{$post->won}}</td>
<td>{{$post->proj_name}}</td>
<td>{{$post->department}}</td>
<td>{{$post->district}}</td>
</tr>
#endforeach
In my Insert Model I used:
<select>
#foreach($clients as $client)
<option value="{{$client->id}}">{{$client->name}}</option>
#endforeach
</select>
But in dropdown List no result is displaying... and also no error displaying.
Plz help... I am new in Laravel.

In my index method I changed this line then it works fine...
$clients = DB::select('select * from client_infos');

Related

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';

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

Laravel 5 how paginate with hasMany relationship

I have a relationship this like;
public function foods() {
return $this->hasMany('App\models\food\food', 'category_id', 'id');
}
My controller file content;
$datas = food_category::where('slug', $slug)->with('foods')->paginate(12);
But incoming datas in there all datas and this is causing bad performance. I want to paginate apply relationship datas.
If you want to paginate foods, try adding a separate method for that:
Model:
class food_category
{
public function getFoodsPaginatedAttribute()
{
return $this->foods()->paginate(12);
}
}
Controller:
$datas = food_category::where('slug', $slug)->get();
View:
#foreach ($datas as $data)
#foreach ($data->foods_paginated as $food)
{{ $food->name }}
#endforeach
#endforeach
Pass paginated collection to the view:
//view
#foreach ($datas as $data)
// do what you need
#endforeach
//link
{{$datas->links()}}

accessing collections within collections laravel 5

I have a table of "rosters" that's pretty much strictly foreign keys. It acceses the "schools" table, "courses" table, and "students" table. So essentially, a 'student' takes a 'course' at a 'school'. My RostersController has this
public function show($id)
{
$roster = Roster::where('course_id', $id);
return view('roster')->with('roster', $roster);
}
My Roster Model is:
public function students()
{
return $this->hasMany('App\Student');
}
My student Model is:
public function roster()
{
return $this->belongsTo('App\Roster');
}
my view is this:
#foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>{{$child->students->first_name}}</p>
#endforeach
The rosters table just saves the student_id rather than all of the student's data that is already in the 'students' table. So i'm trying to access the students table from this relation but when i run this, it tells me that anything related to the students table is 'not on this collection'. I know that I could do things this way if i was working with a hasOne relationship, but how can i accomplish this with a hasMany to output the students table value in each row?
You should try this
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id);
return view('roster')->with('roster', $roster);
}
Try this
Roster.php
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id)->get(); // load the students
return view('roster')->with('roster', $roster);
}
On the view
#foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>
<!-- Loop through the stundents since this returns an collection of students and not just one -->
#foreach($child->students as $student)
{{$student->first_name}} <br>
#endforeach
</p>
#endforeach
Check this for more information on eager loading
The $child->students is a collection. So, you need to use another foreach loop inside the first one.
Your code should look like this:
#foreach ($roster as $child)
<p>{{$child->id}}</p>
#foreach($child->students as $student)
<p>{{$student->first_name}}</p>
<p>{{$student->age}}</p>
<p>{{$sutdent->another_column_in_students_table}}</p>
#endforeach
<p>{{$child->any_other_column_in_roster_table_if_needed}}</p>
#endforeach
So, your first issue is, that
$roster = Roster::where('course_id', $id);
will just return a QueryBuilder instance, you have to use
$roster = Roster::where('course_id', $id)->get();
then for sure, students is a collection, you have to iterate over it like this:
#foreach ($child->students as $student)
{{ $student->yourProperty}} <br>
#endforeach
Update:
I saw you know already about that when to use get() in query laravel 5

How to best get results from 3 different tables based on ID matches in Laravel.

Trying to get products AND variants for a particular supplier.
I can get the products easy enough, but can't figure out how to best get to the variants with matching product_id and send it to the view.
Variants.product_id matches with Product.ID
This works (getting products for the supplier)
public function suppliers($id) {
$supplier = Supplier::orderby('company_name', 'ASC')->find($id);
$products = Supplier::find($id)->products;
$data = [];
$data['supplier'] = $supplier;
$data['products'] = $products;
return view('admin.purchasing.supplier-details', $data);
}
I've tried this to get the variants also without luck.
Controller:
public function suppliers($id) {
$supplier = Supplier::orderby('company_name', 'ASC')->find($id);
$products = Supplier::find($id)->products;
$variants = array();
foreach ($products as $product) {
$product_id = $product->id;
$variants[] = Variant::find($product_id);
}
$data = [];
$data['supplier'] = $supplier;
$data['products'] = $products;
$data['variants'] = $variants;
return view('admin.purchasing.supplier-details', $data);
}
View:
#foreach($products as $product)
<tr>
<td>{{ $product['title'] }}</td>
#foreach($variants as $variant)
#if($variant->product_id == $product['id'])
<td>${{ $variant->price }}</td>
#else
<td>not set</td>
#endif
#endforeach
</tr>
#endforeach
Any tips much appreciated.
First of all , you should have relation set on your models to make this work
like this For exemple :
Supplier.php
public function products()
{
return $this->hasMany('App\Product');
}
Product.php
public function variants()
{
return $this->hasMany('App\Variant');
}
public function Supplier()
{
return $this->belongsToMany('App\Supplier'); //in case you have only one supplier for each product change this to belongsto
}
Variant.php
public function products()
{
return $this->belongsToMany('App\Product'); //not sure if this should be manytomany or one to many , it deppends on what you did
}
anyway now you can do this
Controller
public function suppliers($id) {
$Data = Supplier::where('id',$id)->orderby('company_name', 'ASC')->with('products.variants')->first(); //you will get the supplier with all products associated to him with variants foreach product
return view('admin.purchasing.supplier-details')->with('Data',$Data); // now you just loop the $supplierwithproducts->products to get results (dd the variable to check output)
}
View
{{ $Data->name }} // supplier name since Supplier model was the starting point
#foreach($Data->products as $product) //loop all products related to that supplier
{{ $product->name }} //shows product name (depends on you database columns
#foreach($product->variants as $variant) // loops all variants in the current product
{{ $variant->name }} // shows variants
#endforeach
#endforeach
If you copy and paste this code it might not work ,but this will give you an idea how you should handle relations in laravel (levrage eloquent relations)
Check this for more informations
Laravel Docs
Laracasts Defining Relationships With Eloquent
Laracasts Updating Records and Eager Loading

Resources