Harrish Kumar
Harrish Kumar

Reputation: 126

Why constructor returns a null in Laravel 5.6

class AdminController extends Controller
{
    public function __construct() {
      $notification = Notification::where('read_status', 0)->get();
    }
}

In $notification variable constructor returns an null while data is present in notifications table.

Upvotes: 0

Views: 421

Answers (1)

Robert
Robert

Reputation: 5963

Constructors do not return values, their only purpose is to instantiate class instances.

If you want to fetch data and use it in your class, you can do something like:

class AdminController extends Controller
{
    private $notifications;

    public function __construct()
    {
        $this->notifications = Notification::where('read_status', 0)->get();
    }
}

or

class AdminController extends Controller
{
    private $notifications;

    public function __construct()
    {
         $this->loadUnreadNotifications();
    }

    private function loadUnreadNotifications()
    {
        $this->notifications = Notification::where('read_status', 0)->get();
    }
}

After which you can use $this->notifications in your other controller methods.

Upvotes: 1

Related Questions