I am creating a mini inventory stock for a fashion store. I am using Laravel/Voyager with BREAD and everything fine. I have 2 tables Sizes and Products with a column in common product_code.
I would like to get the results from Sizes where column product_code = Product 'product_code'.
I have this query in the controller:
$product_code = Product::all();
$allSizes = Size::where('product_code', ($product_code->product_code));
and in browse.blade.php I have:
#foreach ($allSizes as $size)
<tr>
<td align="right">{{$size->size_name}}</td>
<td align="right">{{$size->stock}}</td>
</tr>
#endforeach
I guess the where statement is not working as supposed to.
I want to get the corresponding stock based on product_code for each size from table Sizes
Try This
$product_code = Product::pluck('product_code')->toArray();
$allSizes = Size::whereIn('product_code', $product_code)->get();
and in browse.blade.php:
#foreach ($allSizes as $size)
<tr>
<td align="right">{{$size->size_name}}</td>
<td align="right">{{$size->stock}}</td>
</tr>
#endforeach
I think you're going about this the wrong way. Your tables are related in some way and you need to define a relationship to access the data Eloquently.
If I were building such a database, I think that the relationship between Product and Size is a many to many. I.e. a Product can have many Sizes, and you can also shop for many Products in a certain Size. Thus, your models should have a belongsToMany() relationship to each other.
// Product.php
protected $with = ['sizes']; // eager load product sizes
public function sizes() {
return $this->belongsToMany(Size::class);
}
// Size.php
public function products() {
return $this->belongsToMany(Product::class);
}
Then you can do
// ProductsController.php
public function show(Product $product) {
return $product;
}
You missed to run the query
$product_code = Product::all();
# ::all() will return collection, and you can't access a property of it directly
$allSizes = Size::where('product_code', ($product_code->first()->product_code))->get();
Notice the ->get();
Related
I am working on applying many to many relations on table Accident, Car where the relations are as follows:
In the Accident model:
public function car()
{
return $this->belongsToMany(Car::class,'accident_participateds',
'reportNo','vehicleId');
}
In-car Model
public function accidents()
{
return $this->belongsToMany(Accident::class,'accident_participateds',
'vehicleId','reportNo')->withPivot(['damageAmount', 'IBAN']);
}
I want to display the data from all 3 Models (Car, Accident,accident_participateds)My question is whether these statements are correct in the controller
public function AdminClaims()
{
$claim = Accident::with('car')->get();
$details = Car::with('accidentsr')->get();
return view('admin.AdminClaims',compact('claim','details'));
}
Because when I try to display like this:
<tbody>
#foreach($claim as $claims)
<tr>
<td>{{$claims->ReportNumber}}</td>
#foreach($details as $AP)
<td>{{$AP->vehicleId}}</td>
<td>{{$AP->Location}}</td>
<td>{{$AP->Date}}</td>
<td>{{$AP->damageAmount}}</td>
<td>{{$AP->IBAN}}</td>
#endforeach
</tr>
#endforeach
it print only ReportNumber
kindly tell me where I made a mistake?
From what I understand, you want to display the details of Accident(claim), associated Car and data from the pivot table.
To do so you can try
public function AdminClaims()
{
$claims = Car::with('accidents')->get();
return view('admin.AdminClaims',compact('claims'));
}
And in view
#foreach($claims as $claim)
<tr>
<td>{{$claim->ReportNumber}}</td>
<td>{{$claim->vehicleId}}</td>
<td>{{$claim->Location}}</td>
<td>{{$claim->Date}}</td>
<td>{{$claim->pivot->damageAmount}}</td>
<td>{{$claim->pivot->IBAN}}</td>
</tr>
#endforeach
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';
i have two tables ( Factories , Products )
Factories table has two columns ( id , factory_name )
and Products table has three columns ( id , factory_id , product_name )
i want to display factory_name column in Factories table in blade.php based on factory_id in Products table
the code in Factory Model :
public function products()
{
return $this->hasMany('App\Product');
}
and the code in Product Model :
public function factories()
{
return $this->belongsTo('App\Factory');
}
the code in ProductsController :
public function index()
{
$data['Products'] = Product::with('factories')->orderBy('created_at', 'desc')->get();
return view('all_products')->with($data);
}
and the code in view :
#foreach ($Products as $Product)
<tr>
<td>{{$Product->id}}</td>
<td>{{$Product->factory_name}}</td>
<td>{{$Product->product_name}}</td>
</tr>
#endforeach
and this not work ... so how i get factory_name
It's always a good idea to add {{dd($data)}} to blade file to see what you have.
I think the relation between products and factories is one-to-many. In this case, it would be better if you make the function name factory instead of factories.
public function factory()
{
return $this->belongsTo('App\Factory');
}
Unless it's a correct syntax that I'm not familiar with, the problem should be $data['Products'] and with($data). Let's change them:
public function index()
{
$data = Product::with('factory')->orderBy('created_at', 'desc')->get();
return view('all_products')->with('Products', $data);
}
Now, you have $Products on your blade file.
Since you get factory_name through relation, factory info is associated with a key. You need this:
<td>{{$Product->factory->factory_name}}</td>
its easily like this :
#foreach ($Products as $Product)
<tr>
<td>{{$Product->id}}</td>
<td>{{$Product->factories->factory_name}}</td>
<td>{{$Product->product_name}}</td>
</tr>
#endforeach
since you already have a relationship called factories between your two models
As you have shown that you are trying fetching Products along with factories
Product::with('factories')->orderBy('created_at', 'desc')->get();
So the result that you will get from this query will be in the following format
{
id: product_id,
factories: {
id:factory_id,
factory_name: factory_name,
...
}
}
So in order to fetch the factory name in products list you need to use:
<td>{{$Product->factories->factory_name}}</td>
instead of
<td>{{$Product->factory_name}}</td>
Hope this solve your problems
Good day. I have researched about it, but nothings matched with my problem. Here's the scenario. I have courses table, and 3 more tables, assignments, quizzes, and reports. Now, what I want is, to get all of the records from the table assignments, quizzes, and reports and loop through all the records below a specific course.
Example Output: The order should be according to the first created item.
Course1
Assignment1
Quiz1
Quiz2
Assignment2
Report1
How can I do that with three different tables? I know how to use the basic many to many relationship, but for this. I really got stacked. Need help guys.
Note: I'm using Laravel5.1
Update1 — Course.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $fillable = [];
public function assignments(){
return $this->belongsToMany('Assignment');
}
public function quizzes(){
return $this->belongsToMany('Quiz');
}
public function reports(){
return $this->belongsToMany('Report');
}
}
UPDATE2 as per request
<div class="table">
<table class="tabled">
<thead>
<tr>
<th>x</th>
</tr>
</thead>
<tbody>
#foreach($course_items as $course_item)
<tr>
<td>
{{ $table_name }} {{ $course_item->name }}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
Based on the limited information available from your question, you will need to merge your relations into a single collection.
Using unions would be a better solution, if feasible, to improve efficiency, but hey-ho.
// Prepare not deleted scope
// I would suggest using Laravel's SoftDeletes, as it'll be better than writing your own implementation. But if not, you would be better to create this as a reusable scope on your model
$notDeletedScope = function ($query) {
return $query->where('deleted', 0);
};
// Find course with non-deleted relations
$course = Course::with([
'assignments' => $notDeletedScope,
'reports' => $notDeletedScope,
'quizzes' => $notDeletedScope,
])
->findOrFail($id);
// Combine relations into single collection
$merged = collect($course->assignments);
$merged = $merged->merge(collect($course->quizzes));
$merged = $merged->merge(collect($course->reports));
// Sort merged relations by created_at
$merged = $merged->sortBy('created_at');
#foreach ($merged as $relation)
#if ($relation->type === 'assignment')
// ...
#elseif ($relation->type === 'quiz')
// ...
#elseif ($relation->type === 'report')
// ...
#endif
#endforeach
Add to each model:
public function getTypeAttribute()
{
return snake_case(substr(strrchr(get_class($this), '\\'), 1));
}
Very new to laravel and trying to do something simple but keep getting stuck. I have 3 tables
countries:
id
country
regions:
id
region
country_id
wineries:
id
winery
country_id
region_id
joined together as follows:
public function index()
{
$wineries = Country::join('wineries', 'countries.id', '=', 'wineries.country_id')
->join('regions', 'regions.id', '=', 'wineries.region_id')
->select('countries.*')
->orderBy('countries.country', 'asc')
->get()
->unique();
return view('winery.index', compact('wineries'));
}
I'm trying to return a table organized by country with each winery listed along with it's region. Countries without wineries are not to be displayed. My Index page, looks like this:
<tbody>
#foreach ($wineries as $country)
<tr>
<td colspan="2">{{ $country->country }}</td>
</tr>
#foreach ($country->wineries as $winery)
<tr>
<td>{{ $winery->winery }}</td>
<td>{{ $winery->region }}</td>
</tr>
#endforeach
#endforeach
</tbody>
All works well except I can't get the associated region for each winery since the region is not a part of the $winery array. Any advice on how to make it a part of array or how to accomplish this using a different query?
In laravel you can define relationships for Models. Models represent a Model of data (normally related to a DB table, but not always)
Laravel uses Eloquent for database defining relational tables within PHP.
http://laravel.com/docs/4.2/eloquent#relationships
For your case it sounds like you have three Models
Countries
Region
Wineries
Your counties will have many regions, but a region will only have one country.
Your regions will have many wineries, but a winery will only have one region.
To spec your relationships within Eloquent you want to write the following functions within each
(Country)
public function regions()
{
return $this->hasMany('Region');
}
(Region)
public function country()
{
return $this->hasOne('Country');
}
public function winery()
{
return $this->hasMany('Region');
}
etc..
From there you can then relate the data via the models. So if you have a Country object and wanted to get the regions you would do
$country->regions
You might want to wrap this in a loop to print all of the regions
foreach($country->regions as $region) {
echo $region->name;
}
Hope this helps
Define relationships using model. Laravel has Eloquent model in built. It's very easy to query database using that. Learning curve is well worth it.