How to access the parent data eloquent join - laravel-5

i have two tables products and orders
i am able to access all data in the table Order but can't access products product_name
below is the Order model
class Order extends Model
{
// Table name
protected $tablename = 'orders';
// primary key
public $primaryKey = 'id';
public function products(){
return $this->belongsTo('App\Product');
}
}
Product model
class Product extends Model
{
// Table name
protected $tablename = 'products';
// primary key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
public function orders(){
return $this->hasMany('App\Order');
}
}
in my controller i have this OrderController
class OrdersController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(){
$orderedProducts = Order::with('products')->paginate(5);
return view::make('orders.index')->with('products',$orderedProducts);
}
}
now trying to access the product_name on the view fails
#foreach ($products as $product)
<tr>
<td>{{'#'.++$i}}</td>
<td>{{$product->product_name}}</td> //fails to get this from products table
<td>{{$product->quantity}}</td>
<td>{{$product->totalPrice}}</td>
<td>{{$product->totalPrice * $product->quantity }}</td>
<td>{{$product->created_at->diffForHumans()}}</td>
<td>{{$product->orderStatus}}</td>
</tr>
#endforeach

Need to do so
Controller:
public function index(){
$order = Order::with('products')->paginate(5);
return view::make('orders.index')->with('products',$order->products);
}
or
Controller:
public function index(){
$order = Order::with('products')->paginate(5);
return view::make('orders.index')->with('order',$order);
}
View:
#foreach ($order->products as $product)
#if(!empty($product))
<tr>
<td>{{'#'.$loop->iteration}}</td>
<td>{{$product->product_name}}</td> //fails to get this from products table
<td>{{$product->quantity}}</td>
<td>{{$product->totalPrice}}</td>
<td>{{$product->totalPrice * $product->quantity }}</td>
<td>{{$product->created_at->diffForHumans()}}</td>
<td>{{$product->orderStatus}}</td>
</tr>
#endif
#endforeach

i finally figured it by changing my Order model method from products to product because it was having the same name with protected $tablename = 'products'; in the Product model then after that i referenced the related method product in the Order model directly in the view as follow <td>{{$product->product->product_name}}</td>
the complete working code now below
Order model where i changed the method from products to product
class Order extends Model
{
// Table name
protected $tablename = 'orders';
// primary key
public $primaryKey = 'id';
public function product(){
return $this->belongsTo('App\Product');
}
}
Product model
class Product extends Model
{
// Table name
protected $tablename = 'products';
// primary key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
public function orders(){
return $this->hasMany('App\Order');
}
}
Controller
public function index(){
$order = Order::with('product')->paginate(5);
return view::make('orders.index')->with('order',$order);
}
lastly on the view where i make reference to the method product in the Order model
#foreach ($order as $product)
#if (!empty($product))
<tr>
<td>{{$product->product->product_name}}</td> **//Here is the referencing**
<td>{{$product->quantity}}</td>
<td>{{$product->totalPrice}}</td>
<td>{{$product->totalPrice * $product->quantity }}</td>
<td>{{$product->created_at->diffForHumans()}}</td>
<td>{{$product->orderStatus}}</td>
</tr>
#endif
#endforeach

Related

How to display multiple or single images for a product page in Laravel?

