Laravel 5.4 Auth::User() with relationship not working - php

I have Table Vendors (for test Auth relationship) and Table Vendor_users,
But i use Auth::user() it not relationship
And This Database
In Vendor model
protected $table = 'vendor_users';
public function Vendor_test(){
return $this->belongsTo(Vendor_test::class);
}
And Vendor_test model
protected $table = 'vendors';
public function Vendor(){
return $this->hasMany(Vendor::class);
}

from chat and your current table structure, you should have relation like this
in Vendor Model
public function vendor_contact()
{
return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id');
}
in Vendor_contact Model
protected $primaryKey = 'vendContactId'; //check this
public function vendor()
{
return $this->hasOne(Vendor::class, 'vendor_contact_id');
}
Now use lazy eager loading for loading vendor_contact relationship
Auth::user()->load('vendor_contact');
dd(Auth::user());

As per the discussion and the table structure you have,
Add the relation function in your model vendor_users.
protected $table = 'vendor_users';
public function vendor_contact()
{
return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id');
}
get the user with the vendor_contact and check
$user = Auth::user()->with('vendor_contact')->first(); // As you asked with for auth
//OR
$user = Auth::user()->load('vendor_contact'); // From the rkj answer as I found this good.
// OR
$user = Vendor::find(1)->with('vendor_contact')->first();
dd($user);

Related

Sort belongsToMany relation base on field in belongTo relation Laravel Eloquent

I have a scenario where User has a belongsToMany relation with PortalBreakdown, PortalBreakdown has a belongsTo relation with Portal. Portal has order column in it. I have a method listing_quota($id) in UserController which returns all breakdowns of the user. I want to sort these breakdowns based on order column of the portal. Below are the code of classes and a method I have tried.
class User extends Model {
protected $table = 'user';
public function listing_quota() {
return $this->belongsToMany('App\PortalBreakdown', 'user_listing_quota')->withPivot(['quota']);
}
}
class PortalBreakdown extends Model {
protected $table = 'portal_breakdown';
public function portal() {
return $this->belongsTo('App\Portal');
}
}
class Portal extends Model {
protected $table = "portal";
protected $fillable = ['name', 'description', 'order'];
}
Below is the method where I am trying to return sorted by order. I tried few things some of which can be seen in commented code but not working.
class UserController extends Controller {
public function listing_quota($id)
{
$user = User::with(['listing_quota' => function ($query) use ($id) {
// $query->sortBy(function ($query) {
// return $query->portal->order;
// });
}, 'listing_quota.portal:id,name,order'])->findOrFail($id);
// $user = User::with(['listing_quota.portal' => function ($q) {
// $q->select(['id', 'name',order']);
// $q->orderBy('order');
// }])->findOrFail($id);
return $this->success($user->listing_quota);
}
}
I also tried chaining orderBy directly after relation in Model class but that's also not working from me. Thank you in advance.
NOTE: I am using Laravel Framework Lumen (5.7.8) (Laravel Components 5.7.*)

Laravel whereRelation with another database connection

I am just using Laravel whereRelation. It runs smooth and as expected if the relations between 2 tables is in the same database (DB_A). The problem is when I have to use 2 databases (DB_A and DB_B). In the model relationship I put the connections and there is no problem
// Model user DB_A
protected $connection = 'mysql';
public function address()
{
return $this->hasOne(Address::class, 'id_user');
}
// Model address DB_B
protected $connection = 'mysql2';
protected $table = 'address';
public function user()
{
return $this->belongsTo(User::class, 'id_user');
}
In the query I want to get all the relationship between those 2 tables. The query like:
$data = User::with('address')->reorder('id', 'desc');
$data = $data->whereRelation('address', 'status', '=', 'verified');
I got the error say that table address doesn't exist in DB_A which is belong to DB_B. If i remove the line whereRelation takeplace it doesn't give any errors. How to handle or specify the database name and table name in whereRelation?
EDIT: Both DB_A and DB_B is in different Host.
Try it will hopefully work
Model address DB_B
class User extends Eloquent {
// *******default connection************
public function address() {
return $this->setConnection('mysql')->belongsTo(Address::class, 'id_user');
}
}
Model address DB_B
class Address extends Eloquent {
// *******default connection************
public function user() {
return $this->setConnection('mysql2')->belongsTo(User::class, 'id_user');
}
}

Laravel Pagination not working after setConnection() on eloquent model

