How to verify if an eloquent parent model exists in another connection in laravel?

360 Views Asked by At

I'm using the eloquent method has() to retrieve only rows where the parent exists and is not deleted and it's working well.

But this doesn't work when am passing "user" as a parameter because the user is coming from a different connection.

I have set the connections in both models but am still getting a table not found error for users. Please how can I do to check if the parent from another database connects exist? For example.

My Course model

class Course extends Model
{
    protected $connection= "mysql";
    
    public function user(){
        return $this->belongsTo(User::class);
    }
}

My User model from another database connection "accounts".

class User extends Model
{
    protected $connection= "accounts";
    
    public function courses(){
        return $this->hasMany(Course::class);
    }
}

And in my CourseController, I want to do this.

class CoursesController extends Controller
{
   public function index(Request $request){
       $term = $request->get("query","");
       return Course::has("user")->where("name","like","%$term%")->paginate(12);
   }
}

This will work if the courses table and users table are in the same database but since there aren't am getting a table or view not found SQL error.

If there was a way to pass in the connection name in the has method it will be great but the has method only takes one parameter which is the model name.

I really need to get this working and my users are stored in another database.

0

There are 0 best solutions below