[enter image description here][1]
I'm trying to store multiple images in the database. I have products table and images tables. I have faced the issue for image not showing the product list page. I am trying to more tutorials codes unfortunately my issues not solve. Please check the below cods and help me the problem solve.
Products Model
class Products extends Model
{
use HasFactory;
protected $table = 'cw_products';
protected $fillable =
['product_id','product_title','product_details','product_cid'];
public function images()
{
return $this->hasMany(ProductsImage::class, 'images_pdct_id', 'images_id');
}
}
ProductsImage Model
class ProductsImage extends Model
{
use HasFactory;
protected $table = 'cw_products_images';
protected $fillable =
['images_id','images_pdct_id','images_image','images_thumbnail'];
public function products()
{
return $this->belongsTo(Products::class, 'product_id');
}
}
ProductsController
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Products;
use App\Models\ProductsImage;
use Hash;
use Session;
use File;
use Image;
class ProductsController extends Controller
{
public function index(Request $request)
{
$data = array();
//$products = Products::where('product_status', '>=', 0)->orderBy('product_id', 'desc')->paginate(30); // Replace 100
$products = Products::with('images')->where('product_status', '>=', 0)->orderBy('product_id', 'desc')->paginate(30);
//DD($products);
return view('webadmin.pages.products',compact('data','products'));
}
}
Products List View Page
#if($products->count())
#foreach($products as $product)
<tr style="color:rgb(26, 25, 25);">
<td>
#foreach($product->images as $pimages)
<!--$pdctImage = $product->images[0]->images_thumbnail;
dd($pdctImage); -->
<img src="../../assets/img/products/thumbnail/{{ $pimages->images_thumbnail }}" alt="ProjectImage" class="img-thumbnail" style="width: 50%; height: 50px;"/>
#endforeach
</td>
<td>{{ $product->product_title }}</td>
</tr>
#endforeach
#endif
The relation ships are defined using foreign key and local key like this - return $this->hasMany(Comment::class, 'foreign_key', 'local_key'); -https://laravel.com/docs/9.x/eloquent-relationships . So you would need to change relationship in both models.
class Products extends Model
{
use HasFactory;
protected $table = 'cw_products';
protected $fillable =
['product_id','product_title','product_details','product_cid'];
public function images()
{
return $this->hasMany(ProductsImage::class, 'images_pdct_id', 'product_id');
}
}
class ProductsImage extends Model
{
use HasFactory;
protected $table = 'cw_products_images';
protected $fillable =
['images_id','images_pdct_id','images_image','images_thumbnail'];
public function products()
{
return $this->belongsTo(Products::class, 'product_id','images_pdct_id');
}
}

table data relation is not entered, encountered an error Method Illuminate \ Database \ Eloquent \ Collection :: links does not exist

