skip to Main Content

I’m new using Laravel.
I have a model Member with ‘dateOfBirth’ field and an append field called ‘category’ (it has information with sports category depending from age like (Under 10, Under 15, Junior, Senior, Veteran…) so it cannot be in DB because it change every sport season.

But I need filtering members having a condition depending on age.

    $all = Member::where('status', '<>', 'pending');
    if ($category != null) {
        $all = $all->whereIn('category', $category);
    }

This is not working because I have an error telling that column doesn’t exist:

Column not found: 1054 Unknown column 'category' in 'where clause'

Is there a way that I can solve it?

2

Answers


  1. You can use switch case, which allows you to customize SQL queries based on different conditions for each category.

    $members = Member::where('status', '<>', 'pending');
    
    if ($category !== null) {
        switch ($category) {
            case 'Under 10':
                $members = $members->where('dateOfBirth', '>=', now()->subYears(10));
                break;
            case 'Under 15':
                $members = $members->where('dateOfBirth', '>=', now()->subYears(15));
                break;
            case 'Junior':
                // Conditions for Junior category
                break;
            case 'Senior':
                // Conditions for Senior category
                break;
            case 'Veteran':
                // Conditions for Veteran category
                break;
        }
    }
    
    $members = $members->get();
    
    Login or Signup to reply.
  2. The problem is with append column conditioning in laravel.
    You can use whereRaw clause with mysql raw sql query.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search