Laravel4: Chunk function not working with model save() - php

I have a query to select all users and hash the password and save that model. Because it times out as there is large data in the DB, I thought I will try chunk() function. My query looks like,
$users = User::where('password','!=','0')->select(array('password'))->chunk(50,function($users){
foreach ($users as $user) {
$user->password = Hash::make($user->password);
$user->save();
}
});
This doesn't save a model. when I try to dump the $user variable after save() it displays the updated values but when I look into DB it is still unaltered. I tried using try catch and transaction just to see if it hits any exception during the process, nothing helped. Any help will be appreciated. Also, I don't have $guarded on the password field.

You're just doing it wrong. Can you tell which row should be updated in that loop? No? Eloquent doesn't know it either, so it runs update ... where id is null ;)
Simply add id to the select clause and it will work (unless you have some magic happening in the saving event etc):
$users = User::where('password','!=','0')
->select(array('id', 'password'))
->chunk(50,function($users){
foreach ($users as $user) {
$user->password = Hash::make($user->password);
$user->save();
}
});

Related

Build database query in Laravel with eloquent or DB

I need your help to build a query in Laravel either eloquent or DB query would do too.
My table name is Users
To see the DB structure, open the following link:
https://jsfiddle.net/vardaam/mvqzpb2j/
Every user row has 2 columns referral_code and referred_by_code which means every user can refer to someone and earn bonus similarly the same user was also been referred by some one.
I would like to return the information on page with loop in users details along with Username of the user who had referred him to this. To track the same I created those 2 columns in the same table i.e.: referral_code and referred_by_code.
I do not know how to write this in 1 query or how to combine 2 queries and get the desired results.
My controller code looks like below:
$obj_users = User::get();
$codes = [];
$referrers = [];
foreach( $obj_users as $referred_by_code )
{
//Following fetches all user's referred_by_code's code
$codes[] = $referred_by_code->referred_by_code;
}
foreach ($codes as $code)
{
//Following fetches usernames of the given referred_by_code's codes
$referrers[] = User::where('referral_code', $code)->first()->username;
}
return view('users.users', compact(['users', 'paginate', 'referrers']));
The returning $users variable provides me loop of users data but I do not know how to attach those referrer's username to that object.
I tried my level best to describe, please ask incase what I said doesn't make sense, will be happy to provide further clarification.
Best
You can add into your User model the following relationship:
public function referredBy()
{
return $this->belongsTo(User::class, 'referred_code', 'referral_code');
}
In your controller you can use:
$users = User::with('referredBy')->get();
return view('users.users', compact('users'));
and later in your view you can use:
#foreach ($users as $user)
{{ $user->username }} referred by {{ $user->referredBy ? $user->referredBy->username : '-' }}
#endforeach

Updating rows in laravel mysql database

I've set up a database and want to update the column status for each row in my UsersController:
I started with this:
User::where('id', '=', 1)->update(['status' => $status]);
This is working, but I need some loop to change all the rows, something like this:
foreach $id from the table
run some code to change individual $status variable
set individual $status value in the 'status' column in each row:
User::where('id', '=', $id)->update(['status' => $status])
end foreach
So for me its unclear how to go through the table via the foreach. Then save the calculated status from my code to each individual id?
#Serge solution is fine for few records but you should be able to use chuck as #ceejayoz suggested
User::chunk(100, function ($users) {
$users->each(function ($user) {
$user->status = getStatus($user);
$user->save();
});
});
Unless the table contains millions of rows... a simple procedural way of doing it is...
$users = Users::get(); // Gets a collection of all users...
foreach ( $users as $user ) {
//compute your status
$user->status = get_your_user_status($user->id);
$user->save();
}
You could also consider using a more functional approach with map for example...

Laravel Model get all where $id = Auth::user()->id

How to List all rows from a DB where $id matches the logged user id.
I'm using default Auth from Laravel.
At the moment i can list them all with this method in my controller:
public function index(){
$invoices = Invoice::all();
return view('index', compact('invoices'));
}
But i just want the ones that are from this user which is logged in:
Something like
$invoices = Invoice::where('id', '=', Auth::user()->id);
Your code Seems almost right. I would do:
$invoice = Invoice::where('id', Auth::user()->id)->get();
So basically use the get in order to fetch a collection. And maybe I would separate the user id in a varaible in case that you change the authentication in the future ;)
When using any condition then of course you must need to add the get() method. Otherwise, you can't show your data.
$invoices = Invoice::where('id', '=', Auth::user()->id)->get();
This means that you want to see data on which user is logged in now

Laravel-5 using fill() to update database

I'm trying to use fill() to update a current row in the database. However, it seems to be creating a new row instead of updating each time.
Does anyone know what could be wrong?
Here's my code:
$reserve->where('cookie_id', 'idCode')->first();
$reserve->fill($request->all())->save();
return Redirect::to('checkout');
Try something similar to this
$user = User::where ('cookie_id', 'idCode');
$new_user_data = $request->all();
$user->fill($new_user_data);
$user->save();
You can also try using update()
$affectedRows = User::where('votes', '>', 100)->update($request->all());
Judging by your code you've misunderstood how to fetch an instance out the database. See http://laravel.com/docs/5.1/eloquent#retrieving-single-models
Try the following
$reserve = Reserve::where('cookie_id', $id)->first();
$reserve->fill($request->input())->save();
return redirect()->to('checkout');

How to update a column of a field in Laravel 4?

I'm trying to call an AJAX request on a route that calls this function updateImpression() in UserController, and this function tries to increment the counter column named "impressions_cpunt" in my 'users' table stored in MySQL. I tried using Eloquent to update the column of one particular user only.
public function updateImpression()
{
$username = Input::get('username');
$user = User::where('username', '=', $username)->first();
$impressions_count = $user->impressions_count + 1;
// save() method failed to update my database.
// $user->impressions_count = $impressions_count;
// $user->save();
//update() method does not return anything. Any syntax error here?
//$user->update(array('impressions_count' => $impressions_count));
DB::table('users')
->where('username', $username)
->update(array('impressions_count' => $impressions_count));
$user = User::where('username', '=', $username)->first();
return $user->impressions_count;
}
I think save() function should be work at the first place but my database doesn't get updated and return the original count, and the update() function doesn't even returning any value from the function. This only works when I use DB but I think Eloquent should be better to use since this is Laravel. Is there anything I missed or something wrong with the syntax? I know increments() data type should be used but please allow me to solve this before I change anything.
Update:
This is my database queries shown in Debugbar when I use save() method:
select * from 'users' where 'username'= <test> limit 1
select count(*) as aggregate from 'users' where 'username'= <test>
select count(*) as aggregate from 'users' where 'email'= <test#example.org>
User object (which supposed to be Eloquent child) like any other entity will store its state after changes if your save() call was successful. Therefore, there is no need to update the record explicitly. In your case I would go with something like this:
public function updateImpression()
{
$username = Input::get('username');
$user = User::where('username', '=', $username)->first();
$user->impressions_count += 1;
$user->save();
return $user->impressions_count;
}
In Laravel 5.2 you can update specific column by using the following Eloquent builder:
public function update(Request $request, $id) {
$user = User::where('id', $id)->update(['name', $request->name]);
return redirect()->back()->with('status', trans('User has been updated successfully.'))
}

Categories