Home > Mobile >  Laravel: When call function from another controller, the relationship query not work
Laravel: When call function from another controller, the relationship query not work

Time:10-20

I have two controllers (FirstController, SecondController) that use the same functions, to avoid rewriting them I thought of creating another controller (ThirdController) and subsequently calling the functions through it.

the problem is that if in ThirdController there are relationship query they give me the error that "they don't exist".

example:

User Model

class User extends Authenticatable implements AuthenticatableUserContract
{
    use HasFactory, Notifiable;

    public function comments(){
        return $this->hasMany('App\Models\Comment');
}

ThirdController

class ThirdController extends Controller
{
    public static function example($id){
        $comments = Comment::find($id)->comments();
        return $comments;
    }
}

FirstController/SecondController

public function example2(Request $request){
    return ThirdController::example($request->id);

When call the route it give me error: BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::comments does not exist.

my questions are:

  1. Is there any better method instead of creating a third controller?

  2. Is there a solution to this?

p.s. I know I could very well build the queries without exploiting the relationship, but where's the beauty of that? :D

CodePudding user response:

You do not need to create 3rd controller. You can create a class and here you write the query in a function and use this class in controller1 and controller2 by dependency injection.

CodePudding user response:

  1. First thing that's not a best practice to define a static method in one controller and call it in another controller (not recommended way).

  2. Second you're calling Comment::find($id) with comments() relation. you should call a User class, like below snippet:

class ThirdController extends Controller
{
    public static function example($id){
        $comments = User::find($id)->comments();
        return $comments;
    }
}
RECOMEND APPROACH:

Creat a one seperate service/repository class in which you'll define a common method i.e. getUserComments() and use it in both or all of three controllers (upto your requirement/needs). By this way you implementations will be on a centric place.

If you want learn about Repository pattern you can get basic idea from: Article#1

  • Related