How to check eloquent relationship between two tables? - php

I have two tables, customers and users in users table I have:
id
name
email
password
in customers I have
id
customer_id
package_id
when someone register, in user table create id number and in the same time it creates in customers table: id and customer_id get the same value from id->user
inside customers model I have
public function owners()
{
return $this->belongsToMany('App\User', 'customers');
}
all I need now just to check after registration if package_id for the current customer_id is empty or null return to.. else if it has any number return to...
I tried this in controller but doesn't work
public function redirectpackage(Request $request)
{
if (Auth::check() && Auth::user()->customer->package_id == 1) {
return view('index.customer.customerpackage');
}
else{
return view('index.customer.customerabout');
}
}

If customers.customer_id is a foreign key that references users.id, then:
A customer can only have one user ("belongs to").
But a user can have many customers ("has many").
So, inside owners() replace belongsToMany() with belongsTo():
public function owners()
{
return $this->belongsTo('App\User', 'customer_id');
}
And inside the User model, add a relationship to the Customer model:
class User extends Model
{
public function customers()
{
return $this->hasMany('App\Customer', 'customer_id');
}
}
Now you can check if a user has a given package_id in the customers() relationship:
Auth::user()->customers()->where('package_id', 1)->count();
Alternatively, you can use isEmpty() instead of count().

Related

show data from 2 tables laravel 6

I have a problem showing data from 2 tables with an id, in laravel 6. My tables are "users" and "companies".
users
id
name
last name
companies
id
company
address
id_user
Model user
public function company()
{
return $this->hasOne('App\Company','id_user','id');
}
Model company
public function user()
{
return $this->belongsTo('App\User');
}
Controller
public function show($id)
{
$companies = Company::with('user')->find($id);
return view('clients.show', compact('companies'));
}
view
$companies->company
but the problem is that is not showing data from users table, can someone help me?
The foreign key name for user in companies table should be 'user_id' not 'id_user'
If you want to use custom column name make sure you pass it to the second argument of the relationship.
Model company:
public function user()
{
return $this->belongsTo('App\User', 'id_user');
}

Laravel 5.4 Query DB with pivot table

So, I have the following Tables named:
ALBUMS(id, name, shared, group_id, user_id)
GROUPS(id, name, user_id)
GROUP_USER(group_id, user_id)
What I want to do is, using Laravel Eloquent to get the results of a query by checking if the AUTHENTICATED user is a member of the GROUP owned by the ALBUM.
Album Model:
public function groupSecurity()
{
return $this->belongsTo(Group::class, 'group_id');
}
Group Model:
public function ownedBy()
{
return $this->belongsTo(User::class, 'user_id');
}
public function members()
{
return $this->belongsToMany(User::class, 'group_user');
}
Thank you for your help :)
You can do like this:
$album = Album::whereHas('groupSecurity', function ($query) {
$query->whereHas('members', function($query2){
$query2->where('user_id', auth()->user()->id);
})->where('user_id', auth()->user()->id);
})->first();
So you search for one album that has a groupSecurity which has in his members the auth user and also it's owned by the auth user.
If a record match this conditions $album will have an instance of Album model, if not it will be null so you can do:
if($album){
// AUTHENTICATED user is a member of the GROUP owned by the ALBUM
}

Laravel foreign key relation

I've got a strange problem.
I've a users table and a company table. A User belongsTo a company and a company hasMany users.
Both primary keys of the table are id.
In the laravel documentation I read the following:
Additionally, Eloquent assumes that the foreign key should have a
value matching the id column of the parent.
I've got this in my CompanyModel:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class);
}
When I try this:
$users = CompanyModel::find(1)->users;
dd($users);
It's not working. When I add a foreign key in my relation it works!?:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class, 'id');
}
This is strange right? What on earth am I doing wrong.
--EDIT--
In my users table I've got a company_id column!
Firstly, I would suggest you rename your Model from CompanyModelto Company and from UserModel to User.
Then ensure you have company_id in your users table. And in your users migration file connect the users table with the companies table as such:
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
Don't forget to refresh your database.
Then in your models, define the relationships as such:
// User model
// Laravel will automatically identify and use the `company_id` field in your reference
public function company(){
return $this->belongsTo(Company::class);
}
// Company model
public function users(){
return $this->hasMany(User::class);
}
You can then fetch your records in your controller as such:
$user = User::find(1);
$user_company = $user->company; // This might not be necessary in your controller, you can do it in your view
dd($users, $user_company);

Laravel 5 eloquent include the row of the other table from the foreign key of the 2nd joined table

I have 3 sample models
customer
id
order
id
customer_id
deliver_address_id
customer_address
id
customer_id
street
country
A customer can save many addresses on his profile but he can only choose one address per order.
I would like to get all customer orders including the address in one query using laravel 5 eloquent. I'm new in laravel so having difficulty to query complex relationship tables.
class Customer extends Model {
$table = 'customers';
function addresses(){
return $this->hasMany(Address::class, 'customer_id');
}
function orders(){
return $this->hasMany(Order::class, 'customer_id');
}
}
class Order extends Model {
$table = 'orders';
function address(){
return $this->belongsTo(Address::class, 'address_id');
}
function customer() {
return $this->belongsTo(Customer::class, 'customer_id');
}
}
class Address extends Model{
$table = 'customer_addresses';
function customer(){
return $this->belongsTo(Customer::class, 'customer_id');
}
}
TABLES :
1 customers
id
2 orders
id
customer_id
address_id
3 customer_addresses
id
customer_id
street
country

Laravel Eloquent Relationship custom query

I have 2 tables: USERS and SUBJECTS
The relationship between USER and SUBJECT is many to many.
In the User.php and Subject.php models, I defined:
User.php
function subjects() { return $this->belongsToMany('App\User'); }
Subject.php
function users() { return $this->belongsToMany('App\Subject'); }
The pivot table is subject_user and it has 3 columns:
subject_id, user_id, finished
The finished value can only be between 0 and 1.
Now I know that when I want to select all the subjects that an user studied, I have to write $user->subjects.
But what if I want to select all the subjects that an user studied and the finished value in the pivot table is equal to 1?
You need to add "withPivot()" to your relationship definitions, like this:
function subjects() { return $this->belongsToMany('App\User')->withPivot('finished'); }
function users() { return $this->belongsToMany('App\Subject')->withPivot('finished'); }
Then you can do:
$user->subjects()->where('finished', 1)->get();
You will need to eager load that relationship and use the wherePivot method.
$user = User::with(['subjects' => function($q) {
$q->wherePivot('finished', 1);
}])->fine($user_id);

Categories