// models:
class Hometype extends Eloquent {
public function development() {
return $this->belongsTo('Development');
}
}
class Development extends Eloquent {
public function hometypes() {
return $this->hasMany('Hometype', 'dev_id');
}
}
with that, I can do:
// controller:
$development = Development::where('stuff')->first();
// view:
#foreach ($development->hometypes as $hometype)
{{ $hometype->stuff }}
#endforeach
which is perfectly lovely.
but I can't seem to do:
// controller:
$hometype = Hometype::where('stuff')->first();
// view:
{{ $hometype->development->stuff }} // <- fails
How do I access a field on the parent Development model from within $hometype?
I'm resorting to:
'development' => Development::find($hometype->dev_id),
which seems silly.
Possible duplicate of: Laravel 4 - Can't retrieve data in a one-to-many relationship, but I'm not camelCasing...
Also similar to: Laravel 4 hasOne / belongsTo relationship (no answers here)
As I can see, there might be two problems:
The foreign key in Hometype is wrong (if you're using a different column name than "column"_id then you have to specify it)
You might be fetching a Hometype record whose development row doesn't exist
Accessing data and methods between hasMany and belongsTo
First get required models and then loop through
These are the model:
class ExpenseCategory extends Model
public function expense_transactions()
{
return $this->hasMany('App\ExpenseTransaction');
}
class ExpenseTransaction extends Model
public function expense_category()
{
return $this->belongsTo('App\ExpenseCategory');
}
Schema for the above model:
Schema::create('expense_transactions', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('expense_category_id')->nullable();
$table->unsignedInteger('day_sheet_id')->nullable();
$table->string('expense_title')->nullable();
$table->unsignedInteger('amount');
$table->timestamps();
$table->foreign('expense_category_id')
->references('id')->on('expense_categories')
->onDelete('cascade');
$table->foreign('day_sheet_id')
->references('id')->on('day_sheets')
->onDelete('cascade');
Schema for category:
Schema::create('expense_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
find only expense transactions for day sheet id in model
$expenseTransactions = ExpenseTransaction::where('day_sheet_id', $id)->get();
show their category name
access in blade:
in a foreach loop
#foreach($expense_transactions as $expense_transaction)
{{ $expense_transaction->expense_category->name }}
Related
I have two models called DataKelurahan and RegistrasiPasien and have a one-to-many relationship, but I can't access the relationship.
I have made a form for adding patient and save it to the registrasi_pasiens table and it works well. but when I try to display the relation data, it doesn't work properly.
In the registrasi_pasiens table, I have 1 record with kelurahan_id = 3. Then, I try to access it via php artisan tinker with these command:
$kelurahan = App\Domain\DataKelurahan\Models\DataKelurahan::find(3) works fine and data is exist.
$pasien = App\Domain\RegistrasiPasien\Models\RegistrasiPasien::find(2007000001) works fine and the data is exist with kelurahan_id = 3
$kelurahan->pasiens the result is null. Shouldn't it show the pasien data that has kelurahan_id = 3?
$kelurahan->pasiens->nama and the result is like this PHP Notice: Trying to get property 'nama' of non-object in D:/PROFESSIONAL/PROJECT/WEB DEVSeval()'d code on line 1 => null
I don't have any idea what's wrong with my codes. Much appreciate for your help guys.
Below are the models that I have made:
DataKelurahan.php
<?php
namespace App\Domain\DataKelurahan\Models;
use Illuminate\Database\Eloquent\Model;
use App\Domain\RegistrasiPasien\Models\RegistrasiPasien;
class DataKelurahan extends Model
{
protected $fillable = ['nama_kelurahan', 'nama_kecamatan','nama_kota'];
public function pasiens(){
return $this->hasMany('RegistrasiPasien');
}
}
RegistrasiPasien.php
<?php
namespace App\Domain\RegistrasiPasien\Models;
use Illuminate\Database\Eloquent\Model;
use App\Domain\DataKelurahan\Models\DataKelurahan;
class RegistrasiPasien extends Model
{
protected $fillable = [
'nama',
'alamat',
'telepon',
'rt',
'rw',
'tgl_lahir',
'jenis_kelamin'
];
public function kelurahan(){
return $this->belongsTo('DataKelurahan');
}
}
And below are my database tables:
data_kelurahans
Schema::create('data_kelurahans', function (Blueprint $table) {
$table->increments('id');
$table->string('nama_kelurahan');
$table->string('nama_kecamatan');
$table->string('nama_kota');
$table->timestamps();
});
registrasi_pasiens
Schema::create('registrasi_pasiens', function (Blueprint $table) {
$table->increments('id');
$table->integer('kelurahan_id')->unsigned();
$table->string('nama');
$table->string('alamat');
$table->char('telepon', 15);
$table->integer('rt');
$table->integer('rw');
$table->date('tgl_lahir');
$table->string('jenis_kelamin');
$table->timestamps();
});
Schema::table('registrasi_pasiens', function (Blueprint $table){
$table->foreign('kelurahan_id')->references('id')->on('data_kelurahans')->onDelete('cascade');
});
From Docs:
Eloquent will automatically determine the proper foreign key column on
the model. By convention, Eloquent will take the "snake case"
name of the owning model and suffix it with _id.
So, Eloquent probably got your foreign key name wrong so you must override the foreign key by passing additional arguments to the hasMany/belongsTo method:
public function pasiens(){
return $this->hasMany('RegistrasiPasien','kelurahan_id');
}
public function kelurahan(){
return $this->belongsTo('DataKelurahan','kelurahan_id');
}
I don't understand how to return info back to blade template if I have two related tables:
First table is standard Laravel 'users' table
Second table:
Schema::create('recipes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('code', 10);
$table->string('description');
$table->float('size');
$table->bigInteger('created_by')->unsigned();
$table->string('status')->default('pending');
$table->boolean('deleted');
$table->timestamps();
$table->foreign('created_by')
->references('id')
->on('users')
->onDelete('cascade');
}
Than I have two Controllers: User and Recipe
Recipe have
public function user()
{
return $this->belongsTo(\App\User::class);
}
and User have
public function recipes()
{
return $this->hasMany(\App\Recipe::class);
}
actual output looks like this (RecipesController):
$recipes = Recipe::latest()->paginate($perPage);
return view('admin.recipes.index', compact('recipes'));
everything looks OK but column created_by contain users primary key witch is integer. How can I display users name? This is something like inner join but is it possible to do that in eloquent? Or I completely misunderstanding those public functions in a Model?
Your user relationship in your Recipe model is missing the foreignKey:
public function user()
{
return $this->belongsTo(\App\User::class, 'created_by');
}
You can then eager load the users with your recipes in the controller:
$recipes = Recipe::with('user')->latest()->paginate($perPage);
return view('admin.recipes.index', compact('recipes'));
And finally you can access the user in the view:
#foreach($recipes as $recipe)
{{ $recipe->user->name }}
#endforeach
You can read more about the inverse of the one-to-many relationship in the docs.
Ok so I need to get data from the table this way but I would like to get
Vehicle Maker name too
I tried using join or
just doing auth()->user()->vehicles->VehicleMaker but it doesn't work
Migration of Table Vehicle
Schema::create('vehicles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id');
$table->bigInteger('category_id');
$table->bigInteger('vehicle_maker_id');
$table->string('name');
$table->double('price', 8 , 2);
$table->year('manufacture_year');
$table->bigInteger('mileage');
$table->string('vehicle_image');
$table->boolean('admin_verification')->nullable();
$table->timestamps();
});
Migration of vehicle_makers
Schema::create('vehicle_makers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
Controller
public function show(){
$vehicles = auth()->user()->vehicles; -- what shoul i add here
return view('/home', [
'vehicles' => $vehicles
]);
}
Edit
I forget to mention that I already made a relationship and they work in artisan tinker when I try to do something like this:
Vehicles->find(1)->VehicleMaker
What I want is to do is
auth()->user()->vehicles and get vehicle teble with vahicle_maker name not id so some kind of join that would work in this case
Okay base on Laravel Model Relationship.
You first need to create a migration.
Vihicle Migration
Schema::create('vehicles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('vehicle_maker_id');
$table->string('name');
$table->double('price', 8 , 2);
$table->year('manufacture_year');
$table->bigInteger('mileage');
$table->string('vehicle_image');
$table->boolean('admin_verification')->nullable();
$table->timestamps();
});
I used unisignedBigInteger to determine it is a foreign key or you can also use index().
In your model you should place what relation ship you will use. In your case I assumed you are using One To Many Relationship. So that your user model should look like this:
User Model
...
public function vehicles() {
return $this->hasMany(Vehicle::class);
}
So that you can use the convention auth()->user()->vehicles;.
Note: the auth()->user()->vehicles; return a array of object you can loop it in foreach.
Vehicle Model
public function user() {
return $this->belongsTo(User::class);
}
In when you have this in your model you can use it 2 way.
In your controller you can call the relationship of those 2.
Controller
$vehicles = auth()->user()->vehicles;
dd($vehicles);
INFO
You can also refer to this tutorial.
EDIT
Controller
$vehicles = auth()->user()->vehicles();
foreach($vehicles as $vehicle) {
dd($vehicle->VehicleMaker);
}
Note: The $vehicles is returning an array of object. So you can loop it through foreach loop to throw a single instance.
There should be a relationship between the user and vehicles then another relationship between vehicles and vehicle_makers. If you already created your models(Vehicle, VehicleMaker) with their migrations, You can do the following
//add this to your User model.
public function vehicle(){
return this->belongsTo(App\Vehicle);
}
// add this to your Vehicle model
public function user(){
return this->hasMany(App\Vehicle); // implying that a user can have many vehicles
}
//add this to your vehicleMaker model
public function vehicle(){
return this->belongsTo(App\Vehicle);
}
When that is done, you can use Laravel's lazy loading to fetch relationships. You can do something like
$vehicles = auth()->user()->vehicle
return view('/home', [
'vehicles' => $vehicles
]);
I'm writing a sample ecommerce website with Laravel 5.
I have 2 Tables:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->float('price');
$table->integer('category_id');
$table->timestamps();
});
and
Schema::create('featureds', function (Blueprint $table) {
$table->integer('product_id')->unique()->unsigned();
});
Schema::table('featureds', function($table) {
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
Models
class Product extends Model
{
public function category(){
return $this->belongsTo('App\Category');
}
}
class Featured extends Model
{
public function product(){
return $this->hasOne('App\Product', 'product_id');
}
}
Then, I have a Controller, where I take 4 featured products:
$featured_products = Featured::limit(4)->get();
return view('home', ['featured_products' => $featured_products]);
Now, I'm trying to show these featured products in my view. If i show the product_id from the Featured model, everything is ok:
#foreach($featured_products as $prod)
{{$prod->product_id}}
#endforeach
But I want to take the name of the product referred by the featured. I tried this way:
#foreach($featured_products as $prod)
#foreach($prod as $p)
{{$p->name}}
#endforeach
#endforeach
Because featured_products (in the controller) seems to be a collection, but it doesn't work!
In your Featured model, you have a relationship in method product() when you want to access the relation from the view, you could call the method name as property, in you case, you have a method named product() so you have to call product property like this:
#foreach($featured_products as $prod)
{{ $prod->product->name }}
#endforeach
It will automatically write the product name based on the relationship you have configured in the model.
Reference: https://laravel.com/docs/5.2/eloquent-relationships
Edit:
Sorry my bad, I guess you are defining a wrong relation, your Product model, should have a featured() method which uses hasOne relation, while Featured model should have a product() method using belongsTo relation. So in you App\Featured model, you have to define the relation like this:
return $this->belongsTo('App\Product');
And in your App\Product model you should define relation like so:
return $this->hasOne('App\Featured');
Hope it works
In Laravel 5.1 I can see that table column relationships can be set-up in 2 ways:
1) Defining Foreign Keys in the Migration table.
2) Defining the Eloquent relationships in the Models.
I have read the documentations and I am still confused on the following:
Do I need to use both or only 1 is needed?
Is it wrong to use both at the same time? Or does it make it
redundant or cause conflicts?
What is the benefit of using Eloquent relationships without mentioning the
Foreign keys in migration column?
What is the difference?
These are the codes I have now. Its still unclear to me if I need to remove the foreign keys I have set-up in my migration file.
Migration:
public function up()
{
Schema::create('apps', function (Blueprint $table) {
$table->increments('id');
$table->string('app_name');
$table->string('app_alias');
$table->timestamps();
$table->engine = 'InnoDB';
});
// This is the second Migration table
Schema::create('app_roles', function (Blueprint $table) {
$table->increments('id');
$table->integer('app_id')->unsigned()->index();
$table->integer('user_id')->unsigned()->index();
$table->integer('role_id')->unsigned()->index();
$table->engine = 'InnoDB';
$table->unique(array('app_id', 'user_id'));
$table->foreign('app_id')
->references('id')
->on('apps')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade');
});
}
Model with Eloquent Relationships:
// App Model
class App extends Model
{
public function appRoles() {
return $this->hasMany('App\Models\AppRole');
}
}
// AppRole Model
class AppRole extends Model
{
public function app() {
return $this->belongsTo('App\Models\App');
}
public function user() {
return $this->belongsTo('App\User');
}
public function role() {
return $this->belongsTo('App\Models\Role');
}
}
// User Model
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
.....
public function appRole() {
return $this->belongsToMany('App\Models\AppRole');
}
}
// Role Model
class Role extends EntrustRole
{
public function appRole() {
return $this->hasMany('App\Models\AppRole');
}
}
Can someone help me understand this please?
Both go hand in hand. One is in-complete without the other one. If you want your relations to work properly, you need to define both of these things.
If you have just defined the foreign key in a migration file, the relation would work just in case you write a raw query. It won't work on your models since, you haven't written anything about relations in your models.
So, as soon as you write hasMany in one of your models, and corresponding function in the other model, only then your models know about each other, and then you can successfully query things through your model as well as in your database.
Also note that if you have properly defined relations through hasMany and belongsTo in your models, but haven't provided foreign key in the table of the model who belongsTo other table, your relations won't work.
In short, both are equally compulsory.
Eloquent assumes the foreign key of the relationship based on the model name. In this case, the App model is automatically assumed to have an app_id foreign key, so in your migrations you do not need to specify:
$table->foreign('app_id')
->references('id')
->on('apps')
->onDelete('cascade');
Documentation