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

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制