Best way to check if user 'owns' another user - laravel

I have implemented a system in Laravel where a user can be a manager of multiple 'stores'. A store can have multiple users belonging to that store. Here's my stripped down table structure -
users
id (int)
name (string)
email (string)
user_stores
user_id (int)
store_id (int)
manager (boolean/tinyint)
stores
id (int)
name (string)
My issue is checking who a user with a manager pivot flag can manage. I have a solution but I'm not sure it's optimal. I want the query to be as lean as possible. Here is my current solution -
protected $manageable_users;
public function getManageableUserIds () {
if(!is_array($this->manageable_users)) {
// get our store id's that we manage
$manages = DB::table('user_stores')
->where('user_id', $this->id)
->where('manager', true)
->select('store_id');
// make a join so we can get our data
$this->manageable_users = DB::table('user_stores AS d2')
->joinSub($manages, 'stores', function ($join) {
$join->on('d2.store_id', '=', 'stores.dealership_id');
})->distinct()->pluck('d2.user_id')->toArray();
}
return $this->manageable_users;
}
So what I'm doing here is grabbing an array of all user ID's that the manager can possibly manage. I then store this as a protected variable so that on the same request I can perform this check multiple times within the same request without making multiple queries.
I then have a separate method called canManage which checks if the current user object can actually manage the passed user -
public function canManage(User $user) {
// check if our user is manageable
return in_array($user->id, $this->getManageableUserIds(), true);
}
Now I know Laravel is super smart and for some reason I feel like this isn't the best solution.. plus I don't want it to be too intensive on the database as ultimately there will be a lot of users and stores on this system.
If nothing else, maybe this could be a solution for someone else!
Thanks.

So basically you wanted to build a pivot relation. Here is how you could do it relative to your case:
app/User.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
public $table = 'user';
protected $primaryKey 'id';
protected $foreignKey = 'user_id';
public function stores() {
return $this->belongsToMany('App\Store', 'user_stores', 'user_id', 'store_id')->withPivot('manager');
}
}
?>
app/Store.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Store;
class Store extends Model {
public $table = 'store';
protected $primaryKey 'id';
protected $foreignKey = 'store_id';
public function users() {
return $this->belongsToMany('App\User', 'user_stores', 'store_id', 'user_id')->withPivot('manager');
}
}
?>
Now, let us say you know in advance user with id 4 is a manager, and you want to get all the users this manager can manage.
I will asume we are in a controller because most of the time this is the place where all your business logic is located, so you are browsing route /user/4/store/1, and we will display a list of all the users this user(manager) manages.
I also add the store (1) in the route to make it clear we want all users from this store, because your model does not forbid a manager to manage multiples stores. Right after the version assuming a manager only manages one store.
app/Http/Controllers/UserStoreController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserStoreController extends Controller {
public function show(User $user, Store $store) {
// Grab all the users that are in the store and that are not manager
$managed_users = User::whereHas('stores', function($query) use($store) {
$query->where('manager', false)->where('store_id', $store->id);
})->get();
return view('user.store.index')
->withStore($store)
->withUser($user)
->withManagedUsers($managed_users);
}
}
(Note, accessing a route with an id let us use the power of Model injection, that is why I do not put public function show($user_id, $store_id), because Laravel will automatically use User::find($user_id) and Store::find($store_id) for us).
Version assuming a manager can manage only one store:
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Store;
use App\Http\Controllers\Controller;
class UserController extends Controller {
public function show(User $user) {
// We find the related store
$store = $user->stores->first();
// Same thing, we grab all users that are managed
$managed_users = User::whereHas('stores', function($query) use($store) {
$query->where('manager', false)->where('store_id', $store->id);
})->get();
return view('user.index')
->withUser($user)
->withManagedUsers($managed_users);
}
}
Hope it helps.

