Laravel update column value by appending text

Created at 21-Dec-2022 , By samar

You can update column value by appending text to the existing value in laravel using concat() method. You have to pass the text with column name to the concat method in the update query builder to update the data for a specific column in the table.

  • Append text at the start of the column value

    To update the records by appending text to the start of a column in Laravel, you have to pass the string value as a first argument and column name as a second argument to the concat method DB::raw("CONCAT('Some random text ', body)") in update() method of the Eloquent ORM.

    $update = DB::table('posts')
                    ->where("id", $id)
                    ->update([
                        'body' => DB::raw("CONCAT('Some random text ', `body`)")
                    ]);
    

    In the above code example, we have used the DB::raw() method with concat() to append the text in Laravel. Here we use the where condition to get the record which we want to update and execute an update query on it by appending some random text to it.

  • Append text at the end of the column value

    You can update the column value by appending text at the end of the column value by passing the column name as first argument and text as second argument to the concat method.

    $post = Post::find($id);
    
    $post->body = DB::raw('concat(body, ' . $value . ')');
    
    $post->save();
    
    

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.