How to get the inserted id of create() method in laravel? - php

I'm trying to get the last inserted id made from create() eloquent in laravel.
Here's my laravel code
$product = ProductModel::create([
'prodCode' => $prodCode,
'prodTitle' => $dataProducts->prodTitle,
'prodDesc' => $dataProducts->prodDesc,
'attachment' => "images/products/".$attachment,
'prodSize' => $dataProducts->prodSize,
'prodCategory' => $dataProducts->prodCategory,
'prodPrice' => $dataProducts->prodPrice,
'created_by' => auth()->user()->id
]);
I will use this last inserted id for another query with the same function.
Is it possible to do it with this way of saving data, or do I need to convert this code to another efficient way?

The create function of a model returns new record.
Very easily:
$product = ProductModel::create([...]);
// last inserted id
$lastInsertedId = $product->$idField;

Well in this case your are doing right !
use print_r($product->id) to see the last inserted id if the field name is id

Related

Laravel Eloquent - bulk update with whereIn array

I'm working on a project where I need to update many rows at once per coin Id.
in order to update all coins values, Im getting them all from the API, so for example I have back:
$coinsList= [[id="bitcoin", symbol="btc", name="Bintcoin"],[id="etherium", symbol="eth", name="Etherium"]];
and the database table columns is the following:
**| id | coin_id | symbol | name |**
now, I want to update all values to the database, according to the id only, so this is what I did:
// first get ids from my table
$exist_ids = Coinlist::all('coin_id')->pluck('coin_id')->toArray();
//get all ids to update (to ignore other ids):
$updatable_ids = array_values(array_intersect($exist_ids, $allCoinIds));//result for example is: array("bitcoin","etherium");
//and now, update the database:
Coinlist::whereIn('coin_id', $updatable_ids)
->update([
'symbol' => $coinsList[$key]['symbol'],
'name' => $coinsList[$key]['name'],
'updated_at' => now()
]);
the problem is, I don't have the "$key" in order to update the right row, what am I missing here?
Thanks!
Here is a good way to solve it:
in the beginning, I used this library: https://github.com/mavinoo/laravelBatch
to update many dynamic rows, but it was really slow, then thanks to Yasin, I moved to: https://github.com/iksaku/laravel-mass-update and now it works way better.
the implementation is simple, add a simple code to the Model class, then add:
User::massUpdate(
values: [
['username' => 'iksaku', 'name' => 'Jorge González'],
['username' => 'gm_mtz', 'name' => 'Gladys Martínez'],
],
uniqueBy: 'username'
);
while uniqueBy is the key for the row, and add other columns values to change them dynamically.

Laravel save an array of data in individual rows

How can I save an array of data into individual rows in Laravel ?
Here's how my UI looks like
once i click the save button in the controller Store function gets the data
public function store(Request $request, $venue, CustomProduct $customProduct)
{
dd($request->Availability);
}
This is how the data looks like
I'm wondering how can i save this to my database ?
This is how my database table looks like
Please suggest me a way that i can save this to my table
Use this example:
$days = ["monday","thursday","wednesday","tuesday","friday","saturday","sunday"];
forach($request->Availability as $key => $value){
CustomProductAvalibility::create([
'day_id' => array_search($key), // array_search($key) returns day id
'starts_at' => $value["start"],
'ends_at' => $value["end"],
'custom_product_id' => '...' // your custom product id
]);
}

Laravel Replace existing DB value - Favourites

