Laravel Show Table Relation Only if Has Value - laravel-5

I have 2 tables Category & Transaction
in my model Category :
public function transaction()
{
return $this->hasMany('App\Transaction');
}
in my model Transaction :
public function category()
{
return $this->belongsTo('App\Category');
}
Architecture of my Transactions table :
id | category_id | qty
Architecture of my Categories table :
id | name
Now , how to display in view which i want to display only categories that have quantity(qty) value in Transactions table , i'm may have a lot of category in categories table , but not all categories has quantity in transactions table .
Normal in controller to pass view
public function getChart1()
{
$kato = Category::all();
return view('a.chart1',compact('kato'));
}
So in view :
#foreach($kato as $kat)
{{$kat->name}}
{{$kat->transaction->sum('qty')}}
#endforeach
By normal, but how to make sure the foreach , is not looping the categories with empty quantity?
Thank you
note : if my question were stupid enough, forgive me , i already spend 1 week to study about this .

Try this
#foreach($kato as $kat)
#if($kat->transaction->count() > 0)
{{$kat->name}}
{{$kat->transaction->sum('qty')}}
#endif
#endforeach

Related

hasOneThrough condition on intermediate model

i have 3 tables
student
id
guardian_relation_id
student_guardian
id
student_id
guardian_id
guardian_type
Guardian
id
name
i have a relationship function in student model :
public function guardian(){
return $this->hasOneThrough(Guardian::class,StudentGuardian::class,'student_id','id','id','guardian_id');
}
and its working.
but now i want to get get data where guardian_relation_id = guradian_type
how do i achieve this ?

How to make this Eloquent relationship in Laravel

I have a table called users with a column username. Another table called students with a column code. I have made a hasMany relationship in User model like below and it's working fine.
public function students()
{
return $this->hasMany(Student::class,'code','username');
}
I have another table called institutes where a column is similar to students table named inst. I need to show data from institutes table while showing data of an user. How to make this relationship?
users table
username|mobile|address|password
students table
username|name|inst|roll|reg
institutes table
name|inst|address|phone
This is my home controller
public function index()
{
$admins = User::where('username','=',Auth::user()->username)->get();
return view('home', compact('admins'));
}
And this is my view
#foreach($admins as $key => $admin)
#foreach($admin->students as $student)
{{ $student->reg }}
#endforeach
#endforeach
Add migration to your Students table :
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('set null');
Update your model User on students method :
return $this->hasMany(Student::class);
Add "with method"
$admins = User::where('username','=',Auth::user()->username)->with('students')->get();

laravel has many through piviot table

I have 3 tables
Products
id, name, image
Offers
id,name
Offer_product
id,offer_id,product_id
I am accessing data of product table with pagination using
$list = Product::query()->paginate(6);
now i want the complete record of products with offer name stored in offers table . id of both product and offers are stored in offer_product table where one products can have many offers
In your DB design you have a Many-to-Many relation, which in Laravel is handle by belongsToMany https://laravel.com/docs/5.7/eloquent-relationships#many-to-many.
hasManyThrough is for cascade 1-to-Many -> 1-to-Many case. Let's say an Artist has many Albums and each Album has many Songs, then an Artist has many Songs through Albums. If you need an Artist Songs, then you may use directly hasManyThrough.
In your case your relation in Product.php model should be :
public function offers() {
return $this->belongsToMany(Offer::class, 'Offer_product')->withPivot('id');
}
In Offer.php model :
public function products() {
return $this->belongsToMany(Product::class, 'Offer_product')->withPivot('id');
}
Now if you want all of them with eager loading https://laravel.com/docs/5.7/eloquent-relationships#eager-loading to avoid N(products)+1 calls to database :
$products = Product::with('offers')->get();
foreach ($products as $product) {
echo 'product : '.$product->name.'<br/>';
foreach($product->offers as $offer) {
echo '<br>---- offer : '.$offer->name;
// once you called the relation, then you can access data on pivot table
echo ' - pivot id :'.$offer->pivot->id;
}
}

Laravel 5 multi level category

i currently i have 2 tables category & subcategory and everything works just fine, but i need another level of sub category which will be like category->sub->sub for that matter i tried to find a reasonable solution and i end up with bunch of packages to handle that for me.
now the question is
do i have to delete my category tables and their relations to my
another modes before i try any package or i should just add package top of my current tables?
what is the best package for my purpose base on your experience?
thanks in advance.
You don't need to depend on packages to implement this.
You can design your categories table like following:
|----------|------------|---------------|
| id | name | category_id |
|----------|------------|---------------|
Here category_id is nullable field and foreign key referenced to id of categories table.
For category category_id field will be NULL and for sub-category category_id will be it's parent category id. For sub sub category, category_id will be parent sub category id.
In model, you can write relation like following:
Category.php
/**
* Get the sub categories for the category.
*/
public function categories()
{
return $this->hasMany(Category::class);
}
Now you can get your sub categories like $category->categories.
N.B: You don't need the subcategory table, Only one table will do the work.
Update- Show product categories
Update Category.php:
/**
* Get the parent category that owns the category.
*/
public function parent()
{
return $this->belongsTo(Category::class);
}
In Product.php:
/**
* Get the category that owns the product.
*/
public function category()
{
return $this->belongsTo(Category::class);
}
Now, you need to get product category and all of its parents. It'll be an array of categories from parents to child. Then you can show as you wish.
$category = $product->category;
$categories = [$category];
while (!is_null($category) && !is_null($category = $category->parent)) {
$categories.unshift($category);
}
// $categories = ['parent category', 'sub category', 'sub sub category' ..]
Show category title sequentially
foreach ($categories as $category) {
echo $category->title . '<br>';
}

Getting an ID from Pivot table Eloquent belongsToMany() - Laravel 5.2

I have two items. Shops & Categories. In my Shop model I have declared this relation :
public function categories()
{
return $this->belongsToMany('App\Models\Category');
}
and in my Category model I have this :
public function shops()
{
return $this->belongsToMany('App\Models\Shop');
}
I am able to add Shop in to category by using attach. For example this code :
$shop->categories()->attach($cat_id);
By using the above attach method, a record is automatically created in my pivot table category_shop with category_id and shop_id.
Now, I have a shop loaded to $shop. Like below :
$shop = Shop::findOrFail($id);
Obviously now I have my shop id in $shop->id. My question is how can I get back the category id(s) of this shop by using the above setup.? I am new to laravel.
Since, shop has many categories. You will get many categories id.
$shop= Shop::findOrFail($id);
foreach($shop->categories as $category)
{
print_r($category->id);
}

Resources