Laravel how to update value in mysql only when changing value

I am new to Laravel. All I'm trying to do is the following:

I have some fields in my form, such as TITLE, DESCRIPTION .

Field

TITLE is unique in the database.

This is what I did to update my values.

$product              = Product::find($id); 
$product->title       = $request->title;
$product->description = $request->description;
$product->save();

But this will give an error (this value already exists), since my TITLE field is unique.

All I want is updating my TITLE only if the TITLE value is changed, otherwise update the same value, but update the other fields. thank

+4
5

- ?

$product = Product::find($id);

if ($product->title == $request->title) {
    $product->description = $request->description;
} else {
    $product->title = $request->title;
}

$product->save();
+4

, , ( ) , , . : , , .

, .

$duplicate = Product::where('title', '=', $request->title)->where('id', '!=', $id)->first();

, :

a) $id?

b) ?

c) $id, ?

; , , - " TITLE, TITLE ", .

+1

, .

- ...

$checkTitle = Product::where('title', '=', $request->input('title')->first();

...

   $record = Product::find($id)

    if($request->input('title') === $record->title){
     // Record with the $id has the same title as you are posting in the request.
    }else{
         // Title for $id lets say id number 3, Is not the same as the form request you are sending so now Perform insert
      }


   if(count($checkTitle) >= 1){
      // Means the title exists and do what ever you want...
     //  Perform update
    }else{
      // Perform insert
     }

, , . , im , .

0

if, , ?

$currentProduct         = Product::find($id);
//Check and update if title not same
if($currentProduct->title == $request->title){
    $currentProduct->description   = $request->description;   
}
//Update title and description...
else {
    $currentProduct->title         = $request->title;
    $currentProduct->description   = $request->description;
} 

$currentProduct->save();
0

isChanged() Laravel.

0
source

Source: https://habr.com/ru/post/1663300/


All Articles