I'm quite new to laravel and I'm trying to update a record from form's input. However I see that to update the record, first you need to fetch the record from database.
Isn't is possible to something like to update a record (primary key is set):
$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
Post::where('id',3)->update(['title'=>'Updated title']);
You can simply use Query Builder rather than Eloquent, this code directly update your data in the database :) This is a sample:
DB::table('post')
->where('id', 3)
->update(['title' => "Updated Title"]);
You can check the documentation here for more information: http://laravel.com/docs/5.0/queries#updates
The common way is to load the row to update:
$post = Post::find($id);
In your case
$post = Post::find(3);
$post->title = "Updated title";
$post->save();
But in one step (just update) you can do this:
$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);
Use property exists:
$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
Here is the API documentation: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html
You can also use firstOrCreate OR firstOrNew
// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]);
// update record
$post->title = "Updated title";
$post->save();
Hope it will help you :)
Related
Inside my store function i have to search a name of a particular person, thus:
$person = DB::select("select p.* from persons p where concat_ws(', ' ,p.family_name,concat_ws(' ',concat_ws(' ',p.first_name,p.middle_name),p.third_name)) like ?", [$request['person_name']]);
If this person exist i have to update the person and this one works:
Person::where('id', $person[0]->id)->update(['status' => 'Active']);
but not this one:
$person[0]->status = 'Active';
$pArray = json_decode(json_encode($person[0]), true);
$per = new Person($pArray);
$per->update();
Since you have already created a new model instance, you would need to call the save() method.
$per = new Person($pArray);
$per->save();
Or, you can use update() to pass data into an existing model. But first, you need to retrieve the model you want to update.
$per = Person::find($pArray['id']);
$per->update($pArray);
Use your search query instead of mine. I think this will help you.
$result = User::where('id', $userId)->first();
$result->name = 'xyz';
$result->update();
For update data in laravel using model you need to pass where condition in it.
Sample example
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
Hope this helps you!
I know to get the last id I can use insertGetId() but I want to know how can I get the last inserted id through save() method.
order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$invoice = $order->save()['so_id'];
I used this but it returns null value
After $order->save(), $order->so_id should be the last id inserted. Your code should be as below.
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$order->save();
$invoice = $order->so_id;
You can get it by like below :
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$invoice = $order->save();
echo $invoice->so_id;
in this case you no need to store in one variable and then access it, You can get the inserted records by calling the model object itself :
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$order->save();
// echo $order; => will return entire stored last record.
echo $order->so_id;
Make sure so_id is autoincrement.
Try this once it worked for me where $mode->save(); was only returning true.
$mylastid = DB::getPdo()->lastInsertId();
In case of you did overwride the name of primary key in the model as in next case:
protected $primaryKey = 'your_table_id_name';
use:
$id = $your_variable_save->your_table_id_name
if not:
$id = $your_variable_save->id
You can get the last inserted id by the following codes.
Using Laravel Eloquent
$order = new Store_order();
$order->invoice_id = $signed['invoice_id'];
$order->save();
$lastInsertedId = $order->so_id; //now getting Last inserted id
echo $lastInsertedId;
Provided that $order->so_id means last inserted id of the given object where so_id is the primary key of the table.
$ObjTable->nane = $name;
$ObjTable->save();
echo $ObjTable->id;
this will be display last inserted id.
I'm new to Laravel. All I'm trying to do is as follow:
I have some fields in my form like TITLE, DESCRIPTION.
TITLE field is unique in database.
This is what I've done to update my values.
$product = Product::find($id);
$product->title = $request->title;
$product->description = $request->description;
$product->save();
But this will give error (that value already exists) as my TITLE field is unique.
All I want to is update my TITLE only if the TITLE value is changed otherwise update the same value but update other fields. Thanks
Something like this?
$product = Product::find($id);
if ($product->title == $request->title) {
$product->description = $request->description;
} else {
$product->title = $request->title;
}
$product->save();
The code you posted does exactly (if indirectly) what you say you want. Your problem is another: you're assigning a title that is used elsewhere, thereby violating uniqueness.
You must verify that the new title is not already used.
$duplicate = Product::where('title', '=', $request->title)->where('id', '!=', $id)->first();
At this point it is unclear what you want to do:
a) Do you want to use the duplicate record instead of the one indicated by $id?
b) Is this an error?
c) Should the $id record be updated, leaving the title alone?
You can do any of these things; what you can't do is "update my TITLE only if the TITLE value is changed", because the changed value is already in use elsewhere.
I have not seen any of your database structure or form code only the small snippet above you have stated.
you could do something like this...
$checkTitle = Product::where('title', '=', $request->input('title')->first();
You can also do...
$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
}
Sorry for short and sweet, leaving to go to office and thought it might help to post now. Let me know if im on the wrong tracks and ill help where i can.
You can use if statement to check weather column value is same with original?
$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();
You should look at wasChanged() function in Laravel.
I'm trying to use fill() to update a current row in the database. However, it seems to be creating a new row instead of updating each time.
Does anyone know what could be wrong?
Here's my code:
$reserve->where('cookie_id', 'idCode')->first();
$reserve->fill($request->all())->save();
return Redirect::to('checkout');
Try something similar to this
$user = User::where ('cookie_id', 'idCode');
$new_user_data = $request->all();
$user->fill($new_user_data);
$user->save();
You can also try using update()
$affectedRows = User::where('votes', '>', 100)->update($request->all());
Judging by your code you've misunderstood how to fetch an instance out the database. See http://laravel.com/docs/5.1/eloquent#retrieving-single-models
Try the following
$reserve = Reserve::where('cookie_id', $id)->first();
$reserve->fill($request->input())->save();
return redirect()->to('checkout');
I am trying to insert record in Eloquent way.
It is clear in basic cases. For example if I have a Blog with Posts and each post belongs to a User I can do this:
$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);
But how should I do this if my Post belongs to User, Category and Group at the same time?
My first idea was to do it this way:
$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);
$group->posts()->associate($post);
$cat->posts()->associate($post);
But it doesn't work, because group id and category id are null when I save it to the DB and it is not allowed.
What I am doing now is:
$post = new Post;
$post->content = 'Post content';
$post->group = $group->id;
$post->category = $cat->id;
$user->posts()->save($post);
But I don't think it is the right way.
Could someone point me in the right direction?
You're using associate the wrong way around. You have to call it on the belongsTo relation side not the hasMany.
Try this:
$post = new Post;
$post->content = 'Post content';
$post->category()->associate($cat);
$post->group()->associate($group);
$user->posts()->save($post);