get value from another table based on id laravel - laravel

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

Related

Laravel Eloquent get data where comparison is true

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();

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.

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

Category relationship in laravel Undefined property: stdClass::

Hi i'm working on a laravel training project . i'm having an issue with models and relationships when i'm trying to get the each product category name .
Here is my Product Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
}
and my Category model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
public function products()
{
return $this->hasMany('App\Product');
}
}
when i try to get the category name for each product like this
#foreach($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->category->name }}</td>
</tr>
#endforeach
while i run the page i get this error
Undefined property: stdClass::$category (View: /var/www/html/projectname/resources/views/my/products/index.blade.php)
can anyone tell me what's causing this error ?
update
here is the table structure
Products : id , name , category_id->unsigned()
Categories : id , name
and here is the code i use to get $products
$user_id = Auth::user()->id;
$products = DB::table('products')->where('user_id', $user_id)->paginate(5);
return view('my.products.index')->withProducts($products);
Your issue is that you're using Laravel's query builder instead of Eloquent, but you're treating the result as if it was Eloquent.
When you do:
$products = DB::table('products')->where('user_id', $user_id)->paginate(5);
The $products variable will contain a Paginator instance, which contains your items as instances of stdClass. If you want to be able to do this with Eloquent, you should try something like this:
$products = Product::with('category')->where('user_id', $user_id)->paginate(5);
This will ensure that the items returned in the paginator are instances of your Product Eloquent model, with the category relationship eager loaded (I.e. it will load the category relationship for each Product returned using one query, rather than 5 queries, one for every Product).
You should then be able to access $product->category->name.

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