dongzhuifeng1843
dongzhuifeng1843
2018-10-11 20:54

用于CRUD的Laravel Controller,无需在Controller的方法中查询数据库

已采纳

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);
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doushi1929 doushi1929 3年前

    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;
    
            //
        }
    }
    
    点赞 评论 复制链接分享

相关推荐