I have tried to create a model in Laravel 8.x that can use different databases (Dynamically). It is currently working by setting the connection after creating an instance of the model, using Laravels build-in "setConnection" function. However, pagination on the model is not working. I get the following error:
(PDOException(code: 42S02): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.times' doesn't exist
The problem is that the "test" database, is not the one I am currently telling the model to connect to. I am connectin to 'mysql_timer'. Is pagination reseting the DB connection to default or?
You can see my controller code here:
public function getStats(Request $request)
{
$query = new Time;
$query->setConnection('mysql_timer');
$query = $query->with(['user']);
$data = $query->paginate($length);
dd($data);
}
And my "Time" model:
class Time extends Model
{
use HasFactory;
protected $table = 'times';
public $timestamps = false;
protected $primaryKey = 'uid';
protected $fillable = [
'uid',
'mapid',
'runid',
'mode',
'style',
'rectime',
'recdate',
'strf_num',
'jump_num'
];
public function user()
{
return $this->hasOne(User::class, 'uid', 'uid');
}
}
You can use on($connection) to begin querying the model on a given connection:
$data = Time::on('mysql_timer')->with(['user'])->paginate($length);
public function getStats(Request $request)
{
$query = DB::table("mysql_timer.times as times)
->join("users", "users.id", "=", "times.user_id")
->paginate($length);
dd($query);
}
did u try like that?
First make model
php artisan make:time
After go model
protected $connection = "mysql_timer";
protected $table = "times";
protected $guarded = [];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
After go controller
$query = Time::query()->with("user")->paginate($length);
dd($query);

Obtaining a list of non-linked models, in many_to_many relations, using Laravel Eloquent

I have a User-Roles model, using Laravel 4 where a user can have many roles, using Eloquent. I can access all roles linked to a user easily using this code :
class User extends Model {
protected $table = 'user';
protected $fillable = array('name');
public function rolesLinked() {
return $this->hasMany('App\UserRoleLink', 'user_id');
}
}
I've been trying to obtain the roles that are not linked to a user, to display on the specific user's page in a select box. Using this function, included in the User class.
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('App\UserRoleLink',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
The problem is, calling this function gives me the following error.
Call to undefined method Illuminate\Database\Query\Builder::App\UserRoleLink()
I've tried using has with < 1 to see if the function was problematic, but after reading this and the online source code, the function call pretty much does what I've tried.
Is something wrong in my function call, or have I messed up configurations somewhere?
For reference, here are my other Model classes:
class UserRoleLink extends Model{
protected $table = 'user_role_link';
protected $fillable = array('role_id','user_id);
public function role() {
return $this->hasOne('App\Role', 'role_id');
}
}
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
}
EDIT: I've found out that I messed up by fillables when I copy-pasted. It didn't fix the issue, but I guess that's one step closer.
To use whereDoesntHave method, you must add the relation in your Role Model.
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
public function UserRoles() {
return $this->hasMany('App\UserRoleLink', 'id');
}
}
Also, the whereDoesntHave method first parameter is not thte model but the function of the relation:
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('UserRoles',function($query) use ($user){
$query->where('user_id',$user->id);
});
}

relationship array null when eager loading in laravel

I am having issues getting the relationship array back when eager loading in laravel 4. for example:
controller:
foreach (Apps::with('extra')->get() as $app)
{
print_r($app->toArray());//returns array but my relationship array at the bottom says null
echo $app->extra; //this will show my relationship details
}
model:
class Apps extends Eloquent
{
protected $connection = 'mysql_2';
protected $table = 'apps';
public $timestamps = false;
protected $primaryKey = 'name';
public function host()
{
return $this->belongsTo('Hosts','name');
}
public function extra()
{
$this->primaryKey='app_ip';
return $this->hasone('Extra','ip');
}
//other functions below.......
}
class Extra extends Eloquent
{
protected $connection = 'mysql_3';
protected $table = 'extra';
public $timestamps = false;
protected $primaryKey = 'ip';
public function app(){
return $this->belongsTo('Apps', 'app_ip');
}
mysql:
My mysql tables were not created through laravel they were previously existent. the app_ip column in the Apps table relates to the ip column in the extra table. it is a 1 to 1 relationship and I have specified the primary key in the relationship function. I am getting relationships back so I know that it is working.
I am able to get relationship data back when I call the function directly, but it does not show the relationship data when I try and print the full array. The main goal is to be able to return both the relationship columns and the app columns in one response.
You need to do this:
$apps = Apps::all();
$apps->load('extra');
foreach ($apps as $app)
{
print_r($app->toArray()); // prints your relationship data as well
}
What you have should work and iterating through the collection or using ->load() to eager load shouldn't make a difference. Are you using the visible restriction on your models? If so you will need to include the relationships.
class Apps extends Eloquent {
protected $visible = array(
'id',
'name',
'created_at',
'extra', // Make the relationship 'visible'
);
public function extra()
{
return $this->hasMany('Extra');
}
}

Categories