Skip to content
Advertisement

Laravel whereNull and where clause returns empty object

I’m new to laravel. I tried to fetch some records from my database which are “parent” column is “null”. But it returns always empty object. Then I got the query using toSql() function and ran it manually on database. Query works fine. Why laravel returns nothing?

laravel version is : 8.1.0

here is my model

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'child_level',
        'type',
        'meta_url',
        'meta',
        'parent'
   ];

    public function teacher() {
        return $this->belongsToMany(
           Teacher::class,
           'category_teachers',
           'category_id',
           'teacher_id',
         );
    }
}

here is my function in controller

public function mainCourses() {
    $main_courses = Category::whereNull('parent');
    if (isset($main_courses)) {
        return response(['main_courses' => $main_courses], 200);
    }
    return response(['message' => 'No main courses in database'] , 404);
}

this is the database table

this is the database table

when i call to the method it returns response like this.

enter image description here

I want to return all the records with ‘parent’ column is ‘null’. what is the wrong with this? is there an other way to do this? Help me…

Advertisement

Answer

$main_courses = Category::whereNull(‘parent’);

$main_courses in this case will be just a query builder

you should get the result from DB using get() function

$main_courses = Category::whereNull('parent')->get();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement