directly increment or decrement number update from column using Laravel Eloquent - php

I have a query where in I use Eloquent for finding the ID but what I need is to directly subtract inside the eloquent query ? same as in Query Builder,
Documentation code
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
What I need is to directly to substract
$flight = App\Flight::find(1);
$flight->value =- 1;
$flight->save();

use laravel increment() or decrement() method see
App\Flight::find(1)->decrement('value',1);
second way u can achieve by update query
App\Flight::where('id', 1)->update(['value' => \DB::raw('value - 1')]);

you need to do this
$flight = App\Flight::find(1);
$flight->value = $flight->value-1;
$flight->save();
hope it helps! :)

Related

How to use update() functionality in Laravel?

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!

retrieve single row in LARAVELusing eloquent

i am using laravel 5.1 and want to retrieve a single row in the database then manipulate it after.
my current code is
$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();
foreach($profiles as $profile ){
$data['address'] = $profile->address;
}
why cant i do it like this?
$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();
$data['address'] = $profiles->address;
am i using a wrong function or something?
thanks in advance.
Try this:
$data['address'] = $profiles[0]->address;
When you are using get(), it returns an array of Std class object.
In addition to retrieving all of the records for a given table, you may also retrieve single records using first. Instead of returning a collection of models, these methods return a single model instance:
// Retrieve the first model matching the query constraints...
$flight = App\Flight::where('active', 1)->first();
laravel 5.8
Retrieving A Single Row / Column From Profile
If you just need to retrieve a single row from the database table, you may use the first() method. This method will return a single stdClass object:
$Profile = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->first();
If you don't even need an entire row, you may extract a single value from a record using the value() method. This method will return the value of the column directly:
$address = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->value('address');

Laravel 5.2 Conditional Update to Database

How do I update a database column based on a value from a different column?
I have a query like the following which pulls current usage (example: 200):
$currentusage = CurrentPercentageModel::select('current_usage')->where('name', '=', 'User Name')->get();
I would like to update the same value +1 after the each time it passes certain conditions.
My save query would look like this and adds a new row to the table with the new value (example: 201):
$currentusage = $currentusage + 1;
$savecurrentusage = new CurrentPercentageModel;
$savecurrentusage->current_usage = $currentusage;
$savecurrentusage->save();
How do I update the same value from the one I pull from my query?
A bit messy but should works
$model = CurrentPercentageModel::where('name', '=', 'User Name')->first();
$model->current_usage += 1;
$model->save();
If you just want to add 1 to one of the fields, I guess the simplest way will be using Query Builder's increment() method:
DB::table('current_percentage')->increment('current_usage');
If you want to use Eloquent, you can do this:
$current = CurrentPercentageModel::where('name', '=', 'User Name')->first();
$current->update(['current_usage' => ++$current->current_usage]);
Try this
$currentPercent = CurrentPercentageModel::where('name', '=', 'User Name')->first();
$currentusage = $currentPercent->currentusage + 1;
$currentPercent->current_usage = $currentusage;
$currentPercent->save();

ORDER BY "the date" Laravel 5 SQL Query

I want to sort the results by the date, but this Laravel 5 SQL Query is not working as i want.
$b = DB::table('entry')
->select(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y') as tanggal"))
->groupBy(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y')"))
->orderBy(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y')"), 'asc')
->get();
Here's the easy way to achieve this
Step 1 :
Create a Model named as Entry by artisan command or manually
Step 2 :
Then from your Controller just do
$entry = Entry::orderBy('created_at', 'ASC')->get();
Then you should get the $entry array of what you need.
Hope this helps you
You can still use DB::table and simply put this orderBy. It will work just like the above mentioned.
$query = DB::table('entry')
->select(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y') as tanggal"))
->orderBy('created_at','ASC')->get(); //either this
->orderBy('updated_at','ASC')->get(); // or this
$query = DB::table('entry')
->select(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y') as tanggal"))
->orderBy('created_at','DESC')->get(); //either this
->orderBy('updated_at','DESC')->get(); // or this
Note: Either you put 'ASC' or not it will automatically sort it ascendingly.

Laravel nested where using eloquent

I'm using eloquent to build a query but i'm stuck in the final phase.
$city = City::where('name', $event)->first()->event;
This is working and returns all 3 events for this city, as shown in the screenshot
I want to perform another where for the events, so i can select only 1 based on criteria but it's not working.
I have tried the following
$city = City::where('name', $event)->first()->event->where('id', 1);
and it's giving me the following error
Call to undefined method Illuminate\Database\Eloquent\Collection::where()
Your very example makes no sense, since all you need is:
$eventId = 1;
Event::find($eventId);
In case you wanted to check if that even is related to the city:
Event::where('city_id', $cityId)->find($eventId); // Event model or null
or a bit complicated in this case, but generic solution for any relation type:
Event::whereHas('city', function ($q) use ($cityId) {
$q->where('id', $cityId);
})->find($eventId); // model or null
And finally, if you used find instead of where:
City::where('name', $event)->first()->event->find(1);
City::where('name', $event)->first()->event()->find(1);
It would return the same Model.
This is because find it does basically the same in the context of a query builder:
City::where('name', $event)->first()->event()->where('id', 1)->first();
// equals to:
City::where('name', $event)->first()->event()->find(1);
but it is also a method of the collection:
$someCollection->find($someId); // returns single Model
If you already have the id (1), you can do something like:
$city = City::where('name', $event)->where('id', 1)->first();
But I think you'd rather want the city_id:
$city = City::where('name', $event)->where('city_id', 3)->first();
Solution
The solution is to use event()-> instead of event->
This query is returning the 1st record of the relationship, Which is what i needed.
Thanks everyone!
$city = City::where('name', $event)->first()->event()->where('id', 1)->get();

Categories