I’m making a CRUD App, Everything is working fine except Updation. I want to update data in my MySQL table.
Controller code:
function update(Request $req){
$ID = $req->get('update_id');
$Name = $req->get('update_name');
$Price = $req->get('update_price');
$new_prod = product::find($ID);
$new_prod->PName = $Name;
$new_prod->PPrice = $Price;
echo $new_prod;
$new_prod->save();
return redirect('/');
}
Update Blade code:
<form action="updatedata" method="get">
@csrf
<div class="mb-2">
<label for="">Product ID</label>
<input type="text" class="form-control" value="{{$pid}}" name="update_id" disabled>
</div>
<div class="mb-2">
<label for="">Product Name</label>
<input type="text" class="form-control" value="{{$pname}}" name="update_name">
</div>
<div class="mb-2">
<label for="">Product Price</label>
<input type="text" class="form-control" value="{{$price}}" name="update_price">
</div>
<br>
<button type="submit" class="btn btn-outline-warning rounded-pill">Update</button>
</form>
SQL QUERY:
select * from `products` where `products`.`Id` is null limit 1
5
Answers
Try this:
Check if the ID is null or empty and update if it is.
Your
$new_prod
variable isnull
, meaning the result ofproduct::find($ID);
is null. The reason for this likely being Laravel could not find a record in your database with the givenId
.If you trace things backwards to where you set
$ID
, you’re getting it from your$request
object (note it is good practice to never assume user input is always invalid and therefore validate incoming data) which suggests the value you’re getting for$ID
from your$request
is invalid.If you take it back another step and look at your
<form>
and theupdate_id
input
, you’ve set theinput
todisabled
. Fields flagged with thedisabled
attribute are not sent in the request when the form is submitted. Therefore, replacedisabled
withreadonly
. That should allow theupdate_id
to be submitted with the<form>
.It would also be a good idea to perform some checks after you’ve performed your
find
query for aproduct
to ensure it actually has a value before you go using it.This code is not secure!
You must reassure yourself that update_id is present, and check that for the value $ID a record exists in the database. Laravel validation can help you
Nothing reassures that $ID exists, the $new_prod either. But you can try this:
You have to be sure that $new_prod exists and is not NULL before proceeding with the update in the database.
This code should help you
you can validation id first , like this: