laravel 5.2 belongsTo relation not work - php

I'd like to get some additional user information from the divisions table.
But not work why?
BadMethodCallException in Macroable.php line 81: Method division does
not exist.
class AdminsController extends Controller
public function getUserIndex()
{
$users = User::all()->division();
dd($users);
}
class User extends Authenticatable
public function division()
{
return $this->belongsTo('App\Division', 'division_id');
}
class Division extends Model
public function users()
{
return $this->hasMany('App\User');
}
Users table
$table->foreign('division_id')->references('id')->on('divisions')->onUpdate('cascade');
Divisions table
$table->increments('id');

The division() relationship is defined for each individual table row. By calling it on all(), you're attempting to get the relationship for all rows.
You should be able to use something like:
public function getUserIndex()
{
$users = User::all();
foreach ($users as $user) {
dd($user->division());
}
}

Related

Laravel 6 - Illuminate\Database\Eloquent\RelationNotFoundException Call to undefined relationship

I want to send nama column from Supplier table to Transaction_in table, but iget this error.
Illuminate\Database\Eloquent\RelationNotFoundException Call to
undefined relationship [get_transactions_in] on model
[App\Transaction_in].
Transaction_in Model
class Transaction_in extends Model
{
protected $guarded = [];
public function get_suppliers(){
return $this->belongsTo(Supplier::class, 'Supplier_id');
}
}
Supplier Model
class Supplier extends Model
{
protected $guarded = [];
public function get_transactions_in(){
return $this->hasMany(Transaction_in::class);
}
}
Transaction_in Controller
public function index()
{
$transaction_ins = Transaction_in::with('get_transactions_in')->get();
return view('transactionsIN.index', compact('transaction_ins', $transaction_ins, 'supplierList'));
}
The foreign key is Supplier_id based on id from Supplier table.
You called wrong relationship in with it should be get_suppliers instead of get_transactions_in
Transaction_in Model has get_suppliers method so,
$transaction_ins = Transaction_in::with('get_suppliers')->get();
just change your controller code with below
public function index()
{
$transaction_ins = Transaction_in::with('get_suppliers')->get();
return view('transactionsIN.index', compact('transaction_ins', $transaction_ins, 'supplierList'));
}
you got an error because there is no relation like "get_transactions_in" in your Transaction_in model

Problem with Laravel Eloquent - relation not working

I'am beginner in Laravel. I have project in Laravel 5.8.
I have User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use psCMS\Presenters\UserPresenter;
use scopeActiveTrait;
public static $roles = [];
public $dates = ['last_activity'];
// ...
public function scopeHistory()
{
return $this->hasMany('App\UserLoginHistory');
}
// ...
}
and UserLoginHistory:
class UserLoginHistory extends Model
{
protected $quarded = ['id'];
public $timestamps = false;
protected $fillable = ['user_id', 'date_time', 'ip'];
public function user()
{
return $this->belongsTo('App\User');
}
}
I want show user login history by this code:
User::history()->where('id', $idAdmin)->orderBy('id', 'desc')->paginate(25);
but it's not working.
This function not working - I haven't got results.
How can I fixed it?
First of all, you are defining your relationship as a scope (prefixing the relationship with the scope keyword). Try updating your model relationship to this:
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
Then, given your query, it seems that you want to get all the UserLoginHistory
records for a given User. You could accomplish this in two ways (at least).
From the UserLoginHistory model itself, constraining the query by the foreign key value:
$userId = auth()->id(); // get the user ID here.
$results = UserLoginHistory::where('user_id', $userId)->paginate(15);
// ^^^^^^^ your FK column name
From the User model using your defined relationship:
$userId = auth()->id(); // get the user ID here.
$results = User::find($userId)->history;
The downside of the second approach is that you'll need to paginate the results manually.
in your User model you should define your relation by this way :
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
then if you would like to select with history model you can do that with WhereHas() method :
User::whereHas(['history'=>function($q) use ($idAdmin) {
$q->where('id',$idAdmin)
}])->orderBy('id', 'desc')->paginate(25);
You must be do this changes
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
usage
$user = User::find($idAdmin);
$userHistories = $user->history()->latest()->paginate(25);
or get user with all history
User::with('history')->find($idAdmin);
// Post model
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
// Category model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}

Unable to seed db table with relationship in Laravel

In a laravel 5.8 application, I want to seed the users & products table. There is a relationship between the users & products like this
User.php model (users can have one or more products)
public function products()
{
return $this->hasMany(Product::class, 'user_id');
}
Product.php model (a product can belong to one or more users)
public function users()
{
return $this->belongsToMany(User::class);
}
I am trying to use the UsersTableSeeder below to seed both the users table & products table at the same time
public function run()
{
factory(App\User::class, 3)->create()->each(function ($user) {
$user->products()->save(factory(App\Product::class, 3)->make());
});
}
and the 'DatabaseSeeder`looks like this
public function run()
{
$this->call(UsersTableSeeder::class);
}
When I run the command php artisan db:seed, only the users table is seeded and I get this error
Symfony\Component\Debug\Exception\FatalThrowableError : Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of
Illuminate\Database\Eloquent\Collection given, called in C:\Users\Elomena\Projects\Clients\Pramopro\database\seeds\UsersTableSeeder.php on line 15
This is line 15 $user->products()->save(factory(App\Product::class, 3)->make());
I really don't understand why I am getting this error as I have followed the exact thing from the https://laravel.com/docs/5.8/seeding#using-model-factories
Please how should seeding with relationships be done?
This can be solve your problem:
public function run()
{
factory(App\User::class, 3)->create()->each(function ($user) {
$user->products()->saveMany(factory(App\Product::class, 3)->create());
});
}
The error message suggests that you're using a collection instead of a model.
The error is caused by this function, it returns a collection and not a model, because it's a hasMany relationship.
public function products()
{
return $this->hasMany(Product::class, 'user_id');
}
So, you should change your seeder to saveMany instead of save.
public function run()
{
factory(App\User::class, 3)->create()->each(function ($user) {
$user->products()->saveMany(factory(App\Product::class, 3)->create());
}); // ^ saveMany instead of save
}

