【问题标题】:laravel 5.7 how to pass request of controller to model and savelaravel 5.7 如何将控制器的请求传递给模型和保存
【发布时间】:2018-12-04 06:15:03
【问题描述】:

我正在尝试将 $request 从控制器中的函数传递到模型中的函数。

这是我的控制器功能:

PostController.php

public function store(Request $request, post $post)
{

    $post->title = $request->title;
    $post->description = $request->description;

    $post->save();

    return redirect(route('post.index'));

}

如何在模型 Post.php 中保存数据?

我希望控制器仅充当发送信息的角色。信息被发送到模型。所有的计算和存储都在模型中进行

谢谢

【问题讨论】:

  • 什么意思how to save data in model?你的代码已经在保存数据了
  • 谢谢。我希望控制器只起到发送信息的作用。信息被发送到模型。所有的计算和存储都在模型中进行

标签: laravel laravel-5 model-view-controller


【解决方案1】:

你可以让它变得更容易。 Laravel 有自己的帮助器“request()”,可以在代码中的任何位置调用。

所以,一般来说,你可以这样做:

PostController.php

    public function store()
    {
        $post_model = new Post;
        // for queries it's better to use transactions to handle errors
        \DB::beginTransaction();
        try {
           $post_model->postStore();
           \DB::commit(); // if there was no errors, your query will be executed
        } catch (\Exception $e) {
            \DB::rollback(); // either it won't execute any statements and rollback your database to previous state
            abort(500);
        }
        // you don't need any if statements anymore. If you're here, it means all data has been saved successfully
        return redirect(route('post.index'));
    }

Post.php

    public function postStore()
    {
        $request = request(); //save helper result to variable, so it can be reused
        $this->title = $request->title;
        $this->description = $request->description;
        $this->save();
    }

我将向您展示更新和创建的完整最佳实践示例:

web.php

    Route::post('store/post/{post?}', 'PostController@post')->name('post.store');

yourform.blade.php - 可用于更新和创建

    <form action='{{ route('post.store', ['post' => $post->id ?? null]))'>
       <!-- some inputs here -->
       <!-- some inputs here -->

    </form>

PostController.php

    public function update(Post $post) {
        // $post - if you sent null, in this variable will be 'new Post' result
        // either laravel will try to find id you provided in your view, like Post::findOrFail(1). Of course, if it can't, it'll abort(404)

        // then you can call your method postStore and it'll update or create for your new post.
        // anyway, I'd recommend you to do next

        \DB::beginTransaction();
        try {
          $post->fill(request()->all())->save();
          \DB::commit();
        } catch (\Exception $e) {
          \DB::rollback();
           abort(500);
        }
      return redirect(route('post.index'));
    }

【讨论】:

  • 感谢您的回答
  • 好吧,也许你可以这样:public function store($id = null) { if ($id !== null) { $post_model = Post::findOrFail($id); // if it won't be available to find your post, it'll throw abort(404) } else { $post_model = new Post(); } } 就是这样。其余代码适用于两者 - 更新和创建
【解决方案2】:

根据描述,不确定您到底想要什么,但假设您想要一个干净的控制器和模型。这是一种方法

模型 - 帖子

class Post {
    $fillable = array(
        'title', 'description'
    );
}

后控制器

class PostController extend Controller {

    // store function normally don't get Casted Objects as `Post`
    function store(\Request $request) {

        $parameters = $request->all(); // get all your request data as an array

        $post = \Post::create($parameters); // create method expect an array of fields mentioned in $fillable and returns a save dinstance
        // OR
        $post = new \Post();
        $post->fill($parameters);
    }
}

希望对你有帮助

【讨论】:

    【解决方案3】:

    您只需通过实例化它来创建新模型:

    $post = new Post;  //Post is your model
    

    然后将内容放入记录中

    $post->title = $request->title;
    $post->description = $request->description;
    

    最后保存到db:

    $post->save();
    

    使用 create 方法保存模型中的所有数据。使用 create 时需要设置 Mass Assignments 并在模型的可填充属性中设置列。

      protected $fillable = [ 'title', 'description' ];
    

    然后用输入调用它

        $post = Post::create([ 'parametername'  => 'parametervalue' ]);
    
    and if request has unwanted entries like token then us except on request before passing.
    
        $post = Post::create([ $request->except(['_token']) ]);
    

    希望这会有所帮助。

    【讨论】:

    • 我也是这样做的。但我想在模型中完成所有这些步骤
    【解决方案4】:

    我想回答我的问题:

    $request 传递给模型 Post.php 中的 my_method :

    PostController.php:

        public function store(Request $request)
        {
            $post_model = new Post;
            $saved = $post_model->postStore($request);
    
            //$saved = response of my_method in model
    
            if($saved){
                return redirect(route('post.index'));
            }
        }
    

    并将数据保存在模型中:

    Post.php

    我们可以将实例或布尔值返回给控制器。

    我将 bool(保存方​​法响应)返回给控制器:

        public function postStore($request)
        {
            $this->title = $request->title;
            $this->description = $request->description;
    
            $saved = $this->save();
    
            //save method response bool
    
            return $saved;
    
        }
    

    这样,所有的计算和存储都在模型中进行(在MVC中保存数据的最佳方式)

    【讨论】:

    • 我认为您不应该从模型返回响应。这是您的控制器的责任。
    • 这感觉不对。您正在向模型提供请求的知识。
    • 模型不应该负责返回响应。这应该仍然是控制器的角色。
    【解决方案5】:
     public function store(Request $request)
    {
        $book = new Song();
        
        $book->title = $request['title'];
        $book->artist = $request['artist'];
        $book->rating = $request['rating'];
        $book->album_id = $request['album_id'];
        
        $result=  $book->save();
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 2018-12-22
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2014-09-16
      相关资源
      最近更新 更多