Relationship function is not working in laravel - laravel

relationship function is not working of any type. i am creating 2 tables relationship of one to many but it is not working i have no idea at all about that i have follow tutorials and laravel documentation as well but all is vain please guide me thanks.
//this is user model..
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name','email','password','image','candidate_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
//
}
// and this is candidate model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Candidate extends Model
{
public function user()
{
return $this->hasOne('app\User');
}
}

It shows your model User store candidate_id, so there is 1 Candidate many User..
in Candidate model (Table Name should be candidates)
public function user()
{
return $this->hasMany(User::class);
}
in User model (Table Name should be users)
public function candidate()
{
return $this->belongsTo(Candidate::class);
}

All things were correct, I just call a single attribute of a second table instead of function. In Laravel we call function of related table not its attribute this is the mistake.

Related

Why I'm getting a null value when querying a model in eloquent?

I have a problem where I'm getting a null value when querying a model in eloquent, I have a two models User.php and Project.php, When I use tinker and use User.php to check if the data has a relation to Project.php model I got what I want, but when I use the Project.php to check if it has a relation to User.php I'm getting a null value.
This is my code for Project.php :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public $table = "project";
protected $guarded = [];
public function owner(){
return $this->belongsTo(User::class);
}
}
And this is my code for User.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
public function projects(){
return $this->hasMany(Project::class);
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
This is my result in Tinker:
This is the result when I use tinker and query, as you can see my User.php has a relation to Project.php, But when I use Project.php I'm getting null value.
Have you tried with:
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
Because (quote from the docs):
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column.
You should use eager loading to load parent relationship like this :
Project::with('owner')->first()->owner
And confirm that the foreign keys is correct

Laravel relationships not working as expected

So I have been building this simple Guest book where people leave comments. Ive linked the user model to the comment model and have tried returning the user that posted the comment however I always get an error. Ive made a Ticketing program before this using the same code and it worked and works fine still. See below
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('User::class');
}
}
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function comments()
{
return $this->hasMany(Comment::class);
}
}
And this is the controller where I am trying to return the results
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\User;
use Auth;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$comments = Comment::all();
$user = Auth::user();
$test = User::all();
$average = number_format((Comment::avg('rating')),2, '.', '');
dd($comments->user);
return view('welcome')->withComments($comments)->withUser($user)->withAverage($average);
}
}
Everytime I try and DD the result I get the error
Property [user] does not exist on this collection instance.
I am 100% stumped why this will work on one project and not another. I even rebuilt this little app to see if it was something I had done and I still get the same result.
You're trying to get property of a collection, not an object. So do this:
foreach ($comments as $comment) {
dump($comment->user); // $comment is an object
}

Returning null Value for User from Model

I'm getting a null value for the user at http://localhost:8000/messages. I am trying to get the user table values within the Message model. It also gives a null value in the console.
Route
Route::get('/messages', function () {
return App\Message::with('user')-> get();
})-> middleware('auth');
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
User Model code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function messages()
{
return $this-> hasMany(Message::class);
}
}
Snapshot
messages table must have user_id with proper user ID to make belongsTo relationship work.
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

How do I read database data from default User class in Laravel?

When I use the following code in my routes/web.php file, I keep getting the error of 'Trying to get property of non-object' each time I visit the /user/{id}/post url.
routes/web.php
use App\Post;
use App\User;
Route::get('/user/{id}/post', function($id) {
return User::find($id)->name;
});
App/User.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts() {
return $this->hasOne('Post');
}
}
App/Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
// protected $table = 'posts';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [''];
}
How do I view data stored in the table users? I put some dummy data in there to try and retrieve it.
If user hasOne relation with Post,it is better to make relation post() rather than posts() and post belongsTo user.
User Model:
public function post() {
return $this->hasOne('App\Post');
}
Post Model:
public function user()
{
return $this->belongsTo('App\User');
}
then, this gives all user's post along with user name.
$users=User::with('post')->get();
foreach($users as $user)
{
print_r($user->name);
print_r($user->post);
}

Getting data through pivot table using hasMany relationship

Hello i have these three models:
User.php
<?php namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Kodeine\Acl\Traits\HasRole;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword, HasRole;
/**
* The database table used by the model.
*
* #var stringSS
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password', 'is_active'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function roles()
{
return $this->belongsToMany('App\Models\Role', 'role_user', 'user_id', 'role_id');
}
public function bankBranch()
{
return $this->belongsToMany('App\Models\BankBranch', 'bank_branches_users', 'user_id', 'branch_id');
}
public function permissions()
{
return $this->belongsToMany('App\Models\Permissions', 'permission_user', 'user_id', 'permission_id');
}
}
Bank.php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Bank extends Model {
protected $table = 'bank_details';
public function branches()
{
return $this->hasMany('App\Models\BankBranch', 'bank_id');
}
public function users()
{
return $this->hasManyThrough('App\Models\User', 'App\Models\BankBranch');
}
}
BankBranch.php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BankBranch extends Model {
protected $table = 'bank_branches';
public function bank()
{
return $this->belongsTo('App\Models\Bank', 'bank_id');
}
public function users()
{
return $this->hasMany('App\Models\User', 'bank_branches_users', 'branch_id', 'user_id');
}
}
Okay now in my application i have the following relationships:
1. User belongs to Many Bank Branches.
2. Bank Branch belongs to one Bank.
3. BankBranch has many users.
Now when a user logs in i want them to only be able to see other users within the same bank branch as the user.
Meaning on my admin->user page i want a list of users in the same branch as the logged in user only.
Unless the logged in user belongs to many other branches, then it should display all the users in the branches the logged in user belongs to.
I am having great difficulty representing this in my eloquent models and fetching the data through my controllers.
to get user bankBranches ids:
$branchIds = Auth::user()->bankBranch()->get()->lists('id');
than gettting all users that belongs to this branches:
$usersInBranches = BankBranch::whereIn('id',$branchedIds)->with('users')->get();
or:
$usersInBranches = User::whereHas('bankBranch', function($query) use ($branchIds) {
$query->whereIn('id',$branchIds);
})->get();
edit or even better:
$usersInBranches = User::whereHas('bankBranch', function($query){
$query->whereIn('id',Auth::user()->bankBranch()->lists('id'));
})->get();

Resources