I am trying to setup a favourites button on an article. The following code works ...
public function favouriteNotfavouriteArticleParent(Request $request){
$data = [];
$data['user_id'] = Auth::id();
$data['person_id'] = GetPersonData()['id'];
$data['article_id'] = $request->get('article_id');
$data['action'] = $request->get('action');
UserFavourites::updateOrCreate($data,$data);
}
However, i want it to firstly check for any existing values set for that article ID. If it has favourite set and notfavourite is clicked, it should remove the favourite table row.
At the minute it just adds a row for favourite and notfavourite. I've attached a screenshot of the current sql behaviour.
Any help is massively appreciated!
UpdateOrCreate takes two arguments. The first argument is an array of attributes to look for and the second argument is an array of attributes to change. If there isn't a row in the database that has attributes from the first array the arrays will essentially be combined to make a new row in the database.
To achieve what you're after you could do the following:
UserFavourites::updateOrCreate([
'article_id' => $request->input('article_id'),
'user_id' => auth()->id(),
], [
'person_id' => GetPersonData()['id'],
'action' => $request->input('action'),
]);
The above will look for a row that matches the article_id and user_id and then either update the person_id and action for that row or (if the row doesn't exist) create a new row with all the attributes.

check if record is already exist against user id and update if exist and insert if not exist - using laravel

I am trying to update record against user_id if its already exist and insert new record if not exist against user_id in laravel:
But my user id is inside $doctorProfile['user_id']
data is inserting but user id inserting as NULL:
My Controller Code:
if($request->has('doctor_profile'))
{
$doctorProfile = $body['doctor_profile'];
$data_array = [
'user_id' => $doctorProfile['user_id'],
'medical_credentials' =>
$doctorProfile['medical_credentials'],
'registration_number' =>
$doctorProfile['registration_number'],
'registration_expiration_date' =>
$doctorProfile['registration_expiration_date'],
'dea_number' => $doctorProfile['dea_number'],
'dea_expiration_date' =>
$doctorProfile['dea_expiration_date'],
'dea_issue_date' => $doctorProfile['dea_issue_date'],
'npi_number' => $doctorProfile['npi_number'],
'billing_title' => $doctorProfile['billing_title'],
'billing_employment_type' =>
$doctorProfile['billing_employment_type'],
'other_employment_type' => $doctorProfile['other_employment_type'],
'nadean_number' => $doctorProfile['nadean_number'],
'upin' => $doctorProfile['upin'],
'wcb_authorization' => $doctorProfile['wcb_authorization'],
'wcb_rating_code' => $doctorProfile['wcb_rating_code'],
'wcb_date_of_issue' => $doctorProfile['wcb_date_of_issue'],
'hospital_privileges' => $doctorProfile['hospital_privileges'],
];
$medId = MedicalIdentifiers::firstOrCreate(['user_id' => $doctorProfile['user_id']], $data_array);
$medId->save();
}
you can make it easier
if($request->has('doctor_profile'))
MedicalIdentifiers::firstOrCreate($request->all());
firstOrCreate() checks for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.
The difference between firstOrCreate() and firstOrNew():
firstOrCreate() will automatically create a new entry in the
database if there is not match found. Otherwise it will give you the
matched item.
firstOrNew() will give you a new model instance to work with if
not match was found, but will only be saved to the database when
you explicitly do so (calling save() on the model). Otherwise it
will give you the matched item.
Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name or some mandatory field), you should use firstOrNew(). If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate().
from: First Or Create

multiple value insert using saveField function or other function in cakephp

I insert multiple values into my database using saveField function. Here is my code.
$this->Fuel->saveField(
'device_id', $int_fuel_func[0],
'func_code', $int_fuel_func[1],
'device_data', $int_fuel_func[2]
);
It's not a form value. Value automatically insert when the page is refreshed.
It's only inserts first value 'device_id', $int_fuel_func[0],. Other two values are not insert into my database. Any one suggest me how to insert these values.
Thanks in advance
Cake version 2.7.5
You can simply do this as well.
$data = array(
'device_id' => $int_fuel_value[0],
'func_code' => $int_fuel_value[1],
'device_data' => $int_fuel_value[2]
);
$this->Fuel->save($data);
Also try this blog tutorial (cakephp blog tutorial) if you haven't been there before to be more familiar with these things.
My id is not auto Increment it is defined as varchar. Time is not include there also. I got my answer. I use it and it works.
$this->Fuel->set(
array(
'device_id' => $int_fuel_value[0],
'func_code' => $int_fuel_value[1],
'device_data' => $int_fuel_value[2]
)
);
$this->Fuel->save();
saveField function is only for updating one field! use updateAll and pass an array to it :
$this->Fuel->updateAll(
array(
'device_id', $int_fuel_func[0],
'func_code', $int_fuel_func[1],
'device_data', $int_fuel_func[2]
),
array('Fuel.id' => 234) // conditions for the Fuel you want to update
);

Categories