How to limit access from pivot table? Laravel - laravel

I have tables:
user
id
name
companies
id
name
company_user
company_id
user_id
Tables has Many To Many relationships.
As it complicated relationship for me, I can't find way how to make this limit, when user can see companies that was created by this user. (probably not well experienced)
Now I have this, but user can see any company
CompanyController:
public function show($company_id)
{
$company = Company::where('id', $company_id)->firstOrFail();
return view('company.settings', compact('company'));
}
So tip me please how to make user can see only companies created by this user.

You can do this:
public function show($company_id)
{
$company = auth()->user()->companies()->findOrFail($company_id);
return view('company.settings', compact('company'));
}
It will scope the company to the currently logged in user (through the many-to-many relationship on the User model). If none is found, it will return 404.

Since it many to many relation, you can map one company to many users, also map one user to many companies. Check if you have not mistakenly assign the company to many user
Also the above code can be written the way
public function show($company_id)
{
$company = Company::findOrFail($company_id);
return view('company.settings', compact('company'));
}

Related

laravel Many Records to One single record....but how?

I have two tables, one is Users and the other is Loans. These have one to many relationship between them. One user can have many loans and one loan belongs to one User.
Now I want to get the user from the list of loans.
Loan::where('user_id', $user)->get()
This give me repeated array of sample user associated to the multiple loans. But I want to get only a single record, like many loans associate to one user.
I assume you already set up relationships between User & Loan Models
// App\User
public function loans() {
return $this->hasMany('App\Loan');
}
// App\Loan
public function user() {
return $this->belongsTo('App\User');
}
Get user from the list of loans
$user = Loan::where('user_id', $id)->first()->user;
// eager loading version
$loansWithUsers = Loan::with('user')->where('user_id', $id)->get();
Loans associate to one user
$loans = User::findOrFail($id)->loans;
// eager loading version
$userWithLoans = User::with('loans')->findOrFail($id);
For what I understand in your question, you want to get the user together with it's loan right ? Your query should like this.
$user_loans = User::with('loans')->where('id', $user_id)->get();
Get the user informations from loan table
Loan::where('user_id', $user_id)->with('user')->get()
Ge the users from loans table depends on brach id
Loan::where('branch_id', $branch_id)->with('user')->get();

Eloquent relationship for multiple table

I am working in laravel5.4. I have created four table as ticket, users, and company. Here, I have stored users id in ticket table. And stored company id in users table.
Here, I want to show ticket's user name with that users company name.
Here, I have create relation for it that looks like below.
Ticket model :
public function requesters(){
return $this->belongsTo('App\User','requester_id');
}
Here requester_id is who create ticket.
Users model :
public function company()
{
return $this->belongsTo('App\Models\Admin\Company');
}
Company model :
public function Users()
{
return $this->hasOne('App\Users');
}
Here, I have written query to get users information that looks like below.
Ticket::with('requesters')->orderBy('subject','asc')->paginate(10);
Now, I want to fetch company information or request_id So what changes should I have to do in this query to fetch company info along with ticket and users ?
If you want to to Eager load multiple relationship you can put them all in single with like this:
Ticket::with('requesters','requesters.company')->orderBy('subject','asc')->paginate(10);
but if you load nested relationship you can use shorter notation - you can omit parent relationship, so it's enough to use here:
Ticket::with('requesters.company')->orderBy('subject','asc')->paginate(10);
Try this, it should work for this case:
Ticket::with('requesters')
->with('requesters.company')
->orderBy('subject','asc')->paginate(10);

Laravel relationship between two tables

I'd like your input on this.
I have a Customer_table with a field name. I have another table called Reservation_table with a Customer_name field.
How can I relate them in such a way that I'd see all the bookings by the specific customer?
In Reservation_table you should have a field(foreign key) userid in order ta have a user for each reservation.
You can using primary key - foreign key relationship to relate/join those two tables. Also, instead of having a 'Customer_name' field as your FK referring to 'name' field in 'Customer_table' table, it is better to have an id (unique) generated for each customer; This way you can have an efficient way of uniquely identifying and relating customer across tables; can save space on Database side as well. Hope this helps!
If you want to use eloquent you must first define a relationship.
One reservation belongs to a user. Here is how to define the relationships:
Inside the Reservation model:
public function user()
{
return $this->belongsTo('App/User'); //User model
}
To define the inverse you do the following:
Inside User model:
public function reservations()
{
return $this->hasMany('App/Reservation'); // Reservation Model
}
Now you can do the following in your controller:
$reservations = Auth::user()->reservations;
Now you have all reservations by the currently logged in user.
I am not sure if I got the question right so ask away.

Has-Many-Through Relations

I have done a lot of research in Google about this. There are not a good examples with using this type of relation between models.
Can somebody share own sample using Has-Many-Through Relations in Laravel?
Let's take a sample of a social network where you have User, their Friends and their friends' Photos. 3 models. yep a friend is just a normal user but for this example, a Friend would be a separate Model.
1- A user has friends
public function friends() {
return $this->hasMany(Friend::class);
}
2 - A friend has photos
public function photos() {
return $this->hasMany(Photo::class);
}
3 - You are the admin. you have many users, including John. John has a lot a friends. So sometimes, you want to see John's friends photos, maybe those where they tag him. So in user you define the relationship
public function friendsPhotos() {
return $this->hasManyThrough(Friend::class, Photo::class); //could add a scope here for picture with tags only.
}
Not problably the best example. But it shows how you can see all John's friends pictures by just doing
$john = User::where('email', 'john#email.com')->first();
$john->friendsPhotos();
If the example doesnt suit you well, now think of a bank looking for their best salesperson in a specific Branch. A Branch hasMany Salesperson, and each Salesperson hasMany Customers they deal with.
In Branch model, you define
public function customers() {
return $this->hasManyThrough(Salesperson::class, Customer::class);
}
I hope this helps a little bit.
Database tables for the banking system
1- Branch
id
name
...
2 - Salesperson
id
branch_id
firstname
...
3 - Customer
id
salesperson_id
firstname
...

Laravel user management

In Laravel we can manage Users and Permissions easly but i've a problem with my application.
In my application a User is attached to One or Many department.
But a User can have different Role/Permission between departments. That is the problem. In the department One he can have a Admin Role and in the department Two he can only have a User Role. When the User switch between department i would like that his Role can be update.
How i can manage this in Laravel and Eloquent ?
Thank you for your help.
Jeffrey
Without seeing any of your code, I am forced to be fairly generic here. But here is the basic concept.
Architecture
Assuming you have tables like departments, users, roles, and permissions already, all you would need next is define a joining table. Something like this:
department_role_user
department_id // for this department
role_id // this role is assigned to
user_id // this user
Authorization
Define something like a hasPermissionTo() method on your User model.
Definition
class User
{
public function hasPermissionTo($action, $department)
{
// first get permission
$permission = Permission::where('action', $action)->first();
// get all roles which have this permission
$roles = $permission->roles;
return DB::table('department_role_user')
->where('user_id', $this->id) // current user
->where('department_id', $department->id) // the dept
->whereIn('role_id', $roles->pluck('id')) // any of the roles
->exists();
}
}
Usage
And use it like so.
if ($user->hasPermissionTo('do-something', $someDept)) {
// allow action
} else {
// no way
}
This should also work nicely with Laravel's Gates and Policies. Just use your new hasPermissionTo() method inside your gate/policy definitions.

Resources