1

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.

I configured a fresh laravel application and performed

php artisan make:auth

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

These are all routes in 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:

<?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:

{!! 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:fresh and 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.

11
  • is the page reloading? see if the $error variable is populated once you post In blade add <?php {{ $error->all(); }} ?> and see if it shows any error after post. Commented Jun 27, 2018 at 11:50
  • I followed your suggestion and I get this error: Undefined variable: error (View: /<...>/resources/views/user.blade.php) Commented Jun 27, 2018 at 11:51
  • I changed it to $errors->all() and the page does not show any error after posting the form. Commented Jun 27, 2018 at 11:54
  • can you post the contents of your log file, it should be in the storage/logs folder. Also see if your call is even reaching your controller by adding a dd() at the beginning of your controller. Commented Jun 27, 2018 at 11:56
  • I added dd() to the controller but nothing changes..? That would imply the flow never reaches the controller? Commented Jun 27, 2018 at 12:08

2 Answers 2

3

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

Mistakes found:

  • form submit inside table
  • duplicate route names
  • no auth middleware to user routes
  • no data validation
  • using wrong use statements

user.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

UserController.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

// 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 tip i'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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Priyash for taking the time and explaining the mistakes I made!
2

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.

2 Comments

This doesn't solve the problem unfortunately, it still doesn't seem to respond to clicking the submit button. But it turns out the controller isn't even reached...
I have to update logged in user's name and phone number in session after updating profile information by form. How to update Auth session with latest user information? Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.