how to get the value of foreign key in Laravel - php

I have a problem with Laravel model relationships. I need to let users create new trucks. However, I need to store manufacturer's field as an id, not a title. So I decided to make two tables (manufacturers and trucks) that have one to many relationship (manufacturers have multiple trucks while one truck has one manufacturer).
Here's the migrations files.
Manufacturers table:
public function up()
{
Schema::create('manufacturers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('manufacturer');
$table->timestamps();
});
}
Trucks table:
public function up()
{
Schema::create('trucks', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('make_id');
$table->unsignedInteger('year');
$table->string('owner');
$table->unsignedInteger('owner_number')->nullable();
$table->text('comments')->nullable();
$table->foreign('make_id')->references('id')->on('manufacturers');
$table->timestamps();
});
}
Manufacturer.php model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Manufacturer extends Model
{
/**
* #var string
*/
protected $table = 'manufacturers';
/**
* #var array
*/
protected $fillable = [
'manufacturer',
];
public function trucks(){
return $this->hasMany(Truck::class);
}
}
Truck.php model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Truck extends Model
{
/**
* #var string
*/
protected $table = 'trucks';
/**
* #var array
*/
protected $fillable = [
'make_id', 'year', 'owner', 'owner_number', 'comments',
];
public function manufacturer(){
return $this->belongsTo(Manufacturer::class);
}
}
Controller file:
public function index()
{
$trucks = Truck::all();
return view('trucks.index')->with('trucks', $trucks);
}
index.blade.php
#foreach($trucks as $truck)
<tbody>
<tr>
<td>{{$truck->make_id}}</td> //I need this one to show manufacturers title
<td>{{$truck->year}}</td>
<td>{{$truck->owner}}</td>
<td>{{$truck->owner_number}}</td>
<td>{{$truck->comments}}</td>
</tr>
</tbody>
#endforeach
This view now shows the id. What I need to do to show manufacturers title(manufacturers.manufacturer) instead of the id? Thank you all in advance!

Your foreign key for manufacturer in trucks table is not manufacturer_id. In this case you need to declare it in your models:
return $this->belongsTo(Manufacturer::class, 'make_id' )
And
return $this->hasMany(Truck::class, 'make_id' )

Related

NULL value when trying to get an author name of created subcategory using relations on Laravel

I want to print which user is an author of a subcategory but when I do dd(). I get a NULL value.
User model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
/**
* 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 mutated to dates.
*
* #var array
*/
protected $dates = [
'created_at',
'updated_at'
];
}
Category model:
class Category extends Model
{
public function subcategory()
{
return $this->hasMany(Subcategory::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Subcategory Model:
class Subcategory extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Function where I want to print an author of subcategory.
public function show(Category $category)
{
$subcategories = $category->subcategory->user->name;
dd($subcategory);
return view('subcategories', compact('subcategories '));
}
DD output: NULL also when I do dd($category) In "relations" i can see my "subcategory" but there is not "user" relation anywhere. Please help :/
Migrations:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->text('description');
$table->timestamps();
});
}
public function up()
{
Schema::create('subcategories', function (Blueprint $table) {
$table->increments('id');
$table->string('description')->nullable();
$table->foreign('category_id')->references('id')->on('categories')
->onUpdate('cascade')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
Requests:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ItemRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
];
}
}
View:
#foreach($subcategories as $subcategory)
<li>{{$subcategory->user->name}}</li>
#endforeach
Your Category model defines the relation as subcategories, but you are calling $category->subcategory. Instead, call the relation as you have it defined:
$subs = $category->subcategories;
Also, since the relation is one to many, you will need to loop through each subcategory in order to retrieve the user. Example:
$user_names = array();
foreach ($subs as $s) {
$user_names[] = $s->user->name
}
dd($user_names);
Or, get the nth subcategory, etc.:
dd($category->subcategories->first()->user->name);
//Or
dd($category->subcategories->last()->user->name);
//Etc.
Edit:
Change your show method to this:
public function show(Category $category)
{
$subcategories = $category->subcategory;
dd($subcategories);
return view('subcategories', compact('subcategories'));
}
If You are still unable to see the user relation in each subcategory, try it with this:
$subcategories = $category->subcategory()->with('user')->get();
subcategory does not have a user() relationship, only category has.so the user's name would be:
$category->user->name

Laravel Categories

I'm learning php with laravel and trying to implement categories and subcategories for multiple on my project.
For Example: I have Books, Mobiles in my project
Books has its own categories and subcategories. Same goes for Mobile.
I have added another table with relation
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->unique(array('product_id', 'category_id'));
// foreign key constraints are optional (but pretty useful, especially with cascade delete
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
Category Database Schema
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id')->nullable()->index();
$table->string('title')->unique();
$table->string('slug')->unique();
$table->string('description')->nullable();
$table->string('keywords')->nullable();
$table->timestamps();
});
category.php (Model)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
class Category extends Model
{
use Sluggable;
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'categories';
/**
* Attributes that should be mass-assignable.
*
* #var array
*/
protected $fillable = [
'parent_id', 'title', 'description', 'slug'
];
public function parent()
{
return $this->belongsTo('Category', 'parent_id');
}
public function children()
{
return $this->hasMany('Category', 'parent_id');
}
public function categoryProduct(){
return $this->belongsToMany('CategoryProduct');
}
public function product(){
return $this->belongsToMany('Product');
}
}
Am i doing the right way as i didn't find a proper tutorial for this kind of approach. Do i need to create a CategoryProduct.php model and reference
public function categories(){
return $this->belongsToMany('Category');
}
public function products(){
return $this->belongsToMany('Product');
}
No, you don't need to create a model for a pivot table. Eloquent has many methods to make working with pivot tables a breeze. In your case you don't need a model.
But sometimes, when you're working with pivot table additional columns a lot it's a good idea to create a model for a pivot table.

