Recommand · October 14, 2021 0

Laravel – condition on with()

I wanted to join table NotificationTypes with UserEnabledNotificationTypesId on the NotificationTypesId column of UserEnabledNotifications , only for the rows in which deleted_at column of NotificationTypes table is null. I’ve tried as below. But it is not sorting for the null value of deleted_at column in NotifocationTypes table. Any solutions?

UserEnabledNotifications::with('userNotications', function ($query){


public function userNotifications(){
  return $this->belongsTo(NotificationTypes::class, 'notificationTypesId','id');

You need to pass the with/closure as an array key/value pair

UserEnabledNotifications::with(['userNotifications' => function ($query){

To get only the UserEnabledNotifications that have userNotifications that aren’t deleted, you need whereHas

UserEnabledNotifications::whereHas('userNotifications', function(Builder $query) {
    ->with(['userNotifications' => function($query) {
    }])->select('userId', 'notificationTypesId')->get();

Try with this query replace column with actual column. No need to check for the NULL value of deleted_at. It will default check for NULL.

UserEnabledNotifications::with(['userNotifications', function ($query){
    $query->orderBy('column', 'ASC');

Let me know the results.