I am doing a learning project. very new to Laravel. So I have a User and a Company profile CRUD. Company belongsTo User and User may have many Company. So in my User model I implemented this
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Company;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'first_name', 'last_name', 'username', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
//relation with company
public function company(){
return $this->hasMany('App\Company','id');
}
}
and in company model i did
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
//table name
protected $table='companies';
//primary keys
protected $primaryKey='id';
//relation with User Model
public function user(){
return $this->belongsTo(App\Models\User::class);
}
My company profile controller is
public function index()
{
//Showing companies under user
$user_id = auth()->user()->id;
$user = User::find($user_id);
$companies=$user->company;
return view('company.profile')->with('companies', $companies);
}
But when it comes to execution, it seems like
public function user(){
return $this->belongsTo(App\Models\User::class);
}
this function in Company model is not working. I mean a company is getting assigned to one user but it should be like many companies in one user. What did I do wrong?
Btw my User model location is App/Model/User.php, and I declared the user model path in auth.php .My Company.php Model location is App/Company.php. please have a look and try to help this newb out. Many thanks.
i don't understand your question but my answer may be help you
users belongs to company
in model user
public function company()
{
return $this->belongsTo('App\Company');
}
maby be wrong code
//relation with company
public function company(){
return $this->hasMany('App\Company','id'); // not Id foreign_key as company_id
}
this is true but you can write it better as
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id)->with('company');
//$companies=$user->company;
return view('company.profile', compact('user');
}
Related
I have a table "articles" in this table a column name "user_id", I have another table "users" where store username, profile_pic etc... I want to fetch username on home page where I already fetched articles title.
Article Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
View Page(Home Page)
{{$article->user_id}}
Here I want to Display username
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
Add the following to Article class:
public function user() {
return $this->belongsTo(User::class);
}
Then you can access related user data with $article->user->name
Am using Zizaco entrust package and trying to get all users together with their roles
User model i have
use Laravel\Passport\HasApiTokens;
use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Model implements AuthenticatableContract
{
use Authenticatable,HasApiTokens, EntrustUserTrait;
protected $fillable = [
'name', 'email', 'password','status'
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsTo('App\Role', 'id');
}
}
Now the App\Role
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
}
Whenver i fetch my users with
$sortval = explode("|",$request->sort);
return \App\User::orderBy( $sortval[0], $sortval[1])
->with("role") //added the relationship
->paginate($request->per_page);
The above role always returns null even when there are assigned roles to users.
I recently started using laravel and having some issues with eloquent join .
I want to join 3 tables :
User (id)
UserBills (id , user_id , company_id , account)
Bills (id , company_id , account , amount)
I start with the user id (e.g=1)
From that i want to query UserBills and find all UB where the user_id = id
Next i want to query bills and find all bills where the bill company_id and account match UserBills
Basically i want to find all the bills that belong to that specific user . Bills does not have user_id however and must check with UserBills(company_id and account)
// This return all user bills with id = user_id
$results = User::findOrFail(1);
$ub = $results->user_bills;
From there , i have no idea how to join the bills or get the collection . Any help would be much appreciated.
Models (might be wrong)
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Eloquent;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name',
'email',
'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function user_bills()
{
return $this->hasMany('App\UserBills', 'user_id', 'id');
}
}
UserBills
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserBills extends Model
{
protected $table = 'ub';
protected $fillable =
[
'user_id',
'company_id',
'account',
];
public function user()
{
return $this->belongsTo('App\User' , 'id' , 'user_id');
}
}
Bills :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Bills extends Model
{
protected $table = 'bills';
protected $fillable =
[
'company_id',
'account',
'period',
'amount',
];
public function user_bills()
{
return $this->belongsTo('App\UserBills');
}
}
You can read your solution in the docs of HasManyThrough if your UserBills hasMany Bills.
I can't test this code right now, so you can see it as an example:
class User extends Authenticatable {
...
public function Bills()
{
return $this->hasManyThrough('App\UserBills', 'App\Bills');
}
}
Now you can get all bills of the user with
$User = User::findOrFail(1);
$Bills = $User->Bills()->get(); // collection with bills of your user instance
Edit #1
You should add a bill_id into the UserBills table ub.
Now you can try this code
class User extends Authenticatable {
...
public function getBillsAttribute() {
$user_id = $this->id;
return App\Bills::rightJoin('ub', function($join) use ($user_id) {
$join->on('ub.bill_id', '=', 'bills.id')
->where('ub.user_id', '=', $user_id);
})->get();
}
}
Use it like that
$User = User::findOrFail(1);
$Bills = $User->Bills; // collection with bills of your user instance
I have 4 tables:
user(id,role_id)
role(id)
permission_role(role_id,permission_id)
permission(id, name)
User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
/**
* 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 roles()
{
return $this->hasOne('App\Role', 'id', 'role_id');
}
}
Role model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
public function users()
{
return $this->belongsTo('App\User','role_id','id');
}
public function permissions()
{
return $this->belongsToMany('App\Permission','permission_role');
}
}
Permission model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
public function roles()
{
return $this->belongsToMany('App\Role','permission_role');
}
}
and i want to test in my controller to see if user have permission delete_article via if condition, any help? and thanks
In you Role model
Something like this you need to do (Many to Many)
//.......................
public function permissions()
{
return $this->belongsToMany('App\Permission','permission_role''role_id', 'permission_id');
}
//......................
See Many to Many relationship: Link
And to get the data into your controller
//..........................................
$user = get data with role and permission
$roles= $user->roles;
foreach($roles as $role){
foreach($role->permissions as $permission){
$permissiona_name = $permission->name;
}
}
//...........................
first check with var_dump($user)
Many to many with pivot (see Retrieving Intermediate Table Columns section)
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
See also "Has Many Through"
I already tried several things but I can't get this to work. I want to be able to make something like this {{ $user->city->name }}
My user model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public $timestamps = false;
protected $table = 'users';
protected $fillable = ['id_city', 'name', 'email', 'password', 'admin'];
protected $hidden = ['password', 'remember_token'];
public function city()
{
return $this->belongsTo('App\City');
}
}
And this is my City model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
public $timestamps = false;
protected $table = 'cities';
protected $fillable = ['name', 'slug'];
public function users(){
return $this->hasMany('App\User');
}
}
And I'm trying to use {{ $user->city->name }} on my view but it doesn't work, it returns an error ErrorException: Trying to get property of non-object (View: .../views/app/text.blade.php).
What should I do?
Within your belongsTo relationship, Eloquent tries to match city_id as the foreign key by default as you don't pass the second argument.
However, according to your fillable attributes, what you have as the foreign key is actually id_city.
For the User model,
public function city()
{
return $this->belongsTo('App\City', 'id_city');
}
For the City model,
public function users(){
return $this->hasMany('App\User', 'id_city', 'id');
}