Laravel Eloquent - update() function - laravel

Laravel's Eloquent update() function returns a boolean, and not the updated entry. I'm using:
return User::find($id)->update( Input::all() )
And this returns only a boolean. Is there a way I can get the actual row, without running another query?

I think that's the behaviour that you want:
$user = User::find($id)->fill(Input::all());
return ($user->update())?$user:false;
I hope it works fine for you.

Another approach can is to use the laravel tap helper function.
Here is an example to use it for updating and getting the updated model:
$user = User::first();
$updated = tap($user)->update([
"username" => "newUserName123"
]);
tap($user) allows us to chain any method from that model. While at the end, it will return the $user model instead of what update method returned.

Related

BadMethodCallException Call to undefined method App\User::map()

I want to add additional data to $user collection so can get the profile fields in the view
I have tried using $user['profileFields'] = $this->getProfileFields() and pass $user to the view using compatct or with and this is working fine.
DD
However, I have found some reference over the net saying I can extend using map but when I tried it is giving the following error
BadMethodCallException
Call to undefined method App\User::map()
So here is what I am trying to understand
Question:
Is the below code is wrong and won't work for what I am looking for and the first approach is the solution? Is there any
recommended method to add additional data to the $user collection?
public function show(User $user)
{
$user->map(function ($user){
$user['profileFields'] = $this->getProfileFields();
return $user;
});
return view('admin.user.show', compact('user'));
}
collection methods are works on the collection, here you're getting the object of user.
$user->profileFields = $user->getProfileFields();
return view('admin.user.show', compact('user'));
If the profileFields is in another table and having a foreign key with model ProfileField, then try to add a one to one relation to the User model.
Inside the User model, add a function
public function profileFields()
{
return $this->belongsTo('App\ProfileField', 'foreign_key','other_key');
}
This will give you the profileFields in every user when calling using eloquent.

Laravel 6, passing multiple arrays from a controller to a view

