I have model user and user_data. I want to take some data from user and user data. My code looks like:
User model:
public function user_data()
{
return $this->hasMany('App\Models\UserData', 'user_id');
}
public function getUserById($id)
{
$user = User::findOrFail($id);
return $user;
}
UserData model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
User controller
public function getUser($id)
{
//$user = $this->model->getUserById($id);
$user = User::with('user_data')->find(3);
dd($user->sex);
return view('user', compact('user'));
}
How I can get data from two tables? When i dump sex i get null, but I have it in db.
you have to add also the local key in the relationship like this
public function user_data()
{
return $this->hasMany('App\Models\UserData', 'user_id','your local key');
}
$user = User::with('user_data')->where('id',$id)->first(); // Get the data like this
After that you can check what is it in like this
$user->user_data[0]->sex // Not $user->sex
If it's not working try to swap the foreign key and local key places.
Also you have to take the data like this
Related
I have 4 table : Users, CompanyRegister, VoucherDetails, Addvoucher.
So the Authenticate Users Id will be submit as user_id in companyRegister table,and then companyRegister ID will be submit as company_id in Voucherdetails table, and lastly voucherDetails Id will be submit in addVoucher table as voucher_ID. I am new to using eloquent and also laravel, I cant understand why I cant get the id from voucherdetails and submit in addvoucher but I can get id from companyregister and submit in company_id in voucherdetails. I'm using the same method to get id but not work, I hope can get solution and explanation here,Thank you in advance!!
My users model
public function companyregisters()
{
return $this->hasOne('App\companyregisters');
}
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
public function addvoucher()
{
return $this->hasMany('App\addvoucher');
}
public function roles()
{
return $this->belongsToMany('App\role');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
my companyregister model
public function User(){
return $this->belongsTo('App\User');
}
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
my voucherdetails model
public function User(){
return $this->belongsTo('User');
}
public function companyregisters(){
return $this->belongsTo('App\companyregisters');
}
public function addvoucher()
{
return $this->hasOne('App\addvoucher');
}
my addvoucher model
public function User(){
return $this->belongsTo('App\User');
}
public function voucherdetails(){
return $this->belongsTo('App\voucherdetails');
}
my voucherdetailsController
public function store(Request $request){
$voucherdetail = new voucherdetails();
$voucherdetail->title = $request->input('title');
$voucherdetail->description = $request->input('description');
$voucherdetail->user_id = Auth::user()->id;
$id = Auth::user()->id;
$user = User::find($id);
$company = $user->companyregisters;
$companyId = $company->id;
$voucherdetail->company_id = $companyId;
$voucherdetail->save();
return redirect()->to('addvoucher');
}
my addvoucherController
public function store(Request $request){
$addvoucher = new addvoucher();
$addvoucher->voucherTitle = $request->input('voucherTitle');
$addvoucher->voucherCode = $request->input('voucherCode');
$addvoucher->user_id = Auth::user()->id;
//Here(the voucherdetails id cant get to submit in voucher_id)
$id = Auth::user()->id;
$user = User::find($id);
$voucher = $user->voucherdetails;
$voucherID = $voucher->id;
$addvoucher->voucher_id = $voucherID;
$addvoucher->save();
return redirect()->to('displayVouchers');
}
This code works because companyregisters is a hasOne relationship for which the docs say:
Once the relationship is defined, we may retrieve the related record
using Eloquent's dynamic properties.
public function companyregisters()
{
return $this->hasOne('App\companyregisters');
}
$company = $user->companyregisters; // ie this returns the single related record
$companyId = $company->id; // and it has an `id` property, all good here
However, this code fails because voucherdetails is a hasMany relationship for which the docs say:
Once the relationship has been defined, we can access the "collection"
of comments by accessing the comments property.
More info on collections
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
$voucher = $user->voucherdetails; // ie this returns a "collection" of related records
$voucherID = $voucher->id; // this "collection" does NOT have an id property, but each record IN the collection does.
In summary, either your relationship is defined incorrectly (hasMany vs hasOne) or, you'll need to loop over the related records to get the id from each.
I have 3 tables:
User
- id
- email
UserAccount
- id
- user_id
- account_id
Account
- id
- user_id
Verification
- id
- user_id
- guid
I am trying to achieve a post whenever I try to add a user, it will automatically add an account with empty fields but with user_id in it, Verification table with user_id also, at the same time once the Account has been created it should also record UserAccount user_id and account_id but I ended up this error using many to many relationship belongsToMany and sync. How do I add the acct_id and user_id with eloquent?
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acct_id' cannot be null (SQL: insert into `user_accounts` (`acct_id`, `user_id`) values (?, 17))
This is what I've tried so far.
Controller.php
$user = new User();
$user->name = "Not set";
$user->email = $email;
$user->password = NULL;
$user->save();
$accounts = new Account();
$accounts->email = $email;
$user->account()->save($accounts);
$userAccount = new UserAccount();
$userAccount->userAccount()->sync([
$user->id,
$accounts->id
]);
User.php
public function account()
{
return $this->hasMany(Account::class);
}
public function userAccount()
{
return $this->belongsToMany(User::class, UserAccount::class, 'user_id', 'id');
}
UserACcount.php
public function user()
{
return $this->hasMany(User::class, 'user_id', 'id');
}
public function account()
{
return $this->hasMany(Account::class, 'acct_id', 'id');
}
public function userAccount()
{
return $this->belongsToMany(Account::class, UserAccount::class, 'acct_id', 'user_id');
}
Verification.php
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Account.php
public function user()
{
return $this->hasMany(User::class);
}
public function userAccount()
{
return $this->belongsTo(UserAccount::class);
}
I tried using this functionality and completely works fine but pretty sure this is how it works with eloquent.
$userAcct = new UserAccount();
$userAcct->create([
'user_id' => $user->id,
'acct_id' => $accounts->id
]);
Any thoughts?
I also have did found this related problem (Laravel hasManyThrough)
First of all, you should remove user_id from the account table because it is already referenced by user_account which links both tables. Moreover, if you wanna take advantages of Eloquent conventions which allow it to guess table names and fields, you should make sure your tables are named users, accounts, verifications and account_user.
User.php
public function accounts()
{
return $this->belongsToMany(Account::class);
}
Account.php
public function users()
{
return $this->belongsToMany(User::class);
}
The UserAccount model is useless if account_user exists only to links 2 tables.
Then, you may use an observer to get an event-based approach: whenever an user is created => do something
https://laravel.com/docs/5.8/eloquent#observers
<?php
namespace App\Observers;
use App\Account;
use App\Verification;
class UserObserver
{
/**
* Handle the User "created" event.
*
* #param \App\User $user
* #return void
*/
public function created(User $user)
{
(new Verification)->user()->associate($user);
$account = new Account;
$account->save();
$user->accounts()->attach([
$account->id
]);
}
}
// Post Model
public function user()
{
return $this->belongsTo('App\User');
}
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
public function tags()
{
return $this->belongsToMany('App\Tag')->withTimestamps();
}
//User Model
public function posts()
{
return $this->hasMany('App\Post');
}
//Category Model
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
//Tag Model
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
I'm trying to retrieve a group of post IDs from my likes table where the user ID is equal to the ID stored in the Auth Session.
So far I have tested retrieving data in multiple ways, if I select all the likes from the table it works fine, the auth ID retrieved from the session is the same as the one stored in the likes table so should produce a match and return data.
Here's the code I'm currently working with:
public function index()
{
$userid = Auth::id();
$userLikes = likes::all()->pluck('post_id')->where('user_id', $userid);
dd($userLikes);
}
The columns names within the table are as follows:
id
created_at
updated_at
user_id
post_id
I have tried this method of writing the query however am experiencing the same issue, no errors and no data.
DB::table('likes')->pluck('post_id')->where('user_id', $userid)->toArray();
I am looking to have an array of post ids for the posts liked by the logged in user so that it can be passed into the view.
Thanks in Advance
If you've created User, Post, and Like models with the appropriate relationships, you can do the following:
$ids = auth()->user()->likes->pluck('post_id')->toArray();
The model's would have relations defined as:
// User.php
public function likes()
{
return $this->hasMany(Like::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
// Like.php
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
// Post.php
public function user()
{
return $this->belongsTo(User::class);
}
public function likes()
{
return $this->hasMany(Like::class);
}
Alternatively, using the query builder:
DB::table('likes')->where('user_id', auth()->id())->get('post_id')->toArray();
In my destroy function of my controller, I'm attempting to take a copy of my object (model with one relationship) and insert it into another database before deleting it. However only the model is being created and not the relationship. Why is this happening?
Destroy function:
public function destroy($id)
{
$user = User::with('Phone')->find($id);
$archive = $user->replicate();
$archive ->changeConnection('mysql2');
$archive ->push();
}
User model:
public function phone()
{
return $this->hasOne('App\Phone');
}
Phone model:
public function user()
{
return $this->belongsTo('App\User');
}
When I insert via the store function in my controller, it sets up the relationship just fine:
public function store(Request $request)
{
// Validation has passed, insert data into database
$user= User::create($request->all());
$user->Phone()->create($request->all());
}
Hey how can I make relationships between two table.
Users: id, email
Notification: id, user_id(id of the logged user), client_id(id of sender)
I would like make relationship between users and notifications by user_id and client_id.
Then I will can get all notifications assigned to logged user, and get email of sender users.
I made that:
public function notifications_with_client() {
return $this->hasManyThrough('App\Models\User', 'App\Models\Notification', 'user_id', 'id', 'client_id');
}
But when I using query i got good notifications but with wrong email.
I got email from ralationship id(from users table) == id(from notifications table)
My query
$column = 'notifications_with_client';
$value[1] = ['email', 'notifications.id', 'client_id'];
$query->with([$column => function($query) use ($value) {
$query->select($value[1]);
}]);
Someone know what I do wrong?
You can try it by defining the following relations:
User Model
public function notifications()
{
return $this->hasMany('App\Models\Notification');
}
Notification Model
public function to()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function from()
{
return $this->belongsTo('App\Models\User', 'client_id');
}
And then you can query it as:
$notifications = auth()->user()->notifications()->with('from')->get();
Or if you just want email then query it as:
$notifications = auth()->user()
->notifications()
->with(['from' => function($q) {
$q->select('email');
}])
->get();
public function user()
{
return $this->belongsTo(Users::class, 'user_id');
}
public function client()
{
return $this->belongsTo(Users::class, 'client_id');
}
With this code in your Notification Model you can get the logged user with
$this->user(); // $notification->user();
and the sender with
$this->client(); //$notification->client();
You cannot use $this->hasManyThrough(). It use for a different reason
You can use $this->belongsTo() like this.
class User extends BaseModel
{
public function user()
{
return $this->belongsTo(Notification::class, 'user_id');
}
public function client()
{
return $this->belongsTo(Notification::class, 'client_id');
}
}
Then you can query like.
User::with(['user']);
or
User::with(['client']);