Laravel Auth::user relationship - laravel

In Laravel, i´m trying to show relation elements between Auth::user (Users) and Departments. In User table i have id, name, and department_id. In Departments table I have id and name.
In user model i create
public function department()
{
return $this->belongsTo('App\Models\Department');
}
Then, in blade template I try
Auth::user()->department
But return null and doesn´t show linked departments. Null is incorrect, all users have departments. Soo, ¿Any help? ¿What´s wrong in relation?

You can try this User::with('departmento')->find(Auth::id());

This method uses less queries - the others go after the user table twice:
auth()->user()->load(['department']);

You should add 'department_id' as a second parameter ($foreignKey) when calling belongsTo method, because it will searching for departmento_id by default.
public function departamento()
{
return $this->belongsTo('App\Models\Departamento', 'department_id');
}
Or just rename User::departamento() method to User::department()
public function department()
{
return $this->belongsTo('App\Models\Departamento');
}

Relation works with Model. Auth uses the session it not uses relation
Use User Model instead
optional(User::find(Auth::id())->departmento)->department_name

Related

Laravel Create multiple records in Pivot table

I'm trying to create a function in our Laravel 5.8 app that would add multiple records to a pivot table. At present we have the following setup;
Users
Training Courses
Users Training Courses (pivot table for the above relationships, with a few extra fields)
I want to be able to show all users in the database, then check their name, pick a training course and hit "Add" and it'll create a record in the pivot table for each user that was selected.
I can't figure out where to start with this - it seems like I need to have a "for each user selected, run the store function" loop in the controller, but I have no idea where to start.
I wasn't sure if there was an easy way to do this in eloquent or not. Is there a simple way to do this?
Eloquent does this automatically if you set up the relationships correctly and you don't have to worry about pivot tables.
class Users
{
public function trainingCourses()
{
return $this->hasMany(TrainingCourses::class);
}
}
class TrainingCourses
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Then you can use the save() method to create the relationship. But I find it better to wrap this function inside a helper method that you can use throughout your code:
class Users
{
...
public function assignTrainingCourse(TrainingCourse $trainingCourse)
{
return $this->trainingCourses()->save($trainingCourse);
}
}
In your code, you could then do something as simple as this:
$user = User::find(1);
$trainingCourse = TrainingCourse::find(1);
$user->assignTrainingCourse($trainingCourse);
Building on this, suppose you have the following route to assign a training course, where it expects a trainingcourse_id in the request:
Route::post('/users/{user}/trainingcourses', 'UserTrainingCoursesController#store');
Thanks to route model binding, Laravel can inference the parent model (user) from the URL, and your controller might look like this:
// UserTrainingCoursesController.php
public function store(User $user)
{
$trainingCourse = TrainingCourse::find(request()->input('trainingcourse_id'));
$user->assignTrainingCourse($trainingCourse);
return back();
}
Of course, you'll want to put some validation in here, but this should get you started.

Selecting specific column in ORM relationship Laravel 5.5

I have an order table with a primary key id and another table trips. I trip can have many orders. I have defined the relationship in this way
public function orders_currency() {
return $this->hasMany('App\Order', 'trip_id', 'id')->select('id', 'converted_currency_code');
}
Although I know that, I have to select id of the order table in order to get the result, that's why I am mentioning to select the id of the order table.
Despite this, I am getting the orders_currency index empty. Which angle am I missing in this case?
Any clue will be appreciated.
Did you set up the model correctly?
You'd do something like this in your model script I suppose
class Trips extends Model
{
public function orders() {
return $this->hasMany('Order');
}
I got the solution by doing this way
public function orders_currency() {
return $this->hasOne('App\Order', 'trip_id', 'id')
->select('trip_id','converted_currency_code');
}
I had to select referencing key in this case.

Call to undefined relationship in laravel

I have two tables departments and course, and I have defined a relationship between them but I received this error message:
Call to undefined relationship in laravel
Can anyone tell me please where's the problem?
Model Code:
public function course()
{
return $this->hasMany('App\Course','departments_id','id');
}
Model Department:
public function department()
{
return $this->belongsTo('App\Departments','departments_id');
}
So problem is so clear. Either in your Course model you have to rename the function department to departments, or to make a new one with the correct name.
First of all little correction in schema $table->integer('department_id'); should be $table->unsignedInteger('department_id');
And the problem is - in your migration column name is department_id but in your relation you have written departments_id there is a extra S!
just correct the column name from model.
in my case, i used:
::with('boards')
i just changed it to :
::with(['boards'])
with brackets
in my department Model:
public function boards()
{
return $this->hasMany(Board::class);
}

How to check and get the result if the table contain user id in laravel

I have create a relationship between user and table column, I want show the table list which is belongs to particular user. For example if user_id 1 is logged in the system, the system will only show the information belong to him which is Table 1.
This is my controller code :
public function show(Request $request){
$user_id=Auth::user()->id;
$table= Roundtable::findOrFail($user_id);
return view('users.tables.show')->withTables($table);
}
I know that $table= Roundtable::findOrFail($user_id); is incorrect but I had no idea how to do because I am new for laravel.
If user has just one table and if Roundtable model has user_id you can use this query:
Roundtable::where('user_id', $id)->first();
It will give you user's table or null if table doesn't exist.
Another way to get table is to use relation:
auth()->user()->roundTable;
Well i found the solution, just need to change the code into
$id=Auth::user()->id;
$table= Roundtable::where('user_id',$id)->get();
return view('users.tables.show')->withTables($table);
then the result will return correctly.

Eloquent custom relation return type error

I'm having some troubles with a custom relation.
I want $user->sites to return every site $user got access to. It's a belongsToMany relationship, with a pivot table 'user_site'. The problem is, when $user is an admin, he has access to every site in the database, and I can't manage to get it to work with Eloquent.
public function sites() {
if( $this->is_super_user )
return Site::whereNotNull('deleted_at');
return $this->belongsToMany('Site', 'user_site');
}
This is what I got, but it isn't working (Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation).
I could just return Site::all() and $this->belongsToMany('Site', 'user_site)->get(), but I want to be able to use the dynamic property ($user->sites) and to filter the result ($user->sites()->where...)
Am I missing something ?

Resources