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 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色