Laravel : How to show a multiple rows from DB in one row in view blade - laravel

In my Laravel project, I have a multiple rows in my DB table, similar to each other in every thing except ID, other column called stage
Stages table
ID
name
1
first
2
second
3
third
subjects Table
ID
name
stage_id
1
English
1
2
English
2
3
English
3
I need to show em in a blade like this
#
name
stage
1
English
first, two, three, etc
I already have the relations in my modals, and I am already showing them in my blade by loop, but I just want to group the rows by name and show the different stages
I hope that I explained the case well, I am not very good at explaining
Updates : before editing I wrote a dummy data now I hope I explained the issue in more details
The project idea is that you can create more than faculty
and every faculty has Stages and sections and every section has specialties and every specialty has subjects
now about subjects and stages
user can create subject like English and make it available to the first stage and 2nd and third ..etc ( the available stages in this faculty)
The Stages belongs to Faculty
The Subjects belongs to Stage
so the relations are
Subject Model
public function stage()
{
return $this->belongsTo(Stage::class);
}
Stage Model
public function subjects()
{
return $this->hasMany(Subject::class);
}

As you have "English" Multiple Times, you should have a subject Table :
Stages table
ID
name
1
first
2
second
3
third
Subject table
ID
name
1
English
stage_subject Table :
ID
stage_id
subject_id
1
1
1
1
2
1
1
3
1
Subject Model
public function stage()
{
return $this->belongsToMany(Stage::class);
}
Stage Model
public function subjects()
{
return $this->belongsToMany(Subject::class);
}
Then in your foreach:
#php($subjects = Subject::with('stages')->get())
#foreach($subjects as $subject)
{{ $subject->id }} | {{$subject->name}} | {{$subject->stages->pluck('name')->implode(', ')}}
#endforeach
If you don't / can't do a pivot table, then you can use collection :
#php($subjects = Subject::with('stages')->get())
#foreach($subjects->groupBy('name') as $name => $subjects)
{{ $subjects->first()->id }} | {{$name}} | {{$subjects->pluck('stage.name')->implode(', ')}}
#endforeach

Related

Laravel groupby to get sum but only based on another columns value

I have multiple joins that I am doing to get one list. I can group by a certain value to get a sum but need to merge another column that is not being grouped by. My tables look kinda like this (simplified)
Quote Table
id|Name |Location |
---------------------------------
1|My First Quote|123 Main Street|
Quote Items table
quote_id| item_id
--------------------
1 | 1
--------------------
1 | 2
Items Table
id|Name |Quantity|Type
--------------------------------
1|Dog Food|2 |product
2|Delivery|1 |service
I need to show a final result like this in datatables
Name Location Qty Item
My First Quote | 123 Main Street | 2 | Dog Food
So basically i need to sum on item.quantity and show the product type as item. I have the group by working with a raw sum on the item grouped by item.id where item type is product but the where gets rid of the item service that i need to show on the row.
You can try this:
DB::table("Quote")
->select('Quote.Name','Quote.Location')
->(['Items.Quantity AS Qty','Items.Name AS Item'])
->join("Items","Items.item_id","=","Quote.quote_id")
->get();
You can define a relationship for quotes table
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Quote extends Model
{
public function items()
{
return $this->belongsToMany(Item::class);
}
}
after that, call a sum method with that relation for the column you want.
Quote::withSum('items','Quantity')->get();

Laravel hasOne Relation 2 columns

I have 2 Models first one is(Plan) and the second is (PlanPrice)
I have this columns in table plan_price:
$table->float('price')->comment('Price for one month or one year depends
on country code');
$table->string('country_code')->default('EG');
What I want is to get a plan with price depends on the user country code.
I think you should do this:
return $this->hasOne(PlanPrice::class, 'plan_id')->where('country_code',
$what_ever_your_code_is);

How to create a form that contains data for multiple entities?

I've been trying to think of the best possible way to submit data for multiple entities in a single form.
My use case is that I have a table that contains multiple rows of different entities. I want the ability to go into 'edit' view where some of the columns will become textfields and allow for the value to be changed.
Example
Type | Name | Age
Animal | Eevee | 4
Animal | Sandy | 7
Human | Bob | 24
[Submit]
In edit mode they would be able to change the age for any of the entities. When the user hits save button for the entire list, I want the form to submit all the changes. The problem is that in the update method, I need to know which entities to update with which values
I was thinking of using name attribute to store the entity id of each entity on the input
<input name="{{$entity->id}} value="{{$entity->age}}"></input>
but Animals and Humans are stored in different DB tables. So in the update method of the controller I would have to take the name (which would be the id of the entity) and if it exists as a human
entityToUpdate = Human::find(id)
if entityToUpdate does not exist
entityToUpdate = Animal::find(id)
We use UUIDs in our DB so this would work but it doesn't feel right.
is there a way to group a couple inputs together in a form?
group1
type=animal
id = (Sandys ID)
age = 8
group2
type=human
id =(bobs ID)
age = 25
You could use array notation in your input names in order to get what you want on the server side:
#foreach($entities as $entity)
<input type="hidden" name="group[{{$loop->index}}][type]" value="{{$entity->type}}"/>
<input type="hidden" name="group[{{$loop->index}}][id] value="{{$entity->id}}"/>
<input type="text" name="group[{{$loop->index}}][age] value="{{$entity->age}}"/>
#endforeach
Then on the server side:
foreach(request()->get('group') as $entity) {
// $entity contains ['id'], ['type'], ['age']
}

Laravel eloquent deep count with relationship

I want to get count from deep table and the relationship is A->B->C->D and I want total count of D.
For example;
A: 3 Boss
B: 5 Managers
C: 8 Human Resources
D: 25 Employees
Imagine that every boss has managers and every manager has human resources and also every human resource has employees. How can I get total count every boss's employees' with Laravel. (For instance, first boss has 7 employees at the end.) Should I have to write hard sql code like joins or can I handle with eloquent?
By the way, my tables:
A: id, name
B: id, name
A and B has pivot table.
C: id, name
B and C has pivot table
D: id, name
C and D has pivot table
So far, I tried to:
$a = Boss::with("a.b.c.d")->where("id", 10)->first();
dd($a->b->c->d->count());
It just gave me d's count but I want to all of a's.
There is no native relationship for this case.
I created a HasManyThrough relationship with unlimited levels: Repository on GitHub
After the installation, you can use it like this:
class A extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function d() {
return $this->hasManyDeep(D::class, ['a_b', B::class, 'b_c', C::class, 'c_d']);
}
}
$count = A::find($id)->d()->count();

Laravel 5 hasManyThrough repeating row content

I have the following Database tables:
tour
idtour
other_columns
day
idday
other_columns
tour_has_day
idtour
idday
Each tour has many days, and the days can be used in other tours
So, in the Tour.php model I add this function:
function days () {
return $this->hasManyThrough('App\Day', 'App\Tour_has_day', 'idtour', 'idday');
}
It gives me the correct number of related days but all rows have the same content
I debug the query that it returns:
select
`day`.*,
`tour_has_day`.`idtour`
from `day`
inner join
`tour_has_day` on `tour_has_day`.`idtour` = `day`.`idday`
where
`tour_has_day`.`idtour` = '1'
And it returns
You'll need a many-to-many relation with a pivot table like the one you have for that. The has-many-through relation is for when you have a parent and a child, and the child is the parent of another child.

Resources