Laravel 5.2 - 使用控制器 store() 插入新的数据库记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36249603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:28:44  来源:igfitidea点击:

Laravel 5.2 - Use controller store() to insert a new DB record

laravel

提问by TheUnreal

Let's say I have a controller named HeroControllerand I want to create a new hero object and insert it to my database as a new hero.

假设我有一个名为的控制器HeroController,我想创建一个新的英雄对象并将其作为新英雄插入到我的数据库中。

My controller contains the following method:

我的控制器包含以下方法:

public function store(Request $request)
    {
        $hero = new Hero;
        $hero->name = $request->name;
        $hero->description = $request->description;
        $hero->avatar = "None";
        $hero->save();

        return redirect('/');
    }

I want to use this method when the user is posting the "Add a new hero" form. Actually what happens is that i'm creating a new hero via my routes.phpfile:

当用户发布“添加新英雄”表单时,我想使用此方法。实际上,我正在通过我的routes.php文件创建一个新英雄:

Route::post('/heroes/create', function (Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return redirect('/')
            ->withInput()
            ->withErrors($validator);
    }

    $hero = new Hero;
    $heroname = $request->name;
    $hero->save();

    return redirect('/');
});

Why my hero is created in ths routes.phpand how I can change it to work with my HeroController? it feels more right this way..

为什么我的英雄是在 ths 中创建的,routes.php以及如何更改它以与我的 HeroController 一起使用?这样感觉更合适..

回答by Alexey Mezenin

You really need to learn about RESTful controllersand resource routes. This is exactly what you want.

你真的需要了解RESTful controllers和资源路线。这正是您想要的。

https://laravel.com/docs/5.1/controllers#restful-resource-controllers

https://laravel.com/docs/5.1/controllers#restful-resource-controllers

You should use createaction to return a view with a hero creation form and storeaction to create and save data in DB, based on user input.

您应该使用createaction 返回一个带有英雄创建表单的视图,并store根据用户输入使用action在数据库中创建和保存数据。

So all the logic will be inside a controller and the only route you will have is:

因此,所有逻辑都将在控制器内,您将拥有的唯一路线是:

Route::resource('heroes', 'HeroController');

回答by oseintow

Change Route to Route::post("heroes/create","HeroController@store");

将路由更改为 Route::post("heroes/create","HeroController@store");

And copy the content of your current route to the store function in your HeroController

并将你当前路由的内容复制到你的 HeroController 中的 store 函数中

回答by Chris

Pretty straight forward, if I understand correctly:

非常直接,如果我理解正确的话:

Route::post('/heroes/create', 'HeroController@store');

It would be best to go through the controller docs

最好通过控制器文档