21.11.2014 Views

Laravel Starter - PHP User Group (Myanmar)

Laravel Starter - PHP User Group (Myanmar)

Laravel Starter - PHP User Group (Myanmar)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Laravel</strong> <strong>Starter</strong><br />

}<br />

}<br />

return View::make('users.update')->with('user', $user);<br />

Here we have our new get_update() method. This method accepts a user ID as an argument.<br />

Much like we did with the get_delete() method, we need to load the user record from the<br />

database to verify that it exists. Then, we'll pass that user to the update form.<br />

public function post_update($user_id)<br />

{<br />

$user = <strong>User</strong>::find($user_id);<br />

if(is_null($user))<br />

{<br />

return Redirect::to('users');<br />

}<br />

$user->real_name = Input::get('real_name');<br />

$user->email = Input::get('email');<br />

if(Input::has('password'))<br />

{<br />

$user->password = Input::get('password');<br />

}<br />

$user->save();<br />

}<br />

return Redirect::to('users');<br />

When a user submits our update form, they'll be routed to post_update().<br />

You may have noticed a common theme with methods that receive a user ID as an argument.<br />

Whenever we are going to interact with a user model we need to know for sure that the<br />

database record exists and that the model is populated. We must always first load it and<br />

validate that it is not null.<br />

Afterwards, we assign new values to the real_name and email attributes. We don't want to<br />

just change the user's password every time we submit a change. So, we'll first verify that the<br />

password field wasn't left blank. <strong>Laravel</strong>'s Input class' has() method will return false, if<br />

an attribute either wasn't sent in the form post or if it's blank. If it's not blank, we can go ahead<br />

and update the attribute in the model.<br />

We then save the changes to the user and redirect back to the users index page.<br />

25

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!