Q:

Laravel with() relationship if record exists

Imagine this simple query.  
User::with(['company' => function ($query) use($request) {
      $query->where('companies.name', 'like', '%'.$request->name.'%');
}])->get();

This may return something like the below collection if the specified company doesn't exist. 
"data": [
        {
            "id": 1,
            "company": null
        }
    ],

The query runs and returns a collection even if the company value is null. The problem is that in this situation I don't want record to be returned. I only want records where "company" is not null. 
How can I implement this in to my query?

A:

Using ->with(["company" => function(){ ... }]) doesn't filter the parent User query based on the logic, it simply limits what's returned in the company relationship. To limit AND filter, you need to use ->whereHas() in conjucntion with ->with():
User::with(["company"])->whereHas("company", function($query) use($request){
    $query->where("companies.name", "like", "%".$request->name."%");
})->get();

In some cases, you may need to duplicate the logic in ->whereHas() to the function in ->with(), but since you're limiting the query results based on the relationship, you shouldn't have to.

