My model:
class Product extends Model
{
protected $table = 'Products';
protected $fillable = ['product_code', 'type', 'name', 'description', 'price', 'discount', 'image', 'image_alt'];
public function products()
{
return $this->hasMany('App\ProductSpecifics');
}
}
My controller code:
public function product($code)
{
$product = Product::where('product_code',$code)->get();
$productSpec = ProductSpecifics::where('product_code',$code)->get();
var_dump($product->name);
return view('pages.product', compact('product','productSpec'));
}
Error:
Property [name] does not exist on this collection instance
I tried using dd($product) and I noticed that there is a lot of information in there.
How do I extract only the attributes like name,type & etc ?
try this
dd($product->toArray());
Related
I am a beginner in Laravel and am stuck with sending the data from pivot table to view. I have two models one is "Supplier" and another is "Product" which I have created as follows:
Supplier.php
class Supplier extends Model
{
protected $keyType = 'string';
public $incrementing = false;
public function products()
{
return $this->belongsToMany(
'App\Product',
'inward_stock',
'supplier_id',
'product_id'
)->withPivot(
'product_dimension',
'quantity',
'expiry_date',
'type',
'QR_code',
'sales_price',
'arrival_date',
'occassion',
'discount_percentage',
'payment_date',
'cost',
'paid_status',
'sku'
)->withTimestamps();
}
}
Product.php
class Product extends Model
{
protected $keyType = 'string';
protected $primaryKey = 'product_id';
public $incrementing = false;
public function suppliers()
{
return $this->belongsToMany('App\Supplier');
}
}
Now I want to access all the data from the pivot table named as "inward_stock" from my controller and want to send it to the view named "inward-stock-list", I have created "inwardstockController" for that purpose and want to know how to send it to the view using that controller.
I think the most effective way is to create model for pivot table:
class InwardStock extends Model
{
protected $table = 'inward_stock';
public function supplier()
{
return $this->belongsTo('App\Supplier', 'supplier_id', 'supplier_id');
}
public function product()
{
return $this->belongsTo('App\Product', 'product_id', 'product_id');
}
}
inwardstockController:
$inwardStocks = InwartStock::with(['product', 'supplier'])->get();
View:
#foreach($inwardStocks as $inwardStock)
{{ $inwardStock->supplier->id }}
{{ $inwardStock->product->id }}
#endforeach
I have these models with their related db tables,at the moment I can retrieve all the requirement
Requirement::all()
but I just have a list of foreigns key (destination_id,applier_id,doc_id). How can i retrieve directly the row connected to that foreigns key?
class Requirement extends Model
{
protected $fillable = [
'required',
'destination_id',
'applier_id',
'doc_id'
];
public function destination()
{
return $this->belongsTo(Destination::class);
}
public function applier()
{
return $this->belongsTo(Applier::class);
}
public function doc()
{
return $this->belongsTo(Doc::class);
}
}
class Doc extends Model
{
protected $fillable = [
'type',
'description',
'note'
];
public function requirements()
{
return $this->hasMany(Requirement::class);
}
}
class Destination extends Model
{
protected $fillable = [
'country',
'passying_country',
'transfer_conditions',
'passing_conditions'
];
public function requirements()
{
return $this->hasMany(Requirement::class);
}
}
You can call with() function instead of all(). So if you try this following :
$requirements = Requirement::with('destination', 'applier', 'doc')->get();
Make it dd($requirements) and look the output.
Hope it will work.
I am using Laravel 5.3 and this model:
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use SoftDeletes;
protected $table = 'categories';
protected $fillable = [
'name',
'slug',
'description',
'thumbnail',
'parent',
'created_by'
];
protected $hidden = [
'created_by'
];
protected $dates = ['deleted_at'];
public static function getSubcategories($category)
{
return Category::whereParent(Category::whereSlug($category)->first()->id)->get();
}
}
It works perfectly on my localhost server, but when I upload it on my production server, it outputs following error:
Trying to get property of non-object (on line ....)
It is on this line:
return Category::whereParent(Category::whereSlug($category)->first()->id)->get();
(Lines are hidden, because this model has much more functions and would be too long for this post)
Full trace:
its because the Category::whereSlug($category)->first() is returning null and that you are trying to get id of that null. so its as the error states that you are trying to get a property of non object.
I see that you are trying to get self reference category. you could so it this way as a relationships.
//children
public function categories()
{
return $this->hasMany(self::class, 'parent');
}
//parent
public function parent()
{
return $this->belongsTo(self::class, 'parent');
}
if you want to select recursively you could add this too.
public function parentRecursive()
{
return $this->parent()->with('parentRecursive');
}
public function categoriesRecursive()
{
return $this->categories()->with('categoriesRecursive');
}
im new to Laravel and have a relationship question.
The goal is to get all News where news.page_id = page.id AND page.pagetype_id = pagetype.id WHERE pagetype.component = news AND page.app_id = 1
class News extends Model
{
protected $table = 'news';
protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
}
class Page extends Model
{
protected $table = 'pages';
protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];
public function pagetype() {
return $this->belongsTo('App\Models\PageType', 'pagetype_id');
}
}
class PageType extends Model
{
protected $table = 'pagetypes';
protected $fillable = ['pagetype', 'component', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->belongsToMany('App\Models\Page', 'pagetypes', 'id', 'id');
}
}
// now i need All News Items where page.pagetype_id = pagetypes.id and patchtypes.component = news
// First Attempts are
Page::whereHas('pagetype', function ($q) {
$q->where('component', 'news');
})->where(['app_id' => 1])->get();
// result is all Pages which has the proper component news.
This is what i have tried yet, but in my attempt i'll only receive the proper pages but of course not the news.
My "current" solution is to get all the pages and then loop through News::where('page_id', $myPageId). But im pretty sure its possible to get a proper relationship to get also news.
I cant do any other model since there are many different pagetypes and components aswell.
Thanks so far.
You need to add relationship function to news model.
public function pages() {
return $this->belongsTo('App\Models\Page');
}
And call it through News model.
News::with('pages')->where('app_id',1);
First off all I think that you are wrong with you PageType relation
class PageType extends Model
{
protected $table = 'pagetypes';
protected $fillable = ['pagetype', 'component', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->hasMany('App\Models\Page');
// if i understood you correctly you haven't got any pivot table
}
}
Then you should link your News and Page like so
News.php
class News extends Model
{
protected $table = 'news';
protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->belongsTo('App\Models\Page');
}
}
Page.php
class Page extends Model
{
protected $table = 'pages';
protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];
public function pagetype() {
return $this->belongsTo('App\Models\PageType');
}
public function news() {
return $this->hasMany('App\Models\News');
}
}
Then you can achieve your goal
News::whereHas('page', function($q) use($appId) {
$q->where('app_id',$appId);
})->whereHas('page.pagetype', function($q) {
$q->where('component', 'news');
})->get();
How can I add value to a ORM related variable?
It contains a news and comments Model, as shown below:
class News extends Model {
protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $table = 'news';
protected $fillable = array(
'id',
'name',
'category',
'type',
'datetime',
'shortdesc',
'desciption'
);
public $timestamps = false;
public function comments()
{
return $this->hasMany('App\Comments');
}
Comments table
class Comments extends Model {
protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $table = 'comments';
protected $fillable = array(
'id',
'news_id',
'name',
'description'
);
public $timestamps = false;
public function news()
{
return $this->belongsTo('App\News','news_id');
}};
And when I try to add this values it creates only News table
without related Comments table.(Doesn't throw any exception, just creates News table)
public function AddData()
{
$row=new News;
$row->name="Myname";
$row->category="vcc";
$row->type="2";
$row->comments()->news_id="1";
$row->comments()->name="someval";
$row->save();
return view::make('first_view');
}
There is a problem when you are inserting your related Comment model. There are many ways to solve your problem.
Solution I prefer to use:
public function AddData()
{
// Create news model
$news = News::create([
'name' => 'Some name',
'category' => 'somecategory',
....
]);
// Create comment through news model
// news_id will automatically be inserted
$comment = $news->comments()->create([
'name' => 'some name'
]);
}
See documentation