在默认 Laravel 应用程序中更新用户数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51062030/
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 17:50:47  来源:igfitidea点击:

Updating user data in default Laravel application

phplaravellaravel-5

提问by Esther

I just started using Laravel and I can't get my head around this problem... I hope more experienced people here can spot the error I'm making.

我刚开始使用 Laravel,我无法解决这个问题......我希望这里有更多有经验的人可以发现我犯的错误。

I configured a fresh laravel application and performed

我配置了一个新的 Laravel 应用程序并执行

php artisan make:auth

Following the instructions from https://laravel.com/docs/5.6/authentication#authentication-quickstart.

按照https://laravel.com/docs/5.6/authentication#authentication-quickstart 中的说明进行操作 。

These are all routes in routes/web.php:

这些都是 中的路线routes/web.php

Route::get('/', 'HomeController@show');
Route::get('/user', ['as'=>"user", 'uses'=>'UserController@show']);
Route::post('/user/update', ['as' => 'user.update', 'uses' => 'UserController@update']);

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

This is my UserController.php:

这是我的UserController.php

<?php

namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
  public function show() {

    return view('user')->withUser(Auth::user());
  }
  public function update(Request $request)
    {
        $user = Auth::user();
        $user->name=$request->input('name');
        $user->email=$request->input('email');

        $user->save();
        return Redirect::route('user');
    }
}

And this is the form in my user.blade.php:

这是我的表格user.blade.php

{!! Form::model($user, ['route' => ['user.update'], 'method' => 'POST']) !!}
<tr><th colspan=2>My data</th></tr>
  <tr>
      <td>Name</td>
      <td>{!! Form::text('name', null, ['class' => 'form-control']) !!}</td>
  </tr>
  <tr>
      <td>E-mail address</td>
      <td>{!! Form::text('email', null, ['class' => 'form-control']) !!}</td>
  </tr>
  <tr><td colspan=2>{!! Form::submit('Submit', ['class' => 'btn btn-primary']) !!}</td></tr>
{!! Form::close() !!}

Nothing seems to happen when I click the submit button in the form... Data is not changed in the database.

当我单击表单中的提交按钮时,似乎什么也没发生……数据库中的数据没有改变。

Updates:

更新

  • The controller doesn't get triggered. I added dd()to the update()function and this doesn't yield anything.

  • I tried composer du, clearing the browser cache and tried another browser. I refreshed the migration using php artisan migrate:freshand registered again. Same problem still. debug is set to true, I get other errors if I change things. I added the project to a github repo: github.com/EsthervdS/LaravelTest

  • I reinstalled a whole new project and the problem occurs again.

  • 控制器不会被触发。我添加dd()update()函数中,这不会产生任何结果。

  • 我试过composer du,清除浏览器缓存并尝试另一个浏览器。我刷新了迁移使用php artisan migrate:fresh并再次注册。还是一样的问题。debug 设置为 true,如果我更改内容,我会收到其他错误。我将项目添加到 github仓库github.com/EsthervdS/LaravelTest

  • 我重新安装了一个全新的项目,问题再次出现。

回答by Priyash

after looking at your user.blade.phpfound that you are using form inside table and that's what preventing form submission. also i found more mistakes too. so i improved it.

查看您的user.blade.php 后发现您正在使用表格内的表格,这就是阻止表格提交的原因。我也发现了更多的错误。所以我改进了它。

Mistakes found:

发现错误:

  • form submit inside table
  • duplicate route names
  • no auth middleware to user routes
  • no data validation
  • using wrong use statements
  • 表格内提交表格
  • 重复的路线名称
  • 没有用户路由的身份验证中间件
  • 没有数据验证
  • 使用错误的 use 语句

user.blade.php

用户.blade.php

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Profile</div>
                    <div class="card-body">

                        @if($errors)
                            @foreach($errors->all() as $error)
                                <div class="alert alert-danger" role="alert">
                                    {{ $error }}
                                </div>
                            @endforeach
                        @endif

                        {!! Form::model($user, ['route' => ['user.update'], 'method' => 'POST']) !!}
                            <div class="form-group row">
                                <label for="name" class="col-sm-2 col-form-label">Name</label>
                                <div class="col-sm-10">
                                    {!! Form::text('name', null, ['class' => 'form-control', 'id' => 'name']) !!}
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="email" class="col-sm-2 col-form-label">Email</label>
                                <div class="col-sm-10">
                                    {!! Form::text('email', null, ['class' => 'form-control', 'id' => 'email']) !!}
                                </div>
                            </div>

                            <div class="form-group">
                                {!! Form::submit('Submit', ['class' => 'btn btn-primary']) !!}
                            </div>

                        {!! Form::close() !!}
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

i'm not big fan of laravel collective

我不是 Laravel 集体的忠实粉丝

UserController.php

用户控制器.php

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show()
    {
        return view('user', ['user' => Auth::user()]);
    }

    /**
     * @param Request $request
     * @return
     */
    public function update(Request $request)
    {
        // Get current user
        $userId = Auth::id();
        $user = User::findOrFail($userId);

        // Validate the data submitted by user
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'email' => 'required|email|max:225|'. Rule::unique('users')->ignore($user->id),
        ]);

        // if fails redirects back with errors
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Fill user model
        $user->fill([
            'name' => $request->name,
            'email' => $request->email
        ]);

        // Save user to database
        $user->save();

        // Redirect to route
        return redirect()->route('user');
    }
}

web.php

网页.php

<?php

// Auth routes
Auth::routes();

// User account routes
Route::get('user', 'UserController@show')->name('user');
Route::post('user/update', 'UserController@update')->name('user.update');

// other routes
Route::get('/', function () {
    return view('welcome');
})->name('welcome');

Route::get('/home', 'HomeController@index')->name('home');

extra tipi'll recommend to use laravel authorization policies. and if you also want to make welcome route only available to authenticate users then simply add auth middleware to welcome route - laravel docs

额外的提示,我会建议使用laravel 授权策略。如果您还想让欢迎路由仅可用于对用户进行身份验证,那么只需将 auth 中间件添加到欢迎路由中 - laravel docs

回答by Mayank Pandeyz

Change the following line:

更改以下行:

$user = Auth::user();

to

$userDetails = Auth::user();  // To get the logged-in user details
$user = User::find($userDetails ->id);  // Find the user using model and hold its reference
$user->name=$request->input('name');
$user->email=$request->input('email');

$user->save();  // Update the data

Auth::user();contains the logged-in user data in it i.e. the data we mostly put in the session, but to update the user data you have to use the model instance or query builder.

Auth::user();包含登录的用户数据,即我们主要放在会话中的数据,但要更新用户数据,您必须使用模型实例或查询构建器。

回答by Priyash

i cloned your code it's working at my side. try composer du or clear browser cache. or give more information.

我克隆了你的代码,它在我身边工作。尝试 composer du 或清除浏览器缓存。或提供更多信息。