I have laravel's basic auth system, a custom model called SecurityQuestion and a pivot table called securityquestion_user
User
public function securityquestion_user() {
return $this->belongsToMany(SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
SomeController
First option
foreach(Auth::user()->securityquestion_user as $question) {
dd($question);
}
Error: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$pivot
Second Option
foreach(Auth::user()->securityquestion_user() as $question) {
dd($question);
}
Error: returns false
Ok guys I got it,
I modified the relation to this:
public function securityquestion_user() {
return $this->belongsToMany('App\SecurityQuestion', 'securityquestion_user', 'user_id', 'question_id')->withPivot('question_id', 'user_id', 'answer');
}
Basically I reversed the order and place 'user_id' parameter before 'question_id' parameter.
foreach(Auth::user()->securityquestion_user as $question) {
print '<pre>';
print_r($question->pivot->answer);
print '</pre>';
}
Thank you very much for you interest.
Have you added namespace for auth in controller?
Like:
use Auth;
If not imported then use this for it:
foreach(\Auth::user()->securityquestion_user as $question) {
dd($question);
}
And also correct your function in user model
public function securityquestion_user() {
return $this->belongsToMany('App\SecurityQuestion::class', 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
because your first option is correct except it!!
Try by using hasMany instead of belongsToMany in user model
public function securityquestion_user() {
return $this->hasMany (SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
Try like this, withPivot function expects one parameter: array or string.
public function securityquestion_user() {
return $this
->belongsToMany(SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')
->withPivot(['question_id', 'user_id', 'answer']);
}
And 'question_id' and 'user_id' are not necessary to be in withPivot function, since they are the foreign keys.
Related
I am trying to get my data in table by ajax and it's successfull but some of data are id of other tabels and those data i cannot get somehow!
Example
Sample data returned by JS:
customers":[
{
"id":2,
"group_id":3,
"industry_id":2,
"name":"fwgvwrg",
"companyName":"bget"
}
]
In this data if i use like: i.group.name (same as in blade if we say {{$customer->group->name}} for group_id it returns error of
Uncaught TypeError: Cannot read property 'name' of undefined
Basically there is no issue from JS it's about my models relations here are my models:
Customer model
public function group()
{
return $this->belongsTo(GroupCustomer::class, 'id', 'group_id');
}
public function industry()
{
return $this->belongsTo(Industry::class);
}
Groups model
public function customers() {
return $this->hasMany(Customer::class, 'id', 'group_id');
}
Industry model
public function customers() {
return $this->hasMany(Customer::class);
}
Any idea?
Seems the problem is your model relationship about foreign key parameter position:
public function group()
{
return $this->belongsTo(GroupCustomer::class, 'group_id', 'id');
}
See model doc here
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
In Blade view you can call laravel relationship directly. it will work fine.
but in Js it won't work. you can't call relationship
so when you have to use with() like below
Ex : Customer::with('group')->get();
I have a user table it has one userRole and userRole belongs to Role. So, I want to fetch the userRole and Role also.
Code in user Model:
public function userRole()
{
return $this->hasOne(UserRole::class);
}
Code in UserRole model:
public function role()
{
return $this->belongsTo('App\Role');
}
Code in controller:
User::with('userRole', function ($role) {
$role->with(['Role']);
})
->wherehas('userRole', function ($query) {
$query->where('role_id','1');
})->get();
This is giving me error
"mb_strpos() expects parameter 1 to be string"
The problem is that you should pass an array when you want to add a constrait to the with() method.
Your code should like something like:
User::with([
'userRole' => function ($query) {
...
}
])
...
My model Dispatch has a field invoice_id.
It is a foreign key so i can get the invoice details using the below code:
protected $fillable = [
'id',
'truck_no',
'driver_name',
'driver_phone',
'gps_details',
'invoice_id',
];
public function invoice(){
return $this->belongsTo('App\Invoice')->select('id','invoice_no','permit_id');
}
Now I want to get the value permit_id from invoice() so i can use it to get the details of the Permit.
permit_id = id of Permit model
So I use the below code to get the permit data.
public function permit(){
return $this->hasOne('App\Permit','id',$this->invoice()->permit_id);
}
Update:
My Invoice Model has :
class Invoice extends Model
{
protected $fillable = [
'id',
'invoice_no',
'invoice_date',
'permit_id',
];
public function permit(){
return $this->hasOne('App\Permit', 'id', 'permit_id');
}
}
My Permit Model has:
class Permit extends Model
{
protected $fillable = [
'permit_type',
'permit_no',
'application_no',
'supply_unit',
'supply_unit_id' ,
];
public function supplyunit(){
return $this->hasOne('App\SupplyUnit','id','supply_unit_id');
}
}
And as per suggestions i have added below code in my Dispatch Model:
class Dispatch extends Model
{
protected $fillable = [
'id',
'truck_no',
'driver_name',
'driver_phone',
'gps_details',
'invoice_id',
];
public function invoice(){
return $this->hasOne('App\Invoice','id','invoice_id');
}
public function permit(){
return $this->hasOne('App\Permit','id','permit_id');
}
}
But it doesn't work. What should i do to achieve the above? Is there any other solutions please suggest.
Assuming each invoice has one permit, your relationship definition should look like this:
public function permit(){
return $this->hasOne('App\Permit', 'id', 'permit_id');
}
Edit: If invoice belongs to permit, which is the inverse, your relationship would look like this instead:
public function permit(){
return $this->belongsTo('App\Permit', 'permit_id');
}
Edit: Based on your updated question, I think you got the relationship definitions a bit wrong. The following should work:
Since you have an invoice_id column in App\Dispatch, it means that each App\Dispatch belongs to an invoice.
In App\Dispatch, your relationship definition should be as follows:
public function invoice() {
return $this->belongsTo('App\Invoice');
}
// permit does not belong to `App\Dispatch` as a direct relationship
// it should be removed
In App\Invoice, your relationship definition should be as follows:
public function dispatch() {
return $this->hasOne('App\Dispatch');
}
public function permit() {
return $this->belongsTo('App\Permit');
}
In App\Permit, your relationship definition should be as follows:
public function invoice() {
return $this->hasOne('App\Invoice');
}
To then retrieve the permit id from an Invoice model, you would do
$invoice->permit->id;
Change this line
return $this->belongsTo('App\Invoice')->select('id','invoice_no','permit_id');
To
return $this->belongsTo('App\Invoice');
And add the following code on Invoice
public function permit(){
return $this->belongsTo('App\Permit');
}
And you can access as
Dispatch::find($id)->invoice->permit->id;
Or if you want all the information
Dispatch::find($id)->invoice->permit;
I have question about Laravel Eloquent. I created few tables and models, ~like this:
Trip
id
name
user
User
id
email
Message
id
content
trip
user
How can I get all message for single user with all foreign keys? You know, all data from this tables. Like this:
[
1 => [
'content',
'trip' => [
'name'
],
'user' => [
'email'
]
]
]
It's possible, to get in easy way all data?
My models:
// Message.php:
public function user()
{
return $this->belongsTo('App\User');
}
public function trip()
{
return $this->belongsTo('App\Trip');
}
// Trip.php:
public function user()
{
return $this->belongsTo('App\User');
}
// User.php:
public function trips()
{
return $this->hasMany('App\Trip');
}
public function messages()
{
return $this->hasMany('App\Message');
}
My Code
dd(
User::with([
'sent',
'recipient'
])->find(2)->toArray()
);
And what I want to get:
screen
I believe you are looking for the load method.
Lets say you have a user
$user->load('messages'); // var_dump($user);
If you vardump your user object you will see the related messages were loaded.
Use eager loading to achieve that.
Try this:
$users = User::with([
'messages.trip',
])->get();
dd($users);
Ref: https://laravel.com/docs/5.3/eloquent-relationships#eager-loading
I have been trying to create a simple user management system but keep on hitting road blocks when it comes to querying relations. For example I have users and roles and whenever I try to make a query for all users and their roles I get an error. The one in the title is only the latest one I've encountered.
My User and Role Models look like this:
class Role extends Model
{
public function users()
{
$this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');
}
}
class User extends Model
{
public function roles()
{
$this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}
}
My migration table for many-to-many relationship between the two looks like this:
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable(); //fk => users
$table->integer('role_id')->unsigned()->nullable(); //fk => roles
$table->foreign('fk_user_role')->references('id')->on('users')->onDelete('cascade');
$table->foreign('fk_role_user')->references('id')->on('roles')->onDelete('cascade');
});
}
And then I try to get all records with their relation in a controller:
public function index()
{
$users = User::with('roles')->get();
return $users;
}
So I need another pair of eyes to tell me what is it I am missing here?
You are missing return statements in the methods that define relations. They need to return relation definition.
Replace
public function roles()
{
$this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}
With
public function roles()
{
return $this->belongsToMany('\App\Role', 'role_user', 'user_id', 'role_id');
}
You forgot the return in your functions
Do:
return $this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');
return $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
You need to use Return for your function's result. If you do not do that, Laravel does not know What should do with that function without any action.
Just use like this
return $this->hasOne(xxx, xx, xx);
Enjoy your coding !
Make sure you have written return in your model function relation.
return $this->hasMany('App\StaffShift','user_id','user_id');