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
Related
[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');
}
}
I have these three models in Laravel-5.8
GoalType
class GoalType extends Model
{
protected $table = 'goal_types';
protected $fillable = [
'id',
'name',
];
public function goals()
{
return $this->hasMany('App\Models\Goal');
}
public function ratinglimit()
{
return $this->belongsTo(App\Models\RatingLimit);
}
}
RatingLimit
class RatingLimit extends Model
{
protected $table = 'rating_limits';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'max_rating',
];
public function goaltype()
{
return $this->hasOne('App\Models\GoalType','goal_type_id','id');
}
}
Goal
class Goal extends Model
{
protected $table = 'goals';
protected $fillable = [
'id',
'goal_type_id',
'goal_title',
];
public function goaltype()
{
return $this->belongsTo('App\Models\GoalType','goal_type_id');
}
}
Controller
$goals = Goal::where('is_approved', 3)->get();
A RatingLimit is associated with one GoalType (hasOne) and GoalType has many Goal
When I tried to render max_rating
index.blade
{{$goal->goaltype->ratinglimit->max_rating}}
I got this error:
Trying to get property 'max_rating' of non-object
When I changed it to:
{{ $goal->goaltype->ratinglimit ? $goal->goaltype->ratinglimit->max_rating : '-' }}
it deisplays '-', and the error is no more there. But max_rating in the database is not empty
How do I resolve this?
Thanks
->get() returns a collection! so you should loop it through foreach to have access to each item and then you can use your relation:
#foreach ($goals as $g)
{{$goal->goaltype->ratinglimit->max_rating}}
#endforeach
if i have this models relationship
Claims : this table hasMany(Refunds)
Refunds: with data of various request. this table belongsTo(Claims) AND belongsToMany(Services)
Services: with list of services. this table belongsToMany(Refunds)
Refunds-Services: bridge table for refunds and services
Claims model
class Claims extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'dossier',
'date_cla',
];
public function refunds()
{
return $this->hasMany(Refunds::class);
}
}
Refunds model
class Refunds extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'date_ref',
'status_ref',
];
public function services()
{
return $this->belongsToMany(Services::class)->withPivot(['services_id','services_amount','services_status']);
}
public function claims()
{
return $this->belongsTo(Claims::class,'claims_id');
}
}
Services model
class Services extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'code',
'name',
];
public function refunds()
{
return $this->belongsToMany(Refunds::class);
}
}
and in my controller this method
if ($request->ajax()) {
$dossier = request('dossier');
$claim = Claims::with('refunds')
->where('dossier', '=', $dossier)->first();
$
$view = view('pages.modify', compact('claim'));
$sections = $view->renderSections()['table'];
return $sections;
}
how can insert in the Controller the relationship between Refunds and Service to use the pivot (service_amount is in the Refunds-Services table)
<li>- {{ $item->pivot->services_amount }}</li>
Because now in the view cannot see this relationship
Thx
You can use Nested Eager Loading
$claim = Claims::with('refunds.services')
->where('dossier', '=', $dossier)->first();
As per the documentation:
To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:
$books = App\Book::with('author.contacts')->get();
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
I want to populate Every CustomerEvent with the Customer related to the CustomerEvent.
When I Loop through the object and call to $customerevent->customer foreach object I can get the customer related to that event but Can I populate the all objects in the main object without looping through every single event ?
I want to do something like this:
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
Here my code:
Table 1: "events"
id, customer_id
Model for Table 1 "CustomerEvent":
<?php
class CustomerEvent extends Eloquent{
protected $guarded = ['id'];
public $table = "event";
protected $softDelete = true;
public function scopeTypeOne($query)
{
$followUps = $query->where('type_id', '=', '1');
}
public function Customers()
{
return $this->belongsTo('Customer', 'customer_id');
}
}
Table 2: "customers"
id
Model for Table 2 "Customers":
<?php class Customer extends BaseModel{
protected $guarded = ['id'];
}
EventController:
public function index()
{
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
dd($customersWithTypeOne);
}
From you database scheme I see customer has many events, so I would recommend to define this relationship in you Customer model.
class Customer extends BaseModel{
protected $guarded = ['id'];
public function events()
{
return $this->hasMany('CustomerEvent', 'customer_id');
}
}
Then you will be able to query customers with events:
$customersWithTypeOne = Customer::whereHas('events', function($query){
$query->where('type_id', 1);
})->get()
Maybe Ardent can help you: https://github.com/laravelbook/ardent
It's an extension for Eloquent models and very popular.