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:
-
Is there any better method instead of creating a third controller?
-
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
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.
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).Second you’re calling
Comment::find($id)
withcomments()
relation. you should call aUser
class, like below snippet: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.