dongzhuifeng1843 2018-10-11 20:54
浏览 148
已采纳

用于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 2018-10-11 21:10
    关注

    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;
    
            //
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效