I'm brand new to Laravel, I need to display around 8 different drop down menus on a page all populated from tables in my Db, I am using blades.
In my controller I can create various types of arraysin one function (using eloquent) and I can dd(); them out correctly one at a time, my issue appears to be that you can only pass one array through a controller to a view. I have tried various options I found here but without success, including ->with and compact(). I have tried defining the arrays in the controller one at a time and passing them using compact() all result in errors either the variable not defined or trying to get an non-object. I am obviously going about this all wrong any help would be great.
This is not a code issue (hence no code posted) I think it more of a Laravel issue that I don't yet understand, thanks in advance.
Try like this
class YourController extends Controller{
public function yourMethod(){
$arr1 = [];
$arr2 = [];
return view('view.name', ['arr1' => $arr1, 'arr2' => $arr2]);
}
}
If you have:
$array1 = [...];
$array2 = [...];
Then you can:
return view('path.to.view', compact('array1', 'array2');
This is my route from web.php and my controller from ReservationContoller any help as to my the arrays wont pass would be great, many thanks.
Route::get('/client/{client}/reservation/{reservation}', 'ReservationController#getReservation');
public function getReservation($client, $reservation)
{
$client = Client::findOrFail($client);
$reservation = Reservation::where('client_id', $client->id)->get();
$company = Company::where('type', 'staghen')
->where('status', 'Active')
->orderBy('comp_name')
->pluck('comp_name', 'id');
$cl = array(['client' => $client]);
$res = array(['reservation' => $reservation]);
$comp = array(['company' => $company]);
return view('admin.reservations.reservation', compact('$cl', '$res', '$comp'));
}

How can I use laravel db query ->update() method in if statement

I want to check something in if, and if that condition is true I want to update the record that was fetched before.
$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();
if (this condition will pass I want to update this record) {
$resultQuery->update(array('price_usd' => $card->prices->usd));
}
When I use the ->update() like this, I get an error:
Call to undefined method stdClass::update();
How can I do this ?
The first() function on laravel query builder returns a stdClass meaning Standard Class.
There is no function called update() in stdClass in php. You have called update() on stdClass, and that causes the error.
There are several ways to achieve your goal.
Use Laravel query builder update() function.
$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();
if (your_condition) {
Db::table('cards')
->where('api_id', $card->id)
->update([
'price_usd' => $card->prices->usd
]);
}
If you don't want to fetch the card data, don't call first()
$resultQuery = DB::table('cards')->where('api_id', $card->id);
if (your_condition) {
$resultQuery
->update([
'price_usd' => $card->prices->usd
]);
}
Use Eloquent models (Laravel's preferred way)
Create an Eloquent model for Cards (if you have not done already).
public class Card extends Model
{
}
Use eloquent query builder to fetch data. And use model update() function to update data.
$resultingCard = Card::where('api_id', $card->id)->first();
if (your_condition) {
$resultingCard->update([
'price_usd' => $card->prices->usd,
]);
}
If you're using model
You can add in card controller
$card = Card::where('api_id', $card->id)->first();
if (someConditional)
{
// Use card properties, number is a example.
$card->number = 10
// This line update this card.
$card->save();
}
You can learn more about eloquent here.
Something like this:
$resultQuery = DB::table('cards')->where('api_id', $card->id);
if ($resultQuery->count()) {
$object = $resultQuery->first();
$object->price_usd = $card->prices->usd;
$object->save();
}
Or look for an alternative solutions here: Eloquent ->first() if ->exists()

Update the Record of Related Model in Laravel

How to update a record in the related table model by chain expression?
This is what I currently do (and it works)
$user = User::find(1);
$token = Token::where('user_id', $user->id)->first();
$token->token = $request->token;
$token->save();
But can I do the above in a more elegant way, such as?
$user = User::find(1);
$user->token()->token = $new_token;
$user->token()->save();
My User Model
public function token()
{
return $this->hasOne('App\Token');
}
In one line:
User::find(1)->token()->update(['token' => $new_token]);
Just know these things before using it:
User find could return null if the user id is not found.
The saved and updated model events will not be fired for the updated models.
The update method execution does not go through the Eloquent model methods.
However in your particular case I think it's valid, specially if you know that the user id will always be valid.
Yo can do it like this :
User::find(1)->token()->update(['token' => $new_token]);
Or do it in youApp\Token class like this :
User::find(1)->token()->update_token($new_token);
And create update_token function in App\Token class:
public function update_token(string $new_token)
{
$this->update(['token'=>$new_token]);
}
$user = User::with('token')->findOrFail(1);
$user->token->update(['token' => $request->token]);

How to get product after insert and update in query builder

I'm trying to get the same result as in Eloquent when create and update will return the model back.
In the case of query builder, how can I return the model when insert returns boolean and update returns the ID of the updated row?!?!?
For example: DB::table('users')->insert( ['email' => 'john#example.com', 'votes' => 0] );
Will return boolean, instead what I am looking for is to get that created user, same behavior with User::create().
DB::table('users')->update() will return the ID of the updated row, again I want the updated row as an object same behavior with User::update().
I know that insertGetId() will give me the ID when I use insert(), but I don't want to make an extra step to use the ID and find the row.
Also, for the update, I don't want to use the ID that update() returns to use it in order to find the row.
Does that make any sense?
Use insertGetId() instead of insert() and then find() the model. For example:
$id = DB::table('users')->insertGetId(['name' => 'Ivanka', 'email' => 'ivanka#ivanka.com']);
$user = User::find($id);
When you are updating you have the id, so just find() it: User::find($id).
Documentation that explains how insertGetId() works: https://laravel.com/docs/5.7/queries#inserts
also, you can use from below code if you want.
find the last insert column:
$last_id = Illuminate\Support\Facades\DB::getPdo()->lastInsertId();
and next:
$user = User::find($last_id);

Resources