How to associate comments to users on Laravel? - laravel

public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
$post->addComment(request('body'));
return back();
}
this is my code
I am having this error
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into comments (body, post_id, updated_at, created_at) values (ewrtyuttrew, 1, 2018-02-15 15:44:17, 2018-02-15 15:44:17))

You need to add a user who created the comment manually. For example:
public function addComment(string $body)
{
$this->comments()->create(['body' => $body, 'user_id' => auth()->id()]);
}

In your User model you can define the relationship as:
public function comments() {
return $this->hasMany(Comment::class);
}
So, if the user it's the logged user, then you can retrieve it with the Auth facade:
$user = Auth::user();
Then you can simply do:
$user->comments()->save(new Comment(request('body'));
Note that you must set the "fillable" fields on the Comment model in order to allow the dynamic creation.

Field 'user_id'
Open phpmyadmin and open comments table then after
Field 'user_id' => auto increment and primary key add
Try this I solve this type issues, thanks

Related

how to sync() method additional pivot table Laravel

i have pivot table call user_privilege,
user_id,
privilege_id
house_group_id,
i use method sync for store data into pivot tabl, this is my method
$data = $this->getCollectedData($getListCollectData, $viewType, $data);
$getData = $this->crud->store($data);
$getData->getPrivilege()->sync([
'user_id' => $getData->id,
'house_group_id' => $this->request->get('house_group_id'),
'privilege_id' => 3,
]);
this is my getPrivilege() method in Users Model
public function getPrivilege()
{
return $this->belongsToMany(Privilege::class, 'user_privilege', 'user_id', 'privilege_id', 'house_group_id');
}
but when i click submit, return error like this
SQLSTATE[HY000]: General error: 1364 Field 'house_group_id' doesn't have a default value (SQL: insert into `user_privilege` (`privilege_id`, `user_id`) values (b3f08343-a8f6-4a45-b7bc-b396125634d3, ?))
when i dd($this->request->get('house_group_id')) return ID house_group_id like this
"2539d741-1526-4c42-b57a-da60e2e862d8"
this is UUID from house_group_id,
Whats wrong in My Code, how to save data with addtional pivot table ?
thanks

How to scope results with pivot table October Cms

The solution to this is probably easy and I'm just missing it, but I can't seem to figure out how to limit "customers" based on the "user" that the customer belongs to.
This is a many to many relationship, so a customer can belong to more than one user and a user can have more than one customer.
Here is my relationship definition:
public $belongsToMany = [
'user_id' => [
'RainLab\User\Models\User',
'table' => 'tablename_users_customers',
]
];
And here is the scope function that doesn't work as I'd expect:
public function scopeUser($query) {
$user = Auth::getUser()->id;
return $query->where('user_id', $user)->get();
}
Finally, here is my error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from `tblcustomers` where `user_id` = 1)
Obviously, the error is because the "user_id" column doesn't exist in the 'tblcustomers' table, but rather in the pivot table. How can I use the "user_id" from the pivot table in my scope function? I need to only display Customers that belong to the currently logged in user.
Yes this can be possible
But First thing is you need to remove get() method from the scope, scope meant to return query object for chaining methods further.
Your relation and scope should look like this
// relation
public $belongsToMany = [
// PLEASE MAKE RELATION NAME CORRECT HERE
'users' => [ // not user_id, use `users`
'RainLab\User\Models\User',
'table' => 'tablename_users_customers',
// 'key' => 'customer_id', if needed
// 'otherKey' => 'user_id' if needed
]
];
// scope
use RainLab\User\Models\User;
public function scopeUser($query) {
return $query->whereHas('users', function($usersQuery) {
$user_id = Auth::getUser()->id;
return $usersQuery->where((new User)->getTable() . '.id', $user_id);
});
}
// usage
$result = Customer::user()->get();
dd($result);
// you will get only customers which has relation with current logged in user.
if any doubts please comment.

Error inserting a record using Laravel Cashier and many-to-many relationship

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();

Laravel 5.4 elequent create method generate wrong query

I am trying to insert data in a table using eloquent create method, But data which I have passed not coming in insert query generated by create method. Due to which I am getting a default value error.
Below are the code i have used
Model :
namespace App;
use Illuminate\Database\Eloquent\Model;
class PasswordReset extends Model
{
protected $fillable = ['email', 'token'];
}
Controller :
$content = ['email'=>'test#gmail.com', 'token'=>'1234'];
PasswordReset::create($content);
Error I am getting :
SQLSTATE[HY000]: General error: 1364 Field 'email' doesn't have a default value (SQL: insert into password_resets (updated_at, created_at) values (2018-09-25 16:16:45, 2018-09-25 16:16:45))
Why query in above error does not have 'email' and 'token' fields?
from your comment:
#cbaconnier, Thanks, After looking your comment. I have checked with my code and its having a __construct method without having any code within it and removing this resolve the issue.
If you want to use __construct() on the Model, you need to build it like this
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// your code
}
I think you should create like this
PasswordReset::create([
'email'=>'test#gmail.com',
'token' => '1234'
]);
try this way :
$passwordReset = new PasswordReset();
$passwordReset->email = 'test#gmail.com';
$passwordReset->token = '12345';
$passwordReset->save();
try this i hope work for you :
PasswordReset::create([
'email'=>'test#gmail.com',
'token' => '1234']);

Laravel 5.4 with Entrust: How to get users with roles

I am trying to get all users with roles, but "roles" field is always an empty array.
There are 4 users, 2 of them have at least 1 role attached, verified.
UserController.php
public function getUsers()
{
$users = User::select('name', 'email', 'type')->with('roles')->get();
return view('user.list', ['users' => $users, 'lang' => Lang::getLocale()]);
}
I get the 'roles' field as an empty array, even if I don't use "with->('roles')" in the controller. Weird?
If i print each user role in the view, I get this:
object(Illuminate\Database\Eloquent\Collection)#281 (1) { ["items":protected]=> array(0) { } }
What I am doing wrong?
You have to select also primary key, on which roles are related.
Eloquent is first selecting all users and then based on their IDS (primary and foreign) is selecting relations. If you dont select primary key, he cant relate relations.
$users = User::select('id', 'name', 'email', 'type')->with('roles')->get();
Also, if you want specifi which columns from roles you want, you have to select foreign key too.
$users = User::select('id', 'name', 'email', 'type')->with(['roles' => function ($query) {$query->select('id', 'name', 'user_id');}])->get();

Resources