Reputation: 1051
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();
}
}
Upvotes: 3
Views: 15717
Reputation: 1040
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".
Upvotes: 0
Reputation: 1074
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();
}
}
Upvotes: 5