Here's a raw SQL solution:
SELECT
a.userid FROM user_stores a
INNER JOIN
user_stores b ON a.store_id = b.store_id
WHERE
a.manager=0 AND b.manager=1;
To convert this to eloquent, might try DB::select and/or DB::raw
Database table views are also worth considering. Then you'd just query your view to get your custom tailored results instead of the table directly. This kind of solution promotes clean code, allows you to continue using the ORM, doesn't require you to resort to running raw SQL in your application and gives you all the speed benefits of having this done as raw SQL. The main down side is having to write such a view and make sure it's maintained. Pretty much the same drawbacks as using triggers.
Another idea is just pull the whole database in one shot through the ORM, then use laravel collections to filter the data. In this case I'd probably reach for reduce. Could also pipeline it with filter or anything else on the list. Sure this is extra looping, but in comparison to the ORM, is it really that bad of a performance trade off?
Finally, it's also worth considering the solution of "whatever works and is most readable" and then simply cache it using, for example, redis.

Related

Laravel relation one to many get results joined

I'm kinda lost one this one, I really can't find the problem, I have been watching a lot of questions all over the web but still can't seem to put this working properly.
I have two tables, the tabelaAngaricao table and the tabelaFotos table with a relationship of one-to-many, meaning that a tabelaAngariacao can have many tabelaFotos, and tabelaFotos as a angariacaoid(foreign key) so my tabelaAngariacao model is:
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\TabelaFotos;
class TabelaAngariacao extends Model
{
protected $table = 'tabelaAngariacao';
public function TabelaFotos()
{
return $this->hasMany(TabelaFotos::class, 'angariacaoid');
}
}
and my tabelaFotos model is:
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\TabelaAngariacao;
class TabelaFotos extends Model
{
protected $table = 'tabelaFotos';
public function TabelaAngariacao()
{
return $this->belongsTo('App\TabelaAngariacao');
}
}
What I want is to get all results joined by the angariacaoid, so in my controller I have:
public function index()
{
$results = DB::table('tabelaAngariacao')
->leftJoin('tabelaFotos', 'tabelaAngariacao.id', '=', 'tabelaFotos.angariacaoid')
->select('tabelaAngariacao.*')
->get();
}
Could someone help me on finding the problem? What is that I'm doing wrong?
You don't need to add select. Try following
$results = DB::table('tabelaAngariacao')
->leftJoin('tabelaFotos', 'tabelaAngariacao.id', '=', 'tabelaFotos.angariacaoid')
->get();
The above script will give you columns from both tables.
And probably you don't need to use DB::table, you can use Eloquent Queries instead, since you've defined your relationsips
You can try it by doing this.
$results = TabelaFotos::with('TabelaAngariacao')->get();
Here is how it works
$results = ModelName::with('relationship_in_model_name')->get();
Hope it works

Laravel - Illegal offset type when accessing property on OneToMany relationship

