Alexander Kim
Alexander Kim

Reputation: 18401

When validation fails it throws an error: Trying to get property of non object

let me explain a bit about my problem. I have a form, where you can edit a user data and i have a validation as a service, but when the validation fails it throws me an error: "Trying to get property of non object" in userEdit.blade.php

Here's my routes.php:

Route::get('users/{id}/edit', array('before' => 'auth|admin', 'uses' => 'UserController@editUser'));
Route::post('users/{id}/edit', array('before' => 'auth|admin', 'uses' => 'UserController@editUserPost'));

UserController.php:

public function editUser($id) {
    $user = $this->user->find($id);
    return View::make('auth.editUser')->with('user', $user);
}

public function editUserPost() {
    // Validation
    $validator = new UserEditFormValidator(Input::all());

    if ($validator->fails()) { 
        return Redirect::action('UserController@editUser')->withErrors($validator->errors()); // THIS BUGGED
    }

    $input = array(
        'id' => Input::get('id'),
        'name' => Input::get('name'),
        'active' => (Input::has('active')) ? true : false,
        'password' => Input::get('password')
    );

    $this->user->update($input);
        return Redirect::action('UserController@userList')->with('success', 'Your profile has been updated');
    }

And editUser.blade.php:

{{ Form::open(array('url' => (Request::is('users/*')) ? 'users/' . $user->id . '/edit' : 'my/edit')) }}
        {{ Form::hidden('id', $user->id) }}

            <div class="form-group">
                {{ Form::label('name', 'Your name') }}
                {{ Form::text('name', $user->name, array('class' => 'form-control')) }}
            </div>

            <div class="form-group">
                {{ Form::label('password', 'Your password') }}
                {{ Form::password('password', array('class' => 'form-control')) }}
            </div>      
            <div class="form-group">
                {{ Form::label('password_confirmation', 'Your password one more time') }}
                {{ Form::password('password_confirmation', array('class' => 'form-control')) }}
            </div>

            {{ Form::submit('Save', array('class' => 'btn btn-default')) }}

{{ Form::close() }}

Everything looks fine for me, but i can't understand why i am getting "Trying to get property of non-object" in userEdit.blade.php because of $user->id

Upvotes: 0

Views: 856

Answers (1)

BrainPicker
BrainPicker

Reputation: 437

It doesn't look like you're sending the user_id back to the page when it encounters errors.

The redirect should look like this return Redirect::action('UserController@editUser', array('id' => 1))->withErrors($validator->errors());

The route defined needs the user id to initialize the user to show in the View.

Upvotes: 1

Related Questions