Different Ways to store data in laravel 10

By Ved Prakash N | Dec 10, 2023 | Laravel
Share : Whatsapp

https://www.fundaofwebit.com/post/different-ways-to-store-data-in-laravel-10

How many ways exist to Store data into database in laravel?


In this post, we will learn how to store data into database in Different Ways in Laravel 10. So let's begin.


Model ( $model->property )

public function store(Request $request)
{
    $product = new Product();
    $product->name = $request->name;
    $product->price = $request->price;
    $product->description = $request->description;
    $product->is_active = $request->is_active;
    $product->save();
}


Model Create

In this Model Create: we use the Eloquent Model to store the data and you can also give selected column name/attribute to insert data.

public function store(Request $request)
{
    Product::create([
        'name' => $request->name,
        'price' => $request->price,
        'description'  => $request->description,
        'is_active'  => $request->is_active
    ]);
}


Model Create with $request->all() method

Note: If you save as shown below, make sure to add all the fields in your $fillable property in your Model ( Eg. Product.php Model )

public function store(Request $request)
{
    Product::create($request->all());
}

Example for fillable property in your model: 

class Product extends Model {
    protected $fillable = ['name', 'price', 'description'];
}


Model Create with $request->only() method

Note: Add all the field names in the Model (app/Models/Product.php file) 

The below code to save data is for specific fields only, where you can choose "FORM Input fields" using the $request->only() method and save data as shown below: 

public function store(Request $request)
{
    Product::create($request->only(['name','price','description']));
}


New Model

We can create and inject attributes to constructor of the model and save data using save() method with the object of the model.

public function store(Request $request)
{
    $product = new Product([
        'name' => $request->name,
        'price' => $request->price,
        'description'  => $request->description,
        'is_active'  => $request->is_active
    ]);
    $product->save();
}


Model using Fill() method and save()

We use the fill() method to build/add all the fields with data on Eloquent as shown below:

public function store(Request $request)
{
    $product = new Product();
    $product->fill([
        'name' => $request->name,
        'price' => $request->price,
        'description'  => $request->description,
        'is_active'  => $request->is_active
    ]);
    $product->save();
}


Query Builder

We can use Query Builder for saving data in database like this:

public function store(Request $request)
{
    DB::table('products')->insert([
        'name' => $request->name,
        'price' => $request->price,
        'description' => $request->description,
        'is_active' => $request->is_active
    ]);
}


Save data using insert() with Model:

Here, this insert() method uses the Query builder method and it do not creates or save timestamp fields in database by default instead it keeps it NULL. but in create() method it save with timestamp.

public function store(Request $request)
{
    $product = [
        'name' => $request->name,
        'price' => $request->price,
        'description' => $request->description,
        'is_active' => $request->is_active
    ];

    Product::insert($product);
}


Model with firstOrCreate() method to save data.

The firstOrCreate() method in Laravel's Eloquent ORM is used to retrieve the first record matching the specified attributes. If no matching record is found, it creates a new record in the database with the given attributes. Here's an example of how firstOrCreate() can be used in Laravel:

public function store(Request $request)
{
$product = Product::firstOrCreate(
        [ 'name' => $request->name ],
        [
            'price' => $request->price,
            'description' => $request->description
        ]
    );
}


Model with firstOrNew() method to save data.

The firstOrNew() method in Laravel's Eloquent ORM is used to retrieve the first record matching the specified attributes. If no matching record is found, it will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise, it will give you the matched item. Here's an example of how firstOrNew() can be used in Laravel:

$product = Product::firstOrNew(
    [ 'name' => $request->name ],
    [
        'name' => $request->name,
        'price' => $request->price,
        'description' => $request->description
    ]
);
$product->save();


Model with updateOrCreate() method to save data.

The updateOrCreate() method in Laravel's Eloquent ORM is used to find a record that matches the given attributes. If found, it updates the record with the specified values; if not found, it creates a new record with the provided attributes. Here's an example demonstrating the usage of updateOrCreate():

public function storeOrUpdate(Request $request)
{
    $product = Product::updateOrCreate(
        [
            'name' => $request->name,
        ],
        [
            'name' => $request->name,
            'price' => $request->price,
            'description' => $request->description
        ]
    );
}


Upsert() in Laravel: Updating Existing Records and Inserting New Data Dynamically.

In Laravel, the upsert() method allows you to perform an "upsert" operation, which means updating existing records or inserting new records based on a given set of conditions. It's particularly useful when dealing with bulk operations or when you want to update existing records or insert new ones based on certain criteria.

// Products data to be updated or inserted
$productsData = [
    ['id' => 1, 'name' => 'Product A', 'price' => 20.00],
    ['id' => 2, 'name' => 'Product B', 'price' => 25.00],
    ['name' => 'Product C', 'price' => 30.00],
    ['name' => 'Product D', 'price' => 40.00],
    ['name' => 'Product E', 'price' => 46.00],
    // ... more data
];

Product::upsert($productsData, ['id'], ['name', 'price']);


Thanks for reading...