I'm learning how to use laravel and relationships. I'm having trouble accessing data from a hasMany relationship, I understand this might be a silly question. This might be a duplicate question, but I didn't find any specific answer like this.
I have two models, a salesman table and a prices table table. One salesman has many prices tables, so it's like this:
On Salesman model
<?php
namespace App\Pedidos;
use Illuminate\Database\Eloquent\Model;
class Vendedores extends Model
{
protected $connection = 'Pedidos';
protected $primaryKey = 'CD_VENDEDOR';
public function TabelaDePreco() {
return $this->hasMany('\App\Pedidos\TabelaDePreco', 'CD_VENDEDOR', 'CD_VENDEDOR');
}
}
On the prices table model
<?php
namespace App\Pedidos;
use Illuminate\Database\Eloquent\Model;
class TabelaDePreco extends Model
{
protected $connection = 'Pedidos';
protected $primaryKey = ['CD_VENDEDOR', 'CD_PRODUTO', 'CD_ESTADO'];
public function Vendedores() {
return $this->belongsTo('\App\Pedidos\Vendedores', 'CD_VENDEDOR', 'CD_VENDEDOR');
}
}
On the Controller
public function index()
{
$vendedores = Vendedores::all();
return view('pedidos.tabeladepreco.index')
->with('title', 'Tabela de preços')
->with('vendedores', $vendedores);
}
On the view, this will return TabelaDePreco model
#foreach($vendedores as $vendedor)
#foreach ($vendedor->TabelaDePreco as $tabela)
{{ dd($tabela) }}
#endforeach
Here is a print from the code above:
TabelaDePreco model
As you can see, data is loaded on the $tabela variable.
If I try to print, on the view, {{ $tabela->NR_LIMITE1 }}, I get the illegal offset type error. How do I access this attribute since data is loaded when using dd()? I've tried $tabela['NR_LIMITE1'] but with the same error.
What am I doing wrong?
Best regards.
EDIT:
As pointed by Jonas on the comments, Laravel won't support relationships when one of the tables has composite keys. Back to migrations.
You need to eager load your relation:
$vendedores = Vendedores::with('TabelaDePreco')->all();
return view('pedidos.tabeladepreco.index')
->with('title', 'Tabela de preços')
->with('vendedores', $vendedores);
It may also happen that $vendedor->TabelaDePreco is not defined if there is not TabelaDePreco associated with the $vendedor. Try adding a isset(). Also thing about pagination if you have many entries.

laravel model relation not working

I have created a laravel api for my application.I have used Pingpong module package for different modules.I am having hard time establishing many-to-many relation.I have 3 tables:roles,groups,group_roles.And my models are:
Group.php
namespace Modules\User\Entities;
use Illuminate\Database\Eloquent\Model;
class Group extends Model {
protected $fillable = [];
protected $table='groups';
public static function roles(){
return $this->belongsToMany('Modules\User\Entities\Role','group_roles','group_id','role_id');
}
}
Role.php
namespace Modules\User\Entities;
use Illuminate\Database\Eloquent\Model;
class Role extends Model {
protected $fillable = [];
protected $table='roles';
public function groups(){
return $this->belongsToMany('Modules\User\Entities\Group','group_roles','group_id','role_id');
}
}
And my controller
namespace Modules\User\Http\Controllers;
use Pingpong\Modules\Routing\Controller;
use Modules\User\Entities\Group;
use Modules\User\Entities\Role;
use Illuminate\Http\Request;
use App\Login;
use Input;
use Validator;
use Hash;
use Response;
class UserController extends Controller {
public function getGroupById(Request $request){
$groups=Group::with('roles')->get();
return Response::json ([
'status'=>'ok',
'group'=>$groups
],200);
}
}
The problem is I am not able to establish the relation between the models and the getGroupById returns 500 internal error response.$group=Group::all(); $group=Group::find($request['id']); returns fine but it is not returning related roles.
Similar structure and codes work fine on app without the use pingpong.
Your relationships are currently like this:
// not sure why this is static?
public static function roles(){
return $this->belongsToMany('Modules\User\Entities\Role', 'group_roles', 'group_id', 'role_id');
}
public function groups(){
return $this->belongsToMany('Modules\User\Entities\Group', 'group_roles', 'group_id', 'role_id');
}
Please note from the docs, regarding the belongsToMany method:
The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to...
So with this in mind I think your relationships may be incorrect due to using the wrong arguments on your belongsToMany method calls. I think it should be like this:
public function roles(){
return $this->belongsToMany('Modules\User\Entities\Role', 'group_roles', 'group_id', 'role_id');
}
public function groups(){
return $this->belongsToMany('Modules\User\Entities\Group', 'group_roles', 'role_id', 'group_id');
}
Also if you have intermediate table columns you'd need to declare those on the belongsToMany call.
Hope that helps!
Edit
Firstly, you said getGroupById returns 500 internal error response. Have you tried checking what the actual error is!? 500 internal error doesn't provide much info, I'm sure you'd get to the bottom of things a lot faster if you found out the exact issue through laravel's usual error response page.
I assume you're doing this through an ajax request so you could use the network tab if you're using chrome then click on the 500 request to see the error laravel returns or you can use something like postman and hit the url through that.
If I wanted to quickly check the functionality of the models relationship methods, I'd do the following:
After setting up some data for a group and relationship, could you try running this in tinker or a route for testing/debugging.
$g = Group::first(); // get the first group, or you could use find($id) if you had a specific group in mind
// if you're in tinker
$g->roles; // show the roles
// if you're running on a route
dd($g->roles); // show the roles
While haakym's answer is very detailed, but you can also try changing your mapping table name to convention based 'group_role' instead of 'group_roles'. With this method you will have to supply only one argument to belongsToMany call.
Note that in general it should not matter if the other arguments are correct, but its just another step to debug!

How to listed to deleted event properly?

I have records of a Model that I need to delete, however I need to delete their id's also from the pivot table, so I tried to listed to deleted event, but it didn't work
Here is how I add the event:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Criteria extends Model {
protected $table = 'criterias';
public static function boot()
{
parent::boot();
static::deleted(function($criteria)
{
DB::table('criteria_criteria')->where('criteria_id', '=', $criteria->id)->delete();
});
}
}
I am on Laravel 5.1, any idea how to do so?
I think you have not used its relationship. Please create a relationship with your pivot table like this.
public function criteria()
{
return $this->belongsToMany('App\Criteria');
}
This will automatically manage your deletion query on pivot table. It has also one benifit you can use its sync and detach methods to add and remove pivot table records.
For more detail you can read in this tutorial by search keyword pivot.

How to return database table name in Laravel

Is there a way that I can get the current database table in use by the model that I'm in? I see that there is a table() function in Laravel/Database/Eloquent/model.php but I've been unsuccessful calling it calling it from the model that I'm in.
There is a public getTable() method defined in Eloquent\Model so you should be able to use $model->getTable().
Taylor has an answer to your question:
Within the model class you can do something like this:
return with(new static)->getTable();
If you want all your models to have the ability to return table name statically, then so something like this:
class BaseModel extends Eloquent {
public static function getTableName()
{
return with(new static)->getTable();
}
}
class User extends BaseModel {
}
User::getTableName();
Edit April 2019: This answer is now out of date. See the new correct answer by Flyn San
Yes - Eloquent has a $table variable. There are two ways you can access this:
class yourModel extends Eloquent {
public static $table = "differentTable";
function someFunction()
{
return yourModel::$table;
}
}
or
class yourModel extends Eloquent {
public function someFunction()
{
return $this->table();
}
}
then in your code
Route::get('/', function () {
$model = new yourModel();
dd($model->someFunction());
});
In my case, i'm using laravel 5.4
return (new static)->getTable();
Since table is a protected property in the Model class (Laravel >= 5) you will need an instance of your Model.
Here is a case example:
DB::table( (new YourModelClassname)->getTable() )
->update(['field' => false]);
You can get name of a model's table by following code:
If we have a Model as ModelName:
ModelName::query()->getQuery()->from
This method also works fine in case of custom table name that are defined by protected $table = 'custom_table_name' in the Model.
It will return the table name from the model. perfectly worked on laravel 8
app(Modelname::class)->getTable()
you have to replace Modelname with your model class
Based on Lucky Soni answer, there is another easy trick if you want to directly call it from Vontroller or View.
Tested in Laravel 6, and I keep using it, if you are "One Line Programmer" who hates extra line instance declaration. No need for extra lines in Model file too.
$string_table_name = with(new \App\Model\TableModelName)->getTable();
or better you may also be able to just call this
$string_table_name = (new \App\Model\TableModelName)->getTable();
It will return plain string of the tabel name even if you rename $table variable inside model class.
EDIT :
Minus Rep ?? Maybe you should try this first in your controller instead making new function in model class just to get table name and no need to declare the object when calling.
with() itself is Laravel helper function that returns an object of the class. and inside class that extends Model, already has function getTable(). So, you don't have to put another new redundant function inside model class.
It seems the latest version, you can just call (new Class) without with() function.
The difference between this answer and Lucky's answer, mine doesn't make any new function inside Model class to get the table name, even you can just call the function inside the Controller and View without declaring the object of model class. It's for beautify the code.
While Lucky's answer create new function that inside Model class, and you need to call the function from the object.
Simple way to get table name from Laravel Model by this:
$tableName = app(\App\User::class)->getTable();
Don't forget to replace:
\App\User
With Model path.
Here's an other approach so that you can get a model's table name statically.
Define a Trait: app/Traits/CanGetTableNameStatically.php
<?php namespace App\Traits;
trait CanGetTableNameStatically
{
public static function tableName()
{
return (new static)->getTable();
}
}
Extend your required Model or BaseModel with the use statement.
app/Models/BaseModel.php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Traits\CanGetTableNameStatically;
class BaseModel extends Model
{
use CanGetTableNameStatically;
// ...
}
On your models, if you set the custom table name on Laravel's reserved attribute: protected $table then it will still work & return correct table name.
app/Models/Customer.php
<?php namespace App\Models\Master;
use App\Models\BaseModel;
class Customer extends BaseModel
{
protected $table = 'my_customers';
// ...
}
Usage: just call YourModel::tableName() anywhere.
In Views:
{{ \App\Models\Customer::tableName() }}
When doing Joins:
DB::table( Product::tableName() . ' AS p' )
->leftJoin( ProductCategory::tableName() . ' AS pc', 'pc.id', '=', 'p.category_id')
// ... etc
Note:
I use this approach where needed but full disclosure, I found another answer here that have the exact same approach, so I copy pasted here for reference of course with citation thanks to #topher
Based on tailor Otwell's answer you could use something like this:
with(new Model)->getTable();
Note: tested on versions 5.x, 6.x, 7.x, 8.x and it works well.
another solution is to use the resolve helper like so:
resolve('\\App\\Models\\User')->getTable()
None of the answers so far will get you the table name with the prefix, if you are using a table name prefix. At this time it seems like we need to concatenate the prefix with the table name ourselves if we want the real name of database table.
Here's how to get the table name including the table prefix:
echo \App\MyModel::query()->getQuery()->getGrammar()->getTablePrefix() . app(\App\MyModel::class)->getTable();
in laravel 7.x (i'm used)
you can get table name with (new Target())->getTable();
$query->where('parent_id', function ($query) use ($request) {
$query->select('id')->from((new Target())->getTable())->where('unit_id', $request->unit_id);
});
hope it's helps
To people who want to get table name from a Builder object instead of other object, here you are:
$conn = DB::connection("my_private_mysql_conn");
$my_builder_object = $conn->table("my_table_name");
//This will print out the table name
print $my_builder_object->from;
It will work 100%. You will get table name.
$object = new OrderStockProduct();
// Use below line only when you have dynamic connection in laravel project
// $object->setConnection('mysql');
$object = $object->getTable();
dd($object);
I just wanted to add the following for people coming from search engines:
In case you do not even want to instantiate the Model at all (faster?) :
$model = 'App\User';
$modelTable = str_replace('\\', '', Str::snake(Str::plural(class_basename($model))));
dd($modelTable); // will return "users"
That might look ugly but that's exactly how the getTable() method resolves it under the hood, so...
You will need to use Illuminate\Support\Str; on top of your file.
Addendum: implying you follow the framework's standards (i.e: Post model has posts table, User model has users table, etc)
In Laravel 4 use static method
$table_name = Model::getTable();
or "self" inside Eloquent Model
$table_name = self::getTable();

Resources