Невозможно получить и обновить столбцы БД в Laravel (используя Resource Controller & Collective Forms) - PullRequest
0 голосов
/ 06 ноября 2019

Вот небольшой контекст того, что я пытаюсь сделать: я пытаюсь создать систему профилей, где пользователь регистрируется и перенаправляется на страницу отображения, где вся информация пользователя, такая как его имя, адрес электронной почты и т. Д. предназначен для отображения. Поскольку форма регистрации имеет только 2 поля (имя / адрес электронной почты) - пользователь должен обновить свою другую информацию, например, свой пол / идентификатор Facebook / идентификатор Twitter и т. Д. И т. Д. Поэтому у меня есть кнопка «Редактировать», которая переводит пользователя в форму. Теперь в этой форме я хочу, чтобы его уже существующее имя / адрес электронной почты отображалось, в то время как другие поля, такие как Gender / FB / Twitter / Description, пусты - после того, как он заполнит эти поля и нажмет Update, я хочу, чтобы он вернулся к DisplayСтраница, а затем будет показана вся эта обновленная / новая информация, например, Пол / Имя / Электронная почта / Twitter / Описание. Ниже приведен мой код:

ProfileController.php (контроллер ресурсов):

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\CustomUser;


class ProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $customusers = CustomUser::get()->first();
        return view ('display',compact('customusers'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(CustomUser $customuser) 
    {
        return view ('edit',compact('customuser'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, CustomUser $customuser)
    {
        $customuser->update($request->all());
        return redirect()->route('display.index')->with('creation','Profile has been updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

CustomUser.php (модель):

   <?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class CustomUser extends Authenticatable
{
    use Notifiable;

    protected $table = 'customusers';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','username','email','gender','password','message','twitter','facebook',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Display.blade.php (главная страница):

@extends('layouts.app')

@section('content')

<div style="margin-top: 5.2%;" class="container">
    <div class="row">
        <div class="col-lg-12">
            @if (Session::has('creation'))
            <div class="alert alert-info">
                {{ Session::get('creation') }}
            </div> 
            @endif
             {{ link_to_route('display.edit','Edit',[$customusers->id],['class'=>'btn btn-success']) }}

             {{$customusers->name}}
             {{$customusers->email}}
             {{$customusers->message}}
             {{$customusers->facebook}}
             {{$customusers->twitter}}
        </div>
    </div>
</div>

@endsection

И, наконец, это мой Edit.blade.php :

@extends('layouts.app')

@section('content')
<body style="height: 105.6vh;">
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header" style="color: #fff; background-color: #113;font-family: 'Nunito',sans-serif; text-transform: uppercase;letter-spacing: 2px;
                font-weight: bold;">
                    Edit Profile
            </div>
                <div class="card-body">
                        {!! Form::model($customuser,array('route'=>['display.update',$customuser->id],'method'=>'PUT')) !!}
                    <div class="form-group">
                        {!! Form::text('name',null,['class'=>'form-control','placeholder'=>'Username']) !!}
                    </div>
                    <div class="form-group">
                            {!! Form::email('email',null,['class'=>'form-control','placeholder'=>'Email']) !!}
                    </div>
                    <div class="form-group form-row">
                            <div class="col-5">
                                    {!! Form::select('gender', ['Male' => 'Male', 'Female' => 'Female'], null, ['class'=>'form-control','placeholder'=>'Choose Gender']); !!}
                            </div>
                            <div class="col">
                                    {!! Form::text('facebook',null,['class'=>'form-control','placeholder'=>'Facebook ID']) !!}
                            </div>
                            <div class="col">
                                    {!! Form::text('twitter',null,['class'=>'form-control','placeholder'=>'Twitter Handle']) !!}
                            </div>
                    </div>
                    <div class="form-group">
                            {!! Form::textarea('message',null,['class'=>'form-control','placeholder'=>'Talk about yourself']) !!}
                    </div>
                    <div class="form-group">
                            {!! Form::button('Edit',['type'=>'submit','class'=>'btn btn-danger col-lg-12']) !!}
                    </div>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
</div>
</body>
@endsection

Теперь, когда я нажимаю Edit и перехожу к Edit.blade.php - все поля пусты, когда два из них (имя / адрес электронной почты) должны иметь предварительно заполненные пробелы того, что пользовательучетные данные есть, но это не так - они не заполнены. И когда я заполняю все поля и нажимаю «Обновить», он выдает: « Метод PUT не поддерживается для этого маршрута . Что я здесь не так делаю? Я болтал через Интернет более 2 часови я не могу найти то, что я делаю здесь неправильно. Дайте мне знать, что вам нужна дополнительная информация, чтобы решить мою проблему ..

1 Ответ

0 голосов
/ 06 ноября 2019

Вы передаете идентификатор клиента из вашего display.blade.php для обновления функции в ProfileController, и вы получаете объект Customer, которого не должно быть, и вы сделали то же самое в функции редактирования.

Однако ваше редактирование иФункции обновления должны быть такими:

    /**
 * Show the form for editing the specified resource.
 *
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function edit(CustomUser $id)
{
    $customuser = CustomUser::whereId($id)->first();
    return view ('profile.edit',compact('customuser'));
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $customuser = CustomUser::whereId($id)->first();
    $customuser->update($request->all());
    return redirect()->route('display.index')->with('creation','Profile has been updated successfully!');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...