skip to Main Content

I noticed that in web.php I’m able to access find() of Listing model (that I created)

Route::get('listings/{id}',function($id){
return view('listing',[
    'listing'=>Listing::find($id)
]); });

When I checked Listing model I found that it extends IlluminateDatabaseEloquentModelclass. But I couldn’t locate find() there. On further inspection I discovered that the above mentioned find() is a part of IlluminateDatabaseEloquentBuilder class. Question is, how is my Listing model able to access IlluminateDatabaseEloquentBuilderor does it happen through IlluminateDatabaseEloquentModel, if yes, how?

2

Answers


  1. Laravel uses some "magic" ways to do thing like this.
    You can see the way it does this by forcing an Exception in a find method like this:

        try {
            Model::findOrFail('aa');
        } catch (Exception $e) {
            Log::error($e);
        }
    

    This will show you the path the code took

    It will look like this:

    Stack trace:
    #0 /var/www/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php(23): IlluminateDatabaseEloquentBuilder->findOrFail('aa')
    #1 /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2335): IlluminateDatabaseEloquentModel->forwardCallTo(Object(IlluminateDatabaseEloquentBuilder), 'findOrFail', Array)
    #2 /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2347): IlluminateDatabaseEloquentModel->__call('findOrFail', Array)
    #3 /var/www/app/Http/Controllers/Management/Controller.php(68): IlluminateDatabaseEloquentModel::__callStatic('findOrFail', Array)
    #4 /var/www/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): AppHttpControllersController->method()
    
    Login or Signup to reply.
  2. if you want to see all query builder methods use the query method.
    here is an example if you have a user model and want to find a user by id

    $user = User::query()->find($id);
    

    for me, my code editor is Php storm when I click the find method it forwards me to the Builder class

    IlluminateDatabaseEloquentBuilder
    

    you will get all database query builder methods in this class

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