Ticket.php
Protected $table = 'tickets';
Protected $fillable = ['user_id','kategori_id','judul','prioritas_id','status_id','message','file_tambahan'];
public function user()
{
return $this->belongsTo(User::class);
}
User.php
protected $table = 'users';
protected $fillable = [
'avatar','nama_lengkap', 'email', 'password',
];
public function getAvatar()
{
if(!$this->avatar)
{
return asset('images/default.png');
}
return asset('images/'.$this->avatar);
}
public function ticket()
{
return $this->hasMany(Ticket::class);
}
TicketController.php
use App\Model\Ticket;
use App\Model\User;
use App\Model\Kategori;
use App\Model\Prioritas;
use App\Model\Status;
class TicketController extends Controller
{
public function index()
{
$data = Ticket::with('User','Kategori','Prioritas','Status')->get();
return view('admin.crud_ticket.index', compact('data'));
}
index.blade.php
#foreach($data as $d)
<tr role="row" class="odd">
<td>{{ $d->user->nama_lengkap }}</td>
</tr>
#endforeach
{{ $data->links('vendor.pagination.custom') }}
I keep getting the same error over and over again, I do relationships between tables
namely in the user table, category, priority, status.
and cause an error like this, if you have a solution please help me
Method Illuminate\Database\Eloquent\Collection::links does not exist. (View: C:\xampp\htdocs\Helpdesk\resources\views\admin\crud_ticket\index.blade.php)

BelongsToMany of Laravel 5.4 does not work

I am creating a table where it displays a list of requests, I have a relation between the ID's 'erp_createdid' and 'erp_productid'. To display the name of the products, I created a belongsToMany, in which I specify my two 'ID's'.
Order model
class Order extends Model
{
protected $table = 'erp_order';
protected $fillable = ['erp_createdid'];
protected $primaryKey = 'erp_orderid';
public function description()
{
return $this->belongsToMany('App\Description','erp_order_product', 'erp_createdid', 'erp_productid');
}
}
Description Model
class Description extends Model
{
protected $table = 'erp_product_description';
protected $primaryKey = 'erp_productid';
protected $fillable = ['erp_name'];
public $timestamps = false;
public function order()
{
return $this->belongsToMany('App\Order', 'erp_order_product', 'erp_createdid', 'erp_productid');
}
Table
<td>#foreach($orders->description as $des)
{{$des->erp_name}}
#endforeach
</td>
But the values in the table are not displayed, any suggestions?
I think you have the parameters on Order's belongsToMany in an incorrect order.
Try this:
public function description()
{
return $this->belongsToMany('App\Description','erp_order_product', 'erp_productid', 'erp_createdid');
}
Also try updating your foreach like this:
Oh OK, try this:
#foreach($orders as $order)
#foreach($order->description as $description)
{{ $description->erp_name }}
#endforeach
#endforeach

get data from multiple relations in laravel eloquent

I have the following tables pharmacies,categories,medicines and I am using laravel
the relations are like this
pharmacy have many medicines and the medicine belongs to one category
the medicines table have pharmacy_id and category_id columns + other columns
I want to show a pharmacy by id and it should return an object of pharmacy with categories, each category have object of medicines in this pharmacy. If there is no medicine in any category, then it should not be returned.
I think its a model relations issue
any idea could be useful
the category model
class Category extends Model
{
protected $table = 'categories';
public function pharmacies()
{
return $this->belongsToMany(Pharmacy::class, 'pharmacy_category', 'category_id', 'id');
}
public function medicines()
{
return $this->hasMany(Medicine::class);
}
}
the pharmacy model
class Pharmacy extends Model
{
use SoftDeletes;
protected $table = 'pharmacies';
protected $appends = ['favourite'];
public function categories()
{
return $this->belongsToMany(Category::class,'pharmacy_category','pharmacy_id','id');
}
public function getFavouriteAttribute()
{
if (!Auth::check()) {
return 0;
}
return (FavouritePharmacy::where('user_id', Auth::user()->id)->where('pharmacy_id', $this->id)->count() == 1) ? 1 : 0;
}
}
the medicine model
class Medicine extends Model
{
protected $appends = ['favourite'];
public function orders()
{
return $this->belongsToMany(Order::class);
}
public function getFavouriteAttribute()
{
if (!Auth::check()) {
return 0;
}
return (FavouriteMedicine::where('user_id', Auth::user()->id)->where('medicine_id', $this->id)->count() == 1) ? 1 : 0;
}
}
If you want to display pharmacy info, categories with medicines, with these relationships I'd do this:
$pharmacy = Pharmacy::find($id);
$categoriesWithMedicines = Category::whereHas('medicines', function($q) use($id) {
$q->where('pharmacy_id', $id);
})
->with(['medicines' => function($q) use($id) {
$q->where('pharmacy_id', $id);
}])
->get();
Then in a view, you'll have a pharmacy object and a list of categories with medicines which belong to the pharmacy:
#foreach ($categoriesWithMedicines as $category)
{{ $category->name }}
#foreach ($category->medicines as $medicine)
{{ $medicine->name }}
#endforeach
#endforeach

Laravel Eloquent for display row from subject table?

i have three database tables
category (id,name)
subcategory (id,name,category_id) foreign_key category_id on table category(id).
subject(id,name,subcategory_id) foreign_key subcategory_id on table subcategory (id).
i want a row containing the following -
subject_id subject_name category_name subcategory_id
how to do this using eloquent .and if approach is wrong .please suggest a good method to achieve the same .
Assuming you have the following models:
// Category Model
class Category extends \Eloquent {
protected $table = "category";
public function subcategory(){
$this->hasMany('Subcategory','category_id');
}
}
// Subcategory Model
class Subcategory extends \Eloquent {
protected $table = "subcategory";
public function category(){
$this->belongsTo('Category', 'category_id');
}
pubic function subject(){
$this->hasMany('Subject', 'subcategory_id');
}
}
// Subject model
class Subject extends \Eloquent {
protected $table = "subject";
public function subcategory(){
$this->belongsTo('Subcategory','subcategory_id');
}
}
You can get the data in your controller as follows:
// for subject with id 1
public function getOneRow(){
$subject = Subject::with('subcategory.category')->findOrFail(1);
//subject_id = $subject->id
//subject_name = $subject->name
//subcategory_id = $subject->subcategory->id
//category_name = $subject->subcategory->category->name
return array("subject_name"=>$subject->name, "category_name"=>$subject->subcategory->id, "subcategory_name"=>$subject->subcategory->category->name);
}
// for all subjects
public function getOneRow(){
$subjects = Subject::with('subcategory.category')->all();
$out = array();
foreach($subjects as $subject){
// each row
//subject_id = $subject->id
//subject_name = $subject->name
//subcategory_id = $subject->subcategory->id
//category_name = $subject->subcategory->category->name
$out[] = array("subject_name"=>$subject->name, "category_name"=>$subject->subcategory->id, "subcategory_name"=>$subject->subcategory->category->name);
}
return $out;
}
Edit for Laravel 5.1
Your models will be defined differently. Here's an example. Or follow the docs:
// Category Model Laravel 5.1
use Illuminate\Database\Eloquent\Model;
class Category extends Model {
protected $table = "category";
public function subcategory(){
$this->hasMany('Subcategory','category_id');
}
}
Edit: Completed the functions with return statements as requested in comment

Resources