Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 2 years ago.
0

You already identified you relationships. Make a class for every entity (school, project, ...). Inside the classes define the relationships.
You submit the form to a controller method.

function method(){
$query = Project::with('area', 'school', 'country'); //names of eager loaded relationships

$name = Input::get('name');
if($name && !empty($name)){
$query = $query->where('name', 'LIKE', '$'.$name.'$');// where clause for name column
}

$school_id = Input::get('school_id');
if($school_id)
$query = $query->where('school_id', '=', $school_id); //foreign key must have the value $school_id

$country_id = Input::get('country_id');
if($country_id)
$query = $query->whereHas('countries', function($countryQuery) use ($country_id){
$countryQuery->where('id', '=', $country_id); //id is the primary key in countries
}); //select only those project wich have at least one country fulfilling the $countryQuery formed in the passed closure.

$area_id = Input::get('area_id');
if($area_id)
$query = $query->whereHas('areas', function($areaQuery) use ($area_id){
$areaQuery->where('id', '=', $area_id); //is is the primary key in areas
});

$result = $query->get();// make the query and load the data
//result is a collection
return View::make('...')->with('projects', $result);
}

Read here about querying relationships.
Inside the view you can get the relationship properties like so:

@foreach($projects as $project)
{{ $project->name }}<br/>
School: {{ $project->school->name }}<br/>
Areas: 
@foreach($project->areas as $area)
{{ $area->name }}, 
@endforeach
Countries: 
@foreach($project->countries as $country)
{{ $country->name }}, 
@endforeach
<br/><br/>
@endforeach

$project->countries works using magic methods. It returns a collection of related countries. The name is equivalent to the relationship name. Use it to access the eager loaded data.

Last updated 9 years ago.
0

Thanks Firtzberg!. I did finally figure out a longer way that works, btu it's kind of ugly and messy. This looks much more elegant and better utilizes the power of Laravel and Eloquent. I will definitely give this a try.

0

take a look at Query Scopes

0

Sign in to participate in this thread!

Eventy

Your banner here too?

plweil plweil Joined 21 Aug 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.