Search code examples
phpmysqllaravel-5

Laravel DB::raw() not executing query but manual execute works


I am running this query

$query = "update my_cloud set full_dir_url = replace(full_dir_url, '$findWhat', '$replaceWith') where full_dir_url like '$findWhat/%' or where full_dir_url = '$findWhat' ";
DB::raw($query);
echo $query;

Output of echo $query is

update my_cloud set full_dir_url = replace(full_dir_url, '/1st Year/Slide', '/1st Year/Slides') where full_dir_url like '/1st Year/Slide/%' or where full_dir_url = '/1st Year/Slide'

When I run this query in phpmyadmin sql editor, data is updated as expected.

But that DB::raw($query) doesn't update any data. No error log either.


Solution

  • You are attempting to execute a raw SQL update query using Laravel's ``, but it doesn't seem to update any data, even though the query works fine in phpMyAdmin. Here are some insights and solutions to address this issue:

    Problem Analysis:

    1. Using DB::raw() Incorrectly: The DB::raw() method is primarily used for raw expressions in queries, but it does not execute the query itself. To execute a raw query, you need to use DB::statement() or DB::update().
    2. Query Execution: Ensure that the query is being executed properly. Simply calling DB::raw($query) does not run the query; it just prepares it for use in a query builder context.

    Solution: To correctly execute your update query, you can use the following approach:

    $query = "UPDATE my_cloud SET full_dir_url = REPLACE(full_dir_url, '$findWhat', '$replaceWith') 
          WHERE full_dir_url LIKE '$findWhat/%' OR full_dir_url = '$findWhat'";
    
    // Execute the update query
    DB::update($query);
    

    Key Points:

    • DB::raw(): Used for raw expressions within queries, not for executing them.
    • DB::update(): Properly executes the SQL update statement.