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']);
Related
Laravel serialization documentation describes in detail how to get array / JSON representation of Eloquent models.
However, it doesn't currently say a word about reversing this: getting Eloquent models out of arrays / JSON.
How do I do this? Thanks!
I know it's old but if anybody is still looking for it.
Maybe you are trying to do the fill operation.
Eg:
$user = [
'name' => 'Foo Bar',
'email' => 'foo#bar.com',
];
$userModel = new User();
$userModel->fill($user);
// If you want to save this then -> $userModel->save();
You will have to make an instance of your model and affect your data to it, for example, supposer you have a array representation of a User model like this:
$user = [
"name" => "foo",
"age" => 40
]
then you will have to create your model like this:
$user = User::create($user);
//or
$user = new User;
$user->name = $user["name"];
$user->age = $user["age"];
$user->save()
I have a many-to-many relationship between the User and Subscription tables in Laravel, as follows:
In Subscription.php:
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
In User.php
public function subscriptions()
{
return $this->belongsToMany('App\Subscription')->withTimestamps();
}
I create a new subscription in Cashier (using Stripe) as follows:
$user->newSubscription($planname, $planname)->create();
(Note that the product and plan names are currently the same and the user's card is on record, hence the lack of a stripe token.)
But when I run this I get an error:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into subscriptions (name, stripe_id, stripe_plan, quantity, updated_at, created_at) values (projects, sub_EY1zRywZ1jUjLl, projects, 1, 2019-02-17 20:07:36, 2019-02-17 20:07:36))
I'm not sure if the relationship is causing the issue or whether it's my new subscription code. How do I fix this error?
UPDATE:
I've made the following change and I still get the same error:
$user->newSubscription($planname, $planname)->create(null,[
'user_id' => $user->id,
]);
UPDATE 2:
I've made the following change and the exact same error still occurs:
$id = Auth::id();
$user = User::find($id);
// $user = Auth::user();
Do you have the Billable trait added to your User model?
General error: 1364 Field 'user_id' doesn't have a default value.
According to this, I think you need to fill the user_id column with an id value via $id = Auth::id();
Taken from laravel documentation:
Additional User Details
If you would like to specify additional customer details, you may do so by passing them as the second argument to the create method:
$user->newSubscription('main', 'monthly')->create($stripeToken, [
'email' => $email,
]);
UPDATE
Could you try this one:
$id = Auth::id();
$user = User::find($id);
$user->newSubscription($planname, $planname)->create();
I'm trying to build a chat application using laravel echo and pusher, everything works but the data that returns to the databse is either null or the default value, here's the code
public function sendMessage(Request $request){
$conID = $request->conID;
$message1 = $request->message;
$user = Auth::user();
$fetch_userTo = DB::table('messages')
->where('conversation_id', $conID)
->where('user_to', '!=', Auth::user()->id)
->get();
$userTo = $fetch_userTo[0]->user_to;
$message = Message::create([
'user_from' => Auth::user()->id,
'user_to' => $userTo,
'conversation_id' => $conID,
'message' => $message1,
]);
if($message) {
$userMsg = DB::table('messages')
->join('users', 'users.id','messages.user_from')
->where('messages.conversation_id', $conID)->get();
broadcast(new MessagePosted($message))->toOthers();
return $userMsg;
}
}
NB: when i put insert() instead of create in the query the data goes through the database normally but there's an error in broadcasting
Have you tried to create a message like this? instead of using a model event?
$message = new Message;
$message->user_from = Auth::user()->id;
$message->$user_to = $userTo;
$message->conversation_id = $conID;
$message->message = $message1;
$message->save();
You have a lot more control this way, i.e
if($message->save()) { ... }
Or you could wrap the whole thing in a transaction?
Be sure your Message model allows the fields that you want to add in the $fillable array
Create method check fillable attributes into Laravel model. You have to write your all columns into fillable and then use create method.
Second solution is use Active Record technique. #Devin Greay answer is helpful to use Active record.
More information visit https://laravel.com/docs/5.6/eloquent#mass-assignment
I do request to Model:
$user = User::findOrFail($id)->get();
And afetr try to except some fields from $user collection:
$user = $user->except(['surname', 'is_buyer', 'password']);
But in result I get still full $user collection
The problem here is that you don't have here collection as you expect. You have here collection of models, so you will get all model fields. Also using:
$user = User::findOrFail($id)->get();
is really strange, as you will get always 1 record and put this into collection.
Depending on your needs you might want to choose only some fields from database like this:
$user = User::select('id', 'name')->findOrFail($id);
instead of using collections here.
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);