Get Eloquent table data from a nested loop - laravel

I am working on a student consultancy project. In the website header's country option, I am showing the value as, when the country is clicked, it will show the subcontinent and countries under the subcontinent. However, there are some popular countries that students are familiar with but unfamiliar with their subcontinent. So that's why those countries will be created under the subcontinent. So, for example, Australia is in Oceania, but Australia is in the subcontinent.
The subcontinent is in one-to-many relations with the country, and countries are in one-to-many relations with the university. So if I create Australia, I have to add something in countries to find the university under Australia. So I am adding one country Australia under subcontinent Australia. That way, I can access the university.
However, the main problem is I don't want to show that in the header's country drop-down menu. So I am trying to select it differently in the controller, which subcontinent doesn't have the same country name under it. So I will pass it with a different variable.
Controller
$dis = '';
$concatenated = collect();
foreach ($divisions as $key => $value) {
$dis = DB::table('subcontinents')
->where('subcontinent_name', '!=', $value->country_name)->get();
foreach ($concatenated as $k => $val) {
if ($val->subcontinent_name != $dis->subcontinent_name)
$concatenated = $concatenated->concat($dis);
}
}
dd($concatenated);
I created the country as a division. I am selecting subcontinents where the name is not the same. It gives output like this: [output][1]. So I tried to concat once if the name didn't exist previously. Now it's showing a null value. How can I solve this? Any kind of idea will also be helpful.

Related

Laravel Relationship with 4 Table

I've got 4 tables:
users
teams
locations
users_teams
my teams table has relationship with locations. (it has location_id field)
users and teams have belongsToMany relationship with users_teams.
users doesn't have directly relationship with locations.
But I need to get coaches in this location.
It means; "get me all coaches; which are belongs to teams of that location"
But couldnt move any to make this.
How can this be possible?
how my "coaches" function of my "Location" model?
If your relationships are set up correctly, and assuming you have an enum column named type with coach as a possible value, you should be able to do something like this:
$coaches = User::where('type', 'coach')
->whereHas('teams.locations', function($query)
{
$query->where('name', 'some place');
})->get();

View data according to class and class group

I had an admin panel where 3 types of user are there Admin, Teacher and Student. Now I want that when student logged in he/she only see data uploaded by admin
According to his/her class and class group like class=10th and group=computer science. I have no idea how can i get this type of thing. I had used following code
$paper = Paper::where('paper_type','PaperSolution' && 'class',Auth::user()->class)->get();
this is not working properly as I am dumping data
dd($paper);
it is giving me null as answer.
you can use more granular wheres passed as array:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
Try this
$paper = Paper::where([['paper_type','PaperSolution'],['class', Auth::user()->class]])->get();
dd($paper);
OR
$paper = Paper::where([['paper_type','=','PaperSolution'],['class','=', Auth::user()->class]])->get();
dd($paper);
Reference for where query using array
ReferenceLink
Please refer to Laravel collection docs to correct syntax.
$paper = Paper::where('paper_type','PaperSolution')
->where('class', Auth::user()->class)
->get();
I did not exactly understand structure of your DB, but at first you need to have corresponding columns to then write any query. Your first option is uploaded by admin so in your uploads table (which is Paper model as I can see from your text) you should have something like uploader_role. Then you have student_class and student_group options. I want to get your attention in fact that this 2 options are users table columns NOT uploads (Paper). So you need to check some permissions of users, then get papers uploaded by admins. You can do that with middleware or just in your controller
$user = Auth::user();
if ($user->class == 10 && $user->group == 'computer_science') {
$papers = Paper::where('uploader_role', 'admin')
// you can add extra where options if that columns exist in papers table and you need to filter them also by class and group
->where( 'class_that_has_permissions', $user->class)
->where( 'group_that_has_permissions', $user->group)
->get();
return $papers;
}
abort(404);
Also be careful with columns that have name class that can return real user class name like App\User, try to use class_name or class_number.

Cross relationship between models (high i lov level)

I have a few models and relationship. People belongs to city, city belongs to region, region belongs to country. How can I display every people from particular country.
I am assuming your models have relations defined already. You could use whereHas() and the model relationships in dot notation to get all the people of the city of the region of the country you're intersted in.
$people = People::whereHas('city.region', function($query) use ($countryId) {
return $query->where('regions.country_id', $countryId);
->get();

Updating a pivot table in Eloquent

I've got a many to many relationship between a student and an institution_contact.
students should only ever have two institution_contacts and I have an attribute on the pivot table named type to be set as 1 or 2.
So, my pivot table looks like this:
institution_contact_student: id, institution_contact_id, student_id, type
I've run into difficulty in deciding how to approach the issue of adding/updating the pivot table. Let's say I have 100 students and I want to assign them a contact with the type of 1.
My current solution is to delete the contact then add it:
$students = Student::all(); // the 100 students
$contactId = InstitutionContact::first()->id; // the contact
foreach ($students as $student) {
// remove existing contact
$student
->institutionContacts()
->newPivotStatement()
->where('type', 1)
->delete();
// add new contact
$student
->institutionContacts()
->attach([$contactId => ['type' => 1]]);
}
However, I'm thinking that this is going to hit the database twice for each student, right? So would I be better off creating a model for the pivot table and removing all entries that matched the student id and the type then simply adding the new ones? Or would creating a model for the pivot table be considered bad practice and is there a better way of accomplishing this that I've missed?
Please note the reason I'm not using sync is because I'm relying on the type attribute to maintain only two contacts per student. I'm not aware of a way to modify an existing pivot without causing issues to my two contacts per student requirement.
Edit:
Instead of creating a model I could run the following code to perform the delete using DB.
DB::table('institution_contact_student') // the pivot table
->whereIn('student_id', $studentIds)
->where('type', 1)
->delete();
If I have understood your question correctly then you can use the updateExistingPivot method for updating your pivot table.But first of course you have to define the pivot in your relationship. For instance,
public function institutionContacts(){
return $this->belongsToMany('institutionContact')->withPivot('type');
}
after this, all you have to do is use the following code:
$student
->institutionContacts()
->updateExistingPivot($contactId, ["type" => 1]);
Hope this helps.

how do I query this relation with eloquent

I'm using Laravel and eloquent obviously.
I have 4 models and tables.
1 => city
2 => location
3 => venue
4 => tag
now bear with me to describe relationship.
a city has many locations and a location belongs to a city.
a location belongs to a venue and a venue has one location.
a venue belongs to many tags and a tag belongs to many venue (Many to many relationship)
Here are the query I wanna executed.
given A city, how can I filter venues of that city based on tags.
example: for city Austin I wanna get venues that have tag "special".
and Also, how many queries are executed for perform this task.Is it efficient to perform this kind of task with this database model.
I tried to be as explicit as possible but if some parts seems vague for you, please don't hesitate to ask.
thanks
Eloquent query below filters result based on relationship:
$venues = Venue::whereHas('location', function($query) use ($city) {
$query->where('city_id',$city->id);
})->get();

Resources