Laravel save object to database

Updated at 23-Sep-2021, By samar

Laravel save object to database

In this session, we’ll try our hand at solving the "Laravel save object to database" puzzle by using the computer language.

You can save object to the database by instantiating the model class and using save() method on it.
  • Laravel instantiate user model and call save() method to create record in laravel 8

    //Code snippet to create user record by instantiating user model with save method
    $user = new User;
    $user->name = 'w3codegenerator.com';
    $user->email = '[email protected]';
    $user->email_verified_at = now();
    $user->password = bcrypt('password');
    $save = $user->save();
    echo $save;
    
    //Import User model
    use App\Models\User;
    

    Code for demo with output

    routes\web.php

    use App\Models\User;
    
    Route::get('/save-user', function(){
        $user = new User;
        $user->name = 'w3codegenerator.com';
        $user->email = '[email protected]';
        $user->email_verified_at = now();
        $user->password = bcrypt('password');
        $save = $user->save();
        echo $save;
    });

    Output :

    1

    http://localhost:8000/save-user

Back to code snippet queries related laravel