Search code examples
phplaravelcommand-line-interfacelaravel-artisan

Laravel Controller for CRUD without querying Database inside Controller's methods


It's possible to pass the right model object inside CRUD methods without query the database inside the method itself?

If you look at the DOC, You can see that controller's methods accepts the ID from the URL as a param.

https://laravel.com/docs/5.7/controllers

But, if You generate a Controller using artisan CLI, so the methods accept not the IDs as param but Request objects and or Model object, for example Post $post. So, how can I be sure that Laravel correctly query the DB for me and pass the Model as a param? If I try this, the view is correctly rendered but the data are not passed in response.

Example method from the DOCS

 /**
 * Show the profile for the given user.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    return view('user.profile', ['user' => User::findOrFail($id)]);
}

Example method from the CLI generated Controller

    /**
 * Display the specified resource.
 *
 * @param  \App\Order  $order
 * @return \Illuminate\Http\Response
 */
public function show(Order $order)
{
    //
}

Notice the difference in parameters.

Runned Artisan Command

php artisan make:model Order -mcr Ref: https://quickadminpanel.com/blog/list-of-16-artisan-make-commands-with-parameters/

Solution

You have t look at https://laravel.com/docs/master/routing#route-model-binding, Explicit Binding and define the model in the Router in the AppServiceProvider's boot as follows:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Route::model('ordini', \App\Order::class);
}

Solution

  • I think you are looking route model binding https://laravel.com/docs/master/routing#route-model-binding

    If you have a route like user/{user} you can resolve user model with type hinting

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    class UserController extends Controller
    {
        /**
         * Store a new user.
         *
         * @param  \App\User  $user
         * @return Response
         */
        public function store(\App\User $user)
        {
            $name = $user->name;
    
            //
        }
    }