Laravel updateOrCreate with where clause - laravel

How to implement updateOrCreate function with where clause.
For example. I would want to update a field only if certain column contains a specific value otherwise don't update.
Is it possible with updateOrCreate function?

updateOrCreate is an update with where-clause:
$user = User::updateOrCreate(
[
'id' => $userId,
'type' => $userType,
],
[
'name' => $userName,
'email' => $userEmail,
]
);
This query will update the user with $userName and $userEmail if a user exists with matching $userId and $userType. If no matching user is found, a new user is created with $userId, $userType, $userName and $userEmail.
So the first array is the "where-clause" that has to match for the update, second array is the values that should be updated if a match is found and a merge of both arrays are used when creating a new user if no match was found.
See docs here

updateOrCreate mainly used when you upadate one column value in your model.You don't know the condition either this row is exists or not.If the row is exists then it just upadte your column value otherwise it create that row.
$update_value = YourModel::updateOrCreate(
['your_checking_column' => 'your_value',],
['your_updated_coumn' => 'your_updated_value']
);

updateOrCreate doesn't provide this functionality as far as I know. Instead you can use regular where clause followed by update. From your question I see that you don't need to create at all.
Something::where('column', 'value')->first()->update(['otherColumn' => 'some value']);

If you're trying to set a value based on some criteria you can use a ternary:
'user_id' => ($request->user_id && is_numeric($request->user_id) ? $request->user_id : \Auth::user()->id)
This is the equivalent of saying, if user_id is provided and numeric, set the value to $request->user_id, otherwise take the user_id from the authenticated user, a simpler example:
'user_id' => ($request->user_id ? $request->user_id : null)
If a user_id is give in the request use that value, otherwise set value to null.

Related

how to get the value in array from database laravel

I want to extract the values from array in a column from database. For example, my value in my permission column is ["Create","Edit","Delete]. So when I dd($user->permission) it would return like that. How can I get the value from it so that I can return the result in a list. I have really no idea for now and what I cannot find similar question to mine.
This is a task for mutators. Simply add to your model:
protected $casts = [
'permission' => 'array',
];

Problem with adding record to database after seeds in Laravel

I add test records to the database using seeds
public function run()
{
DB::table('categories')->insert([
['id' => 1,'name' => 'Select a category', 'slug' => null],
['id' => 2,'name' => 'Computers', 'slug' => 'computer-&-office'],
]);
}
But then, if I want to add a new record to the database, already through the form, I get the error
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "categories_pkey"
I understand that when I add a new record through the form, it is created with id = 1, and I already have this id in the database. How can I avoid this error?
You should remove id from insert() and make it auto increment in mysql,
It complains about a unique constraint, meaning your primary key is indexed as "categories_pkey" or you have another field that is unique.
This happens because you are inserting a record and a record already exists where that column must be unique.
In general production workflow, when you add a record you never specify an ID. Most cases (there are exceptions) ID is an autoincrement integer, meaning it adds up automatically. On the first insert the database set its ID to 1, the second to 2 and so on.
As a seeder, its generally a good idea to set up the ID so you know that a certain ID matches a certain item (as a base content of a project like user states or roles).
As a regular workflow (from a form submission), you can have something like this
DB::table('categories')->insert([
['name' => 'some value', 'slug' => 'some slug']
]);
However, I don't advise to use DB::table when Laravel provides ActiveRecords pattern (ORM, called Eloquent) which you should take a look here.
https://laravel.com/docs/8.x/eloquent#introduction
Besides the benefits of layer abstraction and working with activerecords, It produces a much cleaner code like
$data = ['slug' => 'some slug', 'name' => 'some name'];
Category::create($data);

Difference between [attributes:protected] and [original:protected]

Please could anyone explain to me a difference between [attributes:protected] array and [original:protected] array in laravel when using print_r to an array?
When Model reads data from table, arrays 'original' and 'attribute' contains same data. When you change the attribute value (ex $user->name='John'), the change is reflected only on the 'attributes' array but 'original' remains same. (hence the name).
When update() on a model is called, method checks what has changed comparing two arrays and construct query only for changed fields. Thus, in the case of $users->name change Laravel will not create this code:
UPDATE users set name = 'John', password = 'pass', email = 'email' where id = 1
but this:
UPDATE users set name = 'John' where id = 1
This may not be the only way Eloquent uses 'original' array. I found clockwork helpful when you need to see what's going on under the hood of Eloquent.

laravel validation check field equal something

how to check a field is exactly equal to a string or number
I want to check a field named course_id is equal a field of database id in course database. now I want to check if course_id is equal to id.
You can validate it by using the exists validation rule:
$validationRules = ['course_id' => 'exists:course,id'];
create rule as below and use validator on input
$rules = array(
'id' => 'exists:your_table_name'
);
for more help
https://laravel.com/docs/5.2/validation#rule-exists

First Or Create

I know using:
User::firstOrCreate(array('name' => $input['name'], 'email' => $input['email'], 'password' => $input['password']));
Checks whether the user exists first, if not it creates it, but how does it check? Does it check on all the params provided or is there a way to specifiy a specific param, e.g. can I just check that the email address exists, and not the name - as two users may have the same name but their email address needs to be unique.
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().
As of Laravel 5.3 it's possible to do this in one step with firstOrCreate using a second optional values parameter used only if a new record is created, and not for the initial search. It's explained in the documentation as follows:
The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model cannot be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument.
Example
$user = User::firstOrCreate([
'email' => 'dummy#domain.example'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
This returns the User for the specified email if found, otherwise creates and returns a new user with the combined array of email, firstName, and lastName.
This technique requires Mass Assignment to be set up, either using the fillable or guarded properties to dictate which fields may be passed into the create call.
For this example the following would work (as a property of the User class):
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['email', 'firstName', 'lastName'];
firstOrCreate() checks for all the arguments to be present before it finds a match.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like:
$user = User::firstOrCreate([
'email' => 'abcd#gmail.com'
], [
'firstName' => 'abcd',
'lastName' => 'efgh',
'veristyName'=>'xyz',
]);
Then it checks only the email.
An update:
As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.
The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:
See the Laravel API documentation
You can always check if in current instance the record is created with the help of
$user->wasRecentlyCreated
So basically you can
if($user->wasRecentlyCreated){
// do what you need to do here
}

Resources