Search code examples
if-statementmodellaravellaravel-4eloquent

if/else Logic in Eloquent Query


I need to be able to query a model based on specific criteria within a route closure.

I have this route:

Route::get('courses/{category_slug}/{slug}', function($category_slug, $slug) {
    $category = Category::where('slug', $category_slug)->first();

    $course = Course::leftJoin('categories', 'categories.id', '=', 'courses.category_id')
        ->where('categories.slug', '=', $category_slug)
        ->where('courses.slug', '=', $slug)
        ->orWhere('categories.parent_id', '=', $category->id)
        ->where('categories.slug', '=', $slug)
        ->firstOrFail();

    return View::make('courses.show')->with('course', $course);
});

This partially works but I need to be able to either use get() or firstOrFail() depending on whether the route points to a sub-category or an actual page.

It would also be nice to change the name of the variable based on this criteria, as well as the return value to use a different blade template.

Is this approach feasible? Thanks.

UPDATE: I almost have it working using:

http://paste.laravel.com/zod

The problem is, if the query for $sub_category doesn't return anything I get a model not found error.


Solution

  • OK, I got it working using:

    Route::get('courses/{category_slug}/{slug}', function($category_slug, $slug) {
        $category = Category::where('slug', $category_slug)->first();
        $sub_category = Category::where('slug', $slug)->first();
    
        if (!is_null($sub_category)) {
            if ($sub_category->slug === $slug) {
                $courses = Course::leftJoin('categories', 'categories.id', '=', 'courses.category_id')
                    ->where('categories.parent_id', '=', $category->id)
                    ->where('categories.slug', '=', $slug)
                    ->get();
    
                return View::make('courses.index')->with('courses', $courses);
            }
        } else {
            $course = Course::leftJoin('categories', 'categories.id', '=', 'courses.category_id')
                ->where('categories.slug', '=', $category_slug)
                ->where('courses.slug', '=', $slug)
                ->firstOrfail();
    
            return View::make('courses.show')->with('course', $course);
        }
    });
    

    There is probably a better way, so if anyone can shed some light on it that would be great.