laravel eloquent relation one to many returns null

The product data always return null when i get the incoming_goods data (belongsTo).
Here is my Product Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $guarded = [
'id', 'created_at', 'updated_at', 'deleted_at',
];
public function transaction_details()
{
return $this->hasMany('App\Transaction_detail');
}
public function incoming_goods()
{
return $this->hasMany('App\Incoming_good');
}
}
Here is my Incoming_good Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Incoming_good extends Model
{
protected $guarded = [
'id', 'created_at', 'updated_at',
];
public function product()
{
return $this->belongsTo('App\Product');
}
}
And here is my migration of that two table:
products table Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50);
$table->integer('price');
$table->integer('stock')->nullable();
$table->integer('available');
$table->string('image1', 190)->nullable();
$table->string('image2', 190)->nullable();
$table->string('image3', 190)->nullable();
$table->string('image4', 190)->nullable();
$table->string('image5', 190)->nullable();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
incoming_goods migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableIncomingGoods extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('incoming_goods', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id');
$table->integer('stock');
$table->text('note')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('incoming_goods');
}
}
Here is my code to show incomong_goods data and product (relation belongsTo):
$data = Incoming_good::select('id', 'stock', 'note', 'created_at')->with('product')->get();
I've try to use alies, but still it return the product data null. Hope you can help me :)
In order to match up the eager loaded Products with the Incoming_goods, Laravel needs the foreign key to be selected. Since you did not include the foreign key (product_id) in the select list, Laravel can't match up the related records after retrieving them. So, all your product relationships will be empty. Add in the foreign key to the select list, and you should be good.
$data = Incoming_good::select('id', 'product_id', 'stock', 'note', 'created_at')
->with('product')
->get();

Laravel relationship returning null when tryying to fetch type using foreign key

I am trying to fetch the type of user using the foreign key in the users table i.e. user_types_id but when I do it I just get null and cant get into the function userType in User Model. Any help would be much appreciated.
Thank you in advance. I have provided related models and tables
Controller
public function dashboard() {
$userType = UserType::all();
$id = Auth::user()->id;
var_dump($id); // returns id
$users = User::find($id);
var_dump($user->user_types_id); // returns user_type_id in users table
if($users->userType){
var_dump($users->userType->types); // error is in here. Not taking userType.
} else {
echo 'does not exit';
}
die();
return view('dashboard', compact('users'));
}
User Model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\UserType;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function userType() {
return $this->belongsTo(UserType::class);
}
}
UserType Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class UserType extends Model
{
protected $fillable=['types'];
public function users() {
return $this->hasMany(User::class);
}
}
User Table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_types_id')->unsigned()->index();
$table->string('username')->unique();
$table->string('password');
$table->string('salt');
$table->rememberToken();
$table->timestamps();
});
}
UserType Table
public function up()
{
Schema::create('user_types', function (Blueprint $table) {
$table->increments('id');
$table->string('types');
$table->timestamps();
});
}
You've named your relation userType, therefore Eloquent assumes that the foreign key is called user_type_id, not user_types_id.
Replace
return $this->belongsTo(UserType::class);
with
return $this->belongsTo(UserType::class, 'user_types_id');
to tell Eloquent the name of foreign key column and it should work.

Eloquent eager loading doesn't work with my naming convention

I have been stuck for most of the day getting an empty array any time I eager loaded product images while requesting products in my controller in Laravel.
public function ProductImages() {
return $this->hasMany('App\ProductImage', 'product_id'); // this matches the Eloquent model
}
I changed my code to make the FK 'test' and suddenly it has started returning the appropriate data I want back. I put the FK back to product_id but again am back to an empty array. Below are My product Model ProductImages Model and the migrations for both with the call Im making in the controlelr
Product Model
class Product extends Model
{
protected $fillable = array('name', 'url_name', 'sku', 'description', 'short_description', 'enabled', 'track_inventory', 'stock_level', 'allow_backorder', 'updated_user_id' );
//protected $hidden = array('id');
// LINK THIS MODEL TO OUR DATABASE TABLE ---------------------------------
// Database table is not called my_products
protected $table = 'products';
// each product HAS many product images
public function ProductImages() {
return $this->hasMany('App\ProductImage', 'productId'); // this matches the Eloquent model
}
}
Product Images Model
class ProductImage extends Model
{
protected $fillable = array('name', 'description', 'path', 'sort_order', 'product_id');
// DEFINE RELATIONSHIPS --------------------------------------------------
// each attribute HAS one product
public function Product() {
return $this->belongsTo('App\Product', 'id'); // this matches the Eloquent model
}
}
Product Migration
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('url');
$table->string('sku');
$table->string('description');
$table->string('short_description');
$table->integer('enabled');
$table->integer('track_inventory');
$table->integer('stock_level');
$table->integer('allow_backorder');
$table->dateTime('updated_user_id');
$table->timestamps();
});
}
}
Product Images Migration
class CreateProductImagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('product_images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->string('path');
$table->integer('sort_order');
$table->integer('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products');
$table->timestamps();
});
}
}
Product Controller Snippet
public function index()
{
//
$Products = Product::with('ProductImages','productTypes')->get();
//dd($Products);
return response()->json( $Products, 200);
}
If you could help me understand why this strange behavior is happening i would be very grateful.

Categories