I am using Laravel 5.5 and I am declaring my model object the following:
$product = new product();
$product->name = $coinArr[$key];
$product->symbol = $symbolArr[$key];
$product->current_price = $priceArr[$key];
///save image to public folder
$fileName = basename($imgArr[$key]);
Image::make($imgArr[$key])->save(public_path('images/' . $fileName));
$product->asset_logo = $fileName;
//$product->updateOrCreate();
App/Product::updateOrCreate($product);
If the product does not exist in the database I would like to create it else just update it.
I tried the following two ways to use the updateOrCreate method. However, I receive the following error for App/Product::updateOrCreate($product);:
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::updateOrCreate(), 0 passed in C:\Users\admin\Desktop\Coding Projects\laravel_proj\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 1455 and at least 1 expected
And the following error for $product->updateOrCreate();:
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::updateOrCreate()
Any suggestions how to use updateOrCreate with my model object?
I appreciate your replies!
When you use updateOrCreate, you need to choose which attributes are used to determine if the product exists already. The function takes 2 arrays:
product::updateOrCreate([
'name' => $coinArr[$key] //Laravel will check if this model exists by name
],[
'symbol' => $symbolArr[$key] //if exists, will update symbol. if doesnt exist, will create new with this name and symbol
]);
That's not how the updateOrCreate() method works. In the first parameter you put an array with search conditions. If you want to search existing route by name for example, the correct syntax will be:
Product::updateOrCreate(
[
'name' => $coinArr[$key]
],
[
'symbol' => $symbolArr[$key],
'current_price' => $symbolArr[$key],
'asset_logo' => $fileName
]
);
The second parameter is array for creating a new object.
https://laravel.com/docs/5.5/eloquent#other-creation-methods
Related
I am new to laravel.
I have an issue when I am trying to update or create record in DB.
I have a table called DspAccountFee with this columns:
I want to create record of dsp_account_id + screen_type when the combination not exists, and to update if the combination exists.
this is my code: (just tried to update the first row keys of -> dsp_account_id(5187) + screen type (ctv). However nothing changed.
DspAccountFee::updateOrCreate(
['dsp_account_id' => $dsp_account_id, 'screen_type' => 'ctv'],
['pmp_percent' =>$fields['fee_ctv_pmp_percent'], 'omp_percent' => $fields['fee_ctv_omp_percent']]
);
When I print the values before the DB operation they exists:
\Log::info("dsp_account:");
\Log::info($dsp_account_id);
\Log::info("ctv pmp percent:");
\Log::info($fields['fee_ctv_pmp_percent']);
\Log::info("ctv omp percent:");
\Log::info($fields['fee_ctv_omp_percent']);
\Log::info("app pmp percent:");
What I am missing why it is not update the db? Nothing in logs and No exception
this is my method in the model
protected $fillable = array(
'dsp_account_id', 'screen_type'
);
Check the corresponding model and make sure that those columns exist in the
$fillable property. It should look somewhat like this.
protected $fillable = [
'dsp_account_id',
'screen_type',
'pmp_percent',
'omp_percent'
];
Your updateOrCreate syntax looks okay.
To update the updated_at column in your database, you can use the touch() method: you'll need to edit your code to something like this
$foo = DspAccountFee::updateOrCreate([
'dsp_account_id' => $dsp_account_id,
'screen_type' => 'ctv'
],
[
'pmp_percent' => $fields['fee_ctv_pmp_percent'],
'omp_percent' => $fields['fee_ctv_omp_percent']
]);
$foo->touch();
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
I'm trying to create a comment form, but I'm stuck with something.
I retrieve my data with findBy(array('slug' => $slug)) .
I know that this method returns an array, not an object.
When I want to add a comment, I have an error
"Type error: Argument 1 passed to AppBundle\Entity\Comment::setTrick() must
be an instance of AppBundle\Entity\Trick, array given, called in
/Applications/MAMP/htdocs/SnowTricks/src/AppBundle/Controller
/AppController.php on line 71"
How can I create, or use a method that returns an object ?
Thanks for your replies and sorry for my English
If you need to retrieve single entity, you should use method ::findOneBy
$entity = $this->getDoctrine()
->getRepository('AppBundle:Trick')
->findOneBy(array('slug' => $slug))
;
I am trying to achieve something that should be simple but seems impossible in PHP ActiveRecord.
In the simplified example I created, I have two models, Person and Exchange, and two tables, people(id, name) and exchange(id, user_from_id, user_to_id, comment). exchange.user_from_id and exchange.user_to_id have a foreign key constraint referencing people.id.
So when I run the following code:
$exchange = Exchange::first();
echo $exchange->user_from_id;
echo $exchange->user_from_id->name;
I would expect the first echo to fail and the second one to succeed. Instead, the first one succeeds and prints the litteral value of exchange.user_from_id and then obviously the second one generates a "Trying to get property of non-object" warning.
The result is the same with or without adding the following to Exchange:
static $belongs_to = array(
array('user_from_id', 'class_name' => 'Person'),
array('user_to_id', 'class_name' => 'Person')
);
What should I change in my code to make it so that $exchange->user_from_id returns an instance of the Person class?
It turns out I had misunderstood how BelongsTo work. I thought it somehow bound a property of a Model, corresponding to an attribute, to a different Model, but I realise now it creates a new property, which you then have to explicitely associate with an attribute using the foreign_key option.
Concretely, this is what I had to add to the Exchange:
static $belongs_to = array(
array('user_from',
'class_name' => 'Person',
'foreign_key' => 'user_from_id'),
array('user_to',
'class_name' => 'Person',
'foreign_key' => 'user_to_id')
);
Then, using this code:
$exchange = Exchange::first();
echo $exchange->user_from;
echo $exchange->user_from->name;
I finally got what I expected: a fatal error on the first echo and the second one printing people.name where people.id = exchange.user_from_id.
This also made it possible to use eager loading of the two people objects with:
$exchange = Exchange::first(array('include' => array('user_from', 'user_to')));
I have a dynamic input field called name="step[]". When submitting the form and displaying the $request->step using dd, I get this:
array:3 [
0 => "Test Step 1"
1 => "Test Step 2"
2 => "Test Step 3"
]
So it is an array. Now, when I want to insert the data using:
$project = new Project;
$project->name = $request->name;
$project->save();
$project->steps()->saveMany($request->step);
I am getting this error:
Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, string given
Project Model:
public function steps()
{
return $this->hasMany('App\Step');
}
My goal is to create a new Project and save it to the database, and save all steps in my Step table. So each Project hasMany steps. Not sure why I am getting the above error though, since I am passing an array?
I usually realize using a foreach loop. Your relation method seems to look OK. Does this work?
foreach($request->steps as $step) {
$project->steps()->create(['step' => $step]);
}
Did you try using the attach method?
$project->steps()->attach($resquest->input('steps'));