My Laravel relationship problems

I'm trying to do browser game like Tribal Wars in Laravel.
I want to get building level by using $wioska->buildings->Tartak->level, but something not working:
This is my Building model:
class Building extends Model
{
protected $table = 'budynki';
public function Tartak(){
return $this->hasOne('App\Tartak');
}
}
Wioska (village) model:
class Wioska extends Model
{
protected $fillable = ['name', 'user_id'];
protected $table = 'wioski';
public function user(){
return $this->belongsTo('App\User');
}
public function buildings(){
return $this->hasOne('App\Building');
}
}
And this is my Tartak model:
class Tartak extends Model
{
protected $table = 'budynki';
public function level(){
$u = Auth::user();
$id = $u->wioska->id;
return DB::table('budynki')->where('wioska_id', $id)->first();
}
}
Migration "budynki":
public function up()
{
if(!Schema::hasTable('budynki')) {
Schema::create('budynki', function (Blueprint $table) {
$table->integer('town_hall')->default(1);
$table->integer('iron')->default(0);
$table->integer('wood')->default(0);
$table->integer('stone')->default(0);
$table->integer('bread')->default(0);
$table->integer('wioska_id');
$table->foreign('wioska_id')->references('id')->on('wioski');
});
}
}
1) It's always good to check for a null entity before trying to call its methods. Example, if $wioska->buildings is null or wioska has no buildings, or buildings have no Tartak, then the rest of the line will throw errors.
2) level() is a method and since its not an authentic Laravel relationship, you will need to use it as a method, example - $wioska->buildings->Tartak->level()
level is not property as per your model, so you have to try as below
$wioska->buildings->Tartak->level()
Now I've got
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'budynki.building_id' in 'where clause' (SQL: select * from budynki where budynki.building_id is null and budynki.building_id is not null limit 1) error
I just want to get tartak level from budynki table: https://i.imgur.com/zoTx5tE.png .

Laravel 5.1 eloquent query syntax

I have the following model relationships. If a user logs in as an employee, I want them to be able to get a list of employees for a their company and the roles they have been assigned:
class User {
// A user can be of an employee user type
public function employee()
{
return $this->hasOne('App\Employee');
}
//
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
class Employee {
// employee profile belong to a user
public function user()
{
return $this->belongsTo('App\User');
}
// employee belongs to a company
public function company()
{
return $this->belongsTo('App\Company');
}
}
class Company {
public function employees()
{
return $this->hasMany('App\Employee');
}
}
But the following query doesnt work. I get error Column not found: 1054 Unknown column companies.id in WHERE clause:
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles' => function ($query) use ($employee) {
$query->where('companies.id', '=', $employee->company_id)
->orderBy('users.created_at', 'desc');
}])->get();
The users and the employees table have a one to one relationship.
All employees have a base role type of employee in addition they may also have other roles such as manager, supervisor etc.
How do I write a query that gives me a company with all its employees and their roles?
I've tried to add a hasManyThrough relation to the Company model but that doesn't work either?
public function users()
{
return $this->hasManyThrough('App\User', 'App\Employee');
}
I think you're ring to get a list of coworkers for the current user and eager load the user and role?
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles')->find($employee->company_id);
Or perhaps:
$companyEmployees = Company::find($employee->company_id)->employees()->with('user.roles')->get();
$sorted = $companyEmployees->sortBy(function($employee){ return $employee->user->created_at; });
That might be a more direct route. Is your employee id in the user table or vice versa? The eloquent relationships are easy to set backwards.
Users::select('table_users.id')->with('roles')->join('table_employes', function($join) use ($employee) {
$join->on('table_employes.user_id','=','table_users.id')->where('table_employes.company_id', '=', $employee->company_id);
})->orderBy('tables_users.created_at')->get();
1. Create relationship for database table columns in migrtaion :
User Role
$table->foreign('user_id')->references('id')->on('users');
Users
$table->increments('id');
2. Create a model for each database table to define relationship
User.php (model)
public function userRoles()
{
return $this->hasOne('App\UserRoles', 'user_id', 'id');
}
Userroles.php (model)
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
3. Let controller handle database calls recommended to use REST api
Controller
use App\User;
use App\UserRoles;
class UserController extends Controller
{
public function index()
{
return User::with('userRoles')->orderBy('users.created_at', 'desc')->paginate(50);
}
}

Categories