skip to Main Content

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('AppModelsComment');
}

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 IlluminateDatabaseEloquentCollection::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? 😀

2

Answers


  1. 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.

    Login or Signup to reply.
    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search