Getting data through pivot table using hasMany relationship - laravel

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();

Related

Laravel Showing all users and check if belong to Bans table

Hi im working on admin dashboard
and i want to show all users and check if the user blocked get information about the ban from bans table
im using cybercog/laravel-ban to ban users
Laravel 5.8
So i have two table
Users table and Bans table
Bans table has the user id of the banded user in column called : bannable_id
User model :
namespace App;
use Illuminate\Notifications\Notifiable;
use Cog\Contracts\Ban\Bannable as BannableContract;
use Cog\Laravel\Ban\Traits\Bannable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Verified;
class User extends Authenticatable implements MustVerifyEmail,BannableContract
{
use Notifiable;
use Bannable;
protected $fillable = [
'name', 'email', 'password',
'last_login_at',
'last_login_userganet',
'avatar','uid'
];
/**
* 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',
];
public function UserBan()
{
return $this->hasOne('App\Ban','bannable_id');
}
Ban Model :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ban extends Model
{
protected $fillable = [
'id','expired_at','bannable_type'
];
protected $casts = [
'bannable_type'
];
public function Users()
{
return $this->belongsTo('App\User');
}
}
User Controller :
namespace App\Http\Controllers;
use App\User;
use App\Ban;
use App\Http\Requests\UserRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Cog\Contracts\Ban\Bannable;
class UserController extends Controller
{
/**
* Display a listing of the users
*
* #param \App\User $model
* #return \Illuminate\View\View
*/
public function index(User $model,Ban $banModel)
{
return view('users.index', ['users' => $model->paginate(15),'bans'=>$banModel->paginate(15)]);
}
Users schema :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->timestamp('last_login')->nullable();
$table->string('last_login_provider')->nullable();
$table->string('last_login_useragent')->nullable();
$table->string('last_login_ip')->nullable();
$table->string('uid')->nullable();
$table->string('password');
$table->string('avatar')->nullable();
$table->string('facebook_id')->unique()->nullable();
$table->string('google_id')->unique()->nullable();
$table->string('twitter_id')->unique()->nullable();
$table->string('instagram_id')->unique()->nullable();
$table->enum('user_type',['member','admin'])->default('member');
$table->boolean('blocked')->default(false);
$table->timestamp('banned_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
I could not found the bans schema but this is the table of bans :
you are using wrong relationship, you should use polymorphic. Look link below.
https://laravel.com/docs/5.8/eloquent-relationships#one-to-one-polymorphic-relations
it would be something like
User model
public function ban()
{
return $this->morphOne('App\Ban', 'bannable');
}
Ban Model
public function bannable()
{
return $this->morphTo();
}
get all users in controller
define
use App\User;
then
$users = User::all();
then you can foreach it and call ban() method on each
foreach($users as $user)
{
//return associated ban model
$user->ban;
}
Or for better performance, use
User::with(ban)->get();
which highly decrease number of SQL calls. It retrieves all user with ban model. Look at eager loading in link below.
https://laravel.com/docs/5.8/eloquent-relationships#eager-loading
Hope it helps. :)

How to use eloquent on the auth command user in laravel

I am facing a weird error right now
In my controller, when I import the class user like this
use Illuminate\Foundation\Auth\User;
It works when I use eloquent like
public function index()
{
$farms = User::where('role_id', 3)->get();
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal', 'farms'));
}
But refuses to work when it comes to table relationships like
public function show($id)
{
$farms = User::with(['animals'])->findOrFail($id);
return view('clinic.show',compact('farms'));
}
showing me this error
"Call to undefined relationship [animals] on model [Illuminate\Foundation\Auth\User]"
But whenever I import the user class as App\User in my controller,
It works in the relationship but refuses to work with the eloquent showing this error
"Call to a member function get() on null"
Now I am kinda confused. Any help will be welcomed
App\User
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = [];
public static function where(string $string, int $int)
{
}
public static function select(array $array)
{
}
public function role(){
return $this->belongsTo(Role::class);
}
public function animals(){
return $this->hasMany(Animal::class);
}
public function clinics(){
return $this->hasMany(Clinic::class);
}
public function slaughter(){
return $this->hasMany(Slaughter::class);
}
public function address(){
return $this->belongsTo(Address::class);
}
/**
* 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',
];
}
The Illuminate\Foundation\Auth\User class is the parent of the App\User class and animals relation set in the App\Userclass. So you can't call animals relation from Illuminate\Foundation\Auth\User class.
You should remove these functions from the App\User Model:
public static function where(string $string, int $int)
{
}
public static function select(array $array)
{
}

Relationship function is not working in 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.

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);
}

Resources