laravel model relation not working - laravel

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!

Related

Best way to check if user 'owns' another user

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.

withTrashed on hasManyThrough relation

How can withTrashed be applied on a hasManyThrough relation ?
$this->hasManyThrough('App\Message', 'App\Deal')->withTrashed();
returns
Call to undefined method Illuminate\Database\Query\Builder::withTrashed()
when i'm doing:
$messages = Auth::user()->messages()->with('deal')->orderBy('created_at', 'DESC')->get();`
Here is my Deal model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Deal extends Model
{
use SoftDeletes;
/* ... */
protected $dates = ['deleted_at'];
public function user() {
return $this->belongsTo('App\User');
}
public function messages() {
return $this->hasMany('App\Message'); // I've tried to put withTrashed() here, there is no error but it doesn't include soft deleting items.
}
}
To all those coming to this late, there is now a native way of doing this with Laravel.
$this->hasManyThrough('App\Message', 'App\Deal')->withTrashedParents();
This is not well documented but can be found in Illuminate\Database\Eloquent\Relations\HasManyThrough
The error is thrown because you are requesting a messages with deleted ones without using SoftDelete trait in Message model.
After I check the hasManyThrough relation code I found that there is no way to do it in this way, you should play around.
Ex:
get the deals of user with messages instead
$deals = Auth::user()->deals()->withTrashed()->with('messages')->get();
foreach($deals as $deal) {
//Do your logic here and you can access messages of deal with $deal->messages
}

How to access my model in laravel?

I can't seem to figure out what's wrong with this code. I'm running laravel 5.4.
The error:
https://www.dropbox.com/s/64ioxdf4mv6ps1w/Screenshot%202017-02-28%2020.11.33.png?dl=0
The Controller function:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Thread;
class ThreadController extends Controller
{
public function show($id) {
return Thread::where('id', '=', $id)->messages();
}
}
The Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
public function messages()
{
return $this->hasMany(Message::class)->get();
}
}
I suggest adding your error code instead of linking to image (right now AWS is down, thus I'm unable to view the image).
Regardless, the messages method is defining a relationship and as such, is an instance of the query builder. Rather than chaining the get method there, I suggest a slightly different approach:
In your controller
public function show($id)
{
// Use first() instead of get() since you're returning a
// specific model by its primary key (I assume)
return Thread::where('id', $id)->with('messages')->first();
}
And in your model
public function messages()
{
// This returns a query builder instance, which is what you want.
// It defines the relationship between Thread and Message
return $this->hasMany(Message::class);
}
This will eager load your messages along with your Thread model.
Hope it helps!
Regarding Joel's question in the comments...
User::find(1)->messages->create($request->only('body'));
Is not calling the 'messages function' you mentioned and not returning the relationship. Instead, it is calling the messages property, which is something different.

Issue with Laravel hasMany relation

I’m having an issue with relations in two of my models in a Laravel application. My models are:
class Invoice extends Eloquent {
protected $table = 'invoices';
public function line_items()
{
return $this->hasMany('LineItem');
}
}
And:
class LineItem extends Eloquent {
protected $table = 'line_items';
public function invoice()
{
return $this->belongsTo('Invoice');
}
}
In my controller, I fetch an Invoice row with the following:
$invoice = Invoice::find($id);
However, if I try and access the line_items property to fetch the LineItem rows relating to my invoice, I get the following error:
Invalid argument supplied for foreach()
Why is this? I’ve set my models up as per Laravel’s documentation: http://laravel.com/docs/eloquent#one-to-many
change
public function line_items()
for
public function lineItems()
and it will work , tested in Laravel 4.1 :)
Check your tables relations... (Schema)
Your FK must be lineitem_id... You have modified this? Laravel will configure automatically... Don't change this...
Then, try
$invoice->line_items() or $invoice->line_items in 4.1
Check for line_items before the foreach loop:
if(! $invoice->line_items->isEmpty()){
foreach($invoice->line_items as $line_item){
//do stuff
}
}
Also, it won't hurt to explicitly mention the FK, although laravel will automatically try to do it for you provided you use proper names for your table fields.
//Invoice Model
return $this->hasMany('LineItem', 'invoice_id');
//LineItem Model
return $this->belongsTo('Invoice', 'invoice_id');

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