Laravel 5.2 Model sync() except field - laravel

So I'm having $user as an instance of User model, and when I'm doing
$user->data()->sync($new_data) the fields address, country and postal_code get updated.
But what if I want to update everything except country? Is there some way to do like
$user->data()->sync($new_data)->except('country')?
Can't find anything in docs so far.

You can use updateExistingPivot as:
$attributes = ['address' => 'some_value', 'postal_code' => 'some_value'];
$user->data()->updateExistingPivot($data_id, $attributes);

Related

Laravel update one field of a model relation

I am trying to update only one field on a models relation but it keeps returning it as null and I cant figure out why;
The profile is a belongsTo relationship
$user = User::find(1);
$user->profile->api_key = 'apikeyhere';
$user->save();
After i do this and then run dd($user->profile) .. The api_key field is null instead of the actual value.
Using two query
$user = User::find(1);
$user->profile()->update([ 'api_key' => 'apikeyhere']);
Using One query
Profile::where('user_id', 1)->update([ 'api_key' => 'apikeyhere']);
Update the field using the relation.
$user = User::find(1);
$user->profile()->update(['api_key' => 'api_key value']);

Laravel 8.0 facing issue while trying to update a table with vue form, 'Attempt to read property \"item_id\" on null'

So, i have a table called Items table and another table called item_quantities, on item_quantities ive a column named item_id which is connected to items table id. All the fillable properties on both tables are all in one form on the frontend, and i take care of the form fields on the backend
Whenever i try to update the quantity on the form which is from item_quantities's table with a form, i'm facing serious issue updating the item_quantities. getting Attempt to read property "item_id" on null.
It all started when i noticed a duplicate entries on the item-quantities table, so i deleted all the datas on it..
Here's is the form screenshot
The vue form
and the backend logic
public function saveData(Request $request, $id) {
// dd($request->name);
$updateGroceries = Item::where('id', $request->id)->get()->first();
$updateGroceries->update([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
]);
if($updateGroceries) {
$item_quantity = ItemQuantity::where('item_id', $updateGroceries->id) ?
ItemQuantity::where('item_id', $updateGroceries->id)->get()->first() :
new ItemQuantity;
if($item_quantity->item_id == null) {
$item_quantity->item_id = $updateGroceries->id;
}
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
}
}
I'M SO SORRY IF MY ENGLISH WAS'NT CLEARED ENOUGH
Thanks in anticipation
You can simply use firstOrNew() method. This will first find the item, if not exist create e new instance.
$item_quantity = ItemQuantity::firstOrNew(['item_id' => $updateGroceries->id]);
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
Note that the model returned by firstOrNew() has not yet been persisted to the database. You will need to manually call the save method to persist it.
Actually your errors workflow as that:
$item_quantity=null;
$item_quantity->item_id;
You can do that with optional global helper:
optional($item_quantity)->item_id ?: 'default value';

Duplicate on 2 fields

I looking a way to avoid the duplicates in Laravel. For example, I have a table with 2 fields which are name and firstname.
How to manage the duplicates on the Controller? I am newbie...
Here is my function store().
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:25',
'firstname' => 'required|string|max:25'
]);
$exists = Auteur::where('name', $request->get('name'))->where('firstName', $request->get('firstName'))->count();
if (!$exists){
Auteur::create($request->all());
return redirect()->route('auteurs.index')
->with('success', 'save');
}
}
I thank you for your help and your explanations.
If it were one field, you could use validation, or make that field unique and that would take care of it with a little error handling. However, with two fields to have to check against, it might be easiest to check if the element is already in the database and deduplicate from there. So in the store() method:
$exists = Auteur::where('name', $req->get('name'))->where('firstname', $req->get('firstname')->count();
if (!$exists){
// create the new model, now that we know there is no duplicate in the database
Auteur::create($request->all());
}
Just add unique in your validation rule. If you would like to check unique validation each field separately.
$request->validate([
'name' => 'required|unique:auteurs,name|string|max:25',
'firstname' => 'required|unique:auteurs,firstname|string|max:25'
]);
Here I hope the table name is `auteurs`

Laravel Coding Practice / Most Optimised Method to Store

Laravel documentation says one should store as follows:
public function store(Request $request)
{
// Validate the request...
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
}
However, why not just as follows:
public function store(Request $request)
{
Flight::create($request->all());
}
The above example is quite easy, since it only has one field. But I imagine its rather tedious to do something with many fields and have to assign each one as opposed to just passing the whole $request as in the second example?
First option gives you better control as to what goes into new model. If you store everything from the request then user might inject fields that you don't want to be stored for a new model in your store method.
For example, your flight has column is_top_priority that is declared as fillable in your Flight model, but when creating new flight you want to set only name for you flight (and leave is_top_priority as null or maybe it has default value of 0 in your table). If you write Flight::create($request->all()); then user can inject <input name="is_top_priority" value="1"> and get advantage of your code.
That is why it is not recommended to use fill($request->all()). Use $request->only(...) or assign each needed field manually as provided in your first example.
For example your model have some fields like name, email, password,status and etc.
Request validate name, email and password and if you do this:
Flight::create($request->all());
Client can send with other fields status, but you change status manually. I do this:
Flight::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => $request->get('password'),
'status' =>config('params.flight.status.not_active'),
]);

User::all show relationship items

I Laravel 5.5 I am returning users information like this...
$users = User::all();
return Response::json(array(
'error' => false,
'response' => $users,
));
I have a belongs to many categories relationship setup and would like to also show all of the categories each user belongs to.
Anyone have an example I can see?
Use the with() method to load categories for each user:
$users = User::with('categories')->get();
If you don't need to load all the columns from the categories table, use select() inside the with() closure. Also, since you're using Laravel 5.5 you could use Resource classes for formatting JSON.

Resources