3

I'm new to learning Laravel 5. I'm following a tutorial and I have the following code in my controller. What I want is to update the username with ID=10 in my login database. I follow the tutorial and also the Laravel documentation but what happens is it inserts another record instead of updating the existing. What is wrong with my code?

Routes.php:

Route::get('/users', "PagesController@login");

login.php (model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class login extends Model
{
    public $timestamps = false;
    protected $table = 'login';

    protected $fillable = [
        'username',
        'password'
    ];    
}

PagesController.php

<?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\login; //added
    use App\Http\Requests;
    use App\Http\Controllers\Controller;

    class PagesController extends Controller
    {
       public function login()
        {
          $login = new login;
          $login::find(10);
          $login->username ='updated_username';
          $login->save();
        }
    }
4
  • What's the result of var_dump($login); after $login::find(10);? Commented Sep 9, 2015 at 8:39
  • the result shows the data in ID number 10 Commented Sep 9, 2015 at 8:40
  • Try same thing in Tinker, its good for debugging just run php artisan tinker and then type the code and see the result there itself Commented Sep 9, 2015 at 8:55
  • 1
    it works now. i just configure my database the ID fields was changes to small letter id and it works. perfectly thank you all! Commented Sep 9, 2015 at 9:13

2 Answers 2

5

By creating new login object means you are creating new record. Simply use login::find() to load your existing record.

class PagesController extends Controller
{
    public function login()
    {
      $login = login::find(10);
      $login->username ='updated_username';
      $login->save();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your comment. i tried but nothing happens. but the return $login = login::find(10); shows result. its just didnt update.
0
class PagesController extends Controller
    {
       public function login()
        {
          $login = (new App\Login)->find(10);
          $login->username ='updated_username';
          $login->save();
        }
    }

Remember that your classname should start with an uppercase letter "use App\Login" and not "use App\login". Optionally you can reference the class directly with "new App\Login".

Comments

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.