dsk710351 2018-11-12 20:28
浏览 192

Laravel:如何创建一个POST请求控制器并将用户保存在数据库中?

I have a problem with inserting Data into Database.

All i have done till now is :

Create a Model with Controller and Migration.

So, now my files looks this way :

UserController - Controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return response()->json([
            'name' => 'Abigail',
            'state' => 'CA'
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $user = new User;
        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;
        $user->role = 'user';
        $user->slug = $userSlug;
        $user->save();
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */

web.php - Routing:

<?php

Route::get('/', function () {
    return view('welcome');
});

Route::resource('users', 'UserController');
Route::post('users', 'UserController@create');
  • 写回答

2条回答 默认 最新

  • doudi8525 2018-11-12 20:37
    关注

    Couple of things that I've noticed are:

    You use $request but it is never initialized not even passed in the method as a parameter, so you should change your method signature to this:

    public function create(Request $request)
    

    Next thing is you use $userSlug which again is not initialized.

    And in your routes you use a resource and then you redeclare the create as separate. So in REST, create is used to represent the creation form, so this is a get method type, and then the store action method is the one to which you pass the form to be saved in the Database.

    Please share your view and the error that you get so we have better picture on what is going on.

    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB yalmip 可转移负荷的简单建模出错,如何解决?
  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?