Laravel - chaining any method on any model instance results in an error all of a sudden












1














Ok so all of a sudden my dev environment broke, I'll try to explain what happened in points:




  • I was adding a new migration and a new model/controller, when all of a sudden my page didn't load anymore saying that I am trying to load a non-object.

  • I went to inspect inside php artisan tinker, I tried to run a normal query similar to the one on the mentioned page like:

  • $p = Product::first();


  • $p->mainCategory; (which is a method on Product.php),

  • Normally it would return an instance of AppCategory.php with all of its parameters (all relationships are defined and they were working correctly), but instead I got null returned;

  • So I thought, maybe that product doesn't have a matching Category, but then I queried the database with the category_id available on the Product instance, and I found the database record.


  • Eventually, I thought maybe the new migration broke the database somehow, so I deleted the database and imported an sql dump from the server (in the process I also made a git reset --hard to the previous commit, just to be sure everything is as it was).

  • I tried the same query again, and I got null again.

  • So right now, I can get database records for models, but I cannot for the life of me run any method available for that model instance, and of course I can't fetch any relationship.


  • IMPORTANT (I think)

  • When I run something like $p->mainCategory(), I am expecting an instance of a belongsTo relationship, instead I get an error:



BadMethodCallException with message 'Call to undefined method IlluminateDatabaseQueryBuilder::mainCategory()'






  • MAYBE this is the key to solving this issue, because if I try to chain any method on a model instance like above, I get that error.

  • I don't know why it is treated as an instance of QueryBuilder, it should be an instance of AppProduct

  • Here is where it gets even weirder, this happens to all of my models, except one that's called Restaurant.php, that's the only one that I can perform queries/add methods normally to its instace, All others are broken.

  • Below I will put my Product.php, Restaurant.php, and the products_table migration as a reference.


Product.php



<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Product extends Model
{
public function isEnabled()
{
return $this->pro_active == 2;
}

public function getName()
{
return $this->{'pro_name_' . app()->getLocale()};
}


public function offer()
{
return $this->hasOne( AppProductOffer::class );
}


public function cats()
{
return $this->hasMany( AppProductCategory::class );
}


public function mainCategory()
{
return $this->belongsTo( AppCategory::class, 'pro_main_cat_id', 'id' );
}


public function subCat()
{
return $this->belongsTo( AppSubCategory::class, 'pro_sub_cat_id', 'id' );
}

public function subsubcategory()
{
return $this->belongsTo(AppSubsubcategory::class, 'pro_sub_sub_cat_id');
}


Restaurant.php



<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Restaurant extends Model
{
public function products()
{
return $this->belongsToMany(AppProduct::class, 'restaurant_products');
}

public function orders()
{
return $this->hasMany(AppRestaurantOrder::class);
}


public function isAvailable()
{
return $this->status == 1;
}


public function isOpen()
{
return $this->open == 1;
}


public function getLogo()
{
return $this->logo ?? asset('setting/logo/2018-06-10.logo.jpg');
}


public function getName()
{
if ( app()->getLocale() == 'ar' ) {
return $this->name_ar ?? $this->name;
}

return $this->name_en ?? $this->name;
}
}


products_table migration:



<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateProductsTable extends Migration {

/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('pro_special');
$table->string('pro_active');
$table->integer('pro_main_cat_id')->nullable();
$table->integer('pro_sub_cat_id')->nullable();
$table->integer('pro_sub_sub_cat_id')->nullable();
$table->integer('pro_country_id')->nullable();
$table->integer('pro_city_id')->nullable();
$table->integer('pro_price');
$table->integer('pro_discount_percentage')->nullable();
$table->integer('pro_after_discount')->nullable();
$table->string('pro_image');
$table->string('pro_name_ar');
$table->string('pro_name_en');
$table->string('pro_desc_ar')->nullable();
$table->string('pro_desc_en')->nullable();
$table->string('pro_small_desc_ar')->nullable();
$table->string('pro_small_desc_en')->nullable();
$table->string('pro_slogen_ar')->nullable();
$table->string('pro_slogen_en')->nullable();
$table->string('pro_view')->nullable();
$table->integer('user_id')->default(0);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('products');
}

}


As you can see they are all normal classes, they should function similarly, but for unknown reason, they just don't.



Edit



Here's dd(Product::first()); :



AppProduct {#907
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:29 [
"id" => 4
"pro_special" => "2"
"pro_active" => "2"
"pro_main_cat_id" => 2
"pro_sub_cat_id" => 2
"pro_sub_sub_cat_id" => 3
"pro_country_id" => 5
"pro_city_id" => 7
"pro_price" => 0.45
"pro_discount_percentage" => 0
"pro_after_discount" => 0.0
"pro_image" => "upload/product/1529115234.Bruot.jpg"
"pro_name_ar" => "خبز عربي 6 أرغفة"
"pro_name_en" => "ARABISCHES BROT 6 STÜCK"
"pro_desc_ar" => "<p>خبز عربي 6 أرغفة</p>rn"
"pro_desc_en" => "<p>ARABISCHES BROT 6 STÜCK</p>rn"
"pro_small_desc_ar" => "الوصف عربى"
"pro_small_desc_en" => "الوصف المانى"
"pro_slogen_ar" => "خبز-عربي-6-أرغفة"
"pro_slogen_en" => "arabisches-brot-6-stck"
"pro_view" => null
"user_id" => 0
"prod_count" => 988
"pro_keywords_ar" => ""
"pro_keywords_en" => ""
"pro_meta_desc_ar" => ""
"pro_meta_desc_en" => ""
"created_at" => "2018-06-14 06:46:34"
"updated_at" => "2018-11-30 20:06:58"
]
#original: array:29 [
"id" => 4
"pro_special" => "2"
"pro_active" => "2"
"pro_main_cat_id" => 2
"pro_sub_cat_id" => 2
"pro_sub_sub_cat_id" => 3
"pro_country_id" => 5
"pro_city_id" => 7
"pro_price" => 0.45
"pro_discount_percentage" => 0
"pro_after_discount" => 0.0
"pro_image" => "upload/product/1529115234.Bruot.jpg"
"pro_name_ar" => "خبز عربي 6 أرغفة"
"pro_name_en" => "ARABISCHES BROT 6 STÜCK"
"pro_desc_ar" => "<p>خبز عربي 6 أرغفة</p>rn"
"pro_desc_en" => "<p>ARABISCHES BROT 6 STÜCK</p>rn"
"pro_small_desc_ar" => "الوصف عربى"
"pro_small_desc_en" => "الوصف المانى"
"pro_slogen_ar" => "خبز-عربي-6-أرغفة"
"pro_slogen_en" => "arabisches-brot-6-stck"
"pro_view" => null
"user_id" => 0
"prod_count" => 988
"pro_keywords_ar" => ""
"pro_keywords_en" => ""
"pro_meta_desc_ar" => ""
"pro_meta_desc_en" => ""
"created_at" => "2018-06-14 06:46:34"
"updated_at" => "2018-11-30 20:06:58"
]
#relations:
#hidden:
#visible:
#appends:
#fillable:
#guarded: array:1 [
0 => "*"
]
#dates:
#dateFormat: null
#casts:
#touches:
#observables:
#with:
#morphClass: null
+exists: true
+wasRecentlyCreated: false


dd(Category::first());



AppCategory {#907
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:11 [
"id" => 2
"cat_name_ar" => " المواد الغذائية"
"cat_name_en" => " Lebensmittel"
"cat_order" => "1"
"cat_image" => "upload/category/maincat/1529112273.categ.jpg"
"cat_restura" => null
"cat_slogen_ar" => "المواد-الغذائية"
"cat_slogen_en" => "lebensmittel"
"status" => "1"
"created_at" => "2018-06-10 09:26:24"
"updated_at" => "2018-10-11 21:26:22"
]
#original: array:11 [
"id" => 2
"cat_name_ar" => " المواد الغذائية"
"cat_name_en" => " Lebensmittel"
"cat_order" => "1"
"cat_image" => "upload/category/maincat/1529112273.categ.jpg"
"cat_restura" => null
"cat_slogen_ar" => "المواد-الغذائية"
"cat_slogen_en" => "lebensmittel"
"status" => "1"
"created_at" => "2018-06-10 09:26:24"
"updated_at" => "2018-10-11 21:26:22"
]
#relations:
#hidden:
#visible:
#appends:
#fillable:
#guarded: array:1 [
0 => "*"
]
#dates:
#dateFormat: null
#casts:
#touches:
#observables:
#with:
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}


Relevant route in routes.php:



Route::auth();
Route::get('/', 'frontFrontController@index');


FrontController.php



<?php

namespace AppHttpControllersfront;

use IlluminateHttpRequest;
use AppHttpControllersController;
use IlluminateSupportFacadesSession;
use IlluminateSupportFacadesRedirect;
use IlluminateSupportFacadesValidator;
use AppSlider;
use AppHomeAdvert;
use AppCategory;
use AppProduct;
use AppContact;
use AppPage;
use AppCountry;
use AppCity;
use AppSubcategory;

class FrontController extends Controller {

public function index() {
$sliders = Slider::orderBy('slider_order', 'asc')->get();
$homeadvert = HomeAdvert::first();
$homecategories = Category::where('status', '1')->orderBy('cat_order', 'desc')->with('products')->get();
$homeproducts = $homecategories->map(function ($item) {
return ($item->products()->limit(8))->get();
});

$homelatestproducts = Product::where('pro_active', 2)->orderBy('id', 'desc')->get()->take(8);


$homecategorysearch = Category::where('status', '1')->orderBy('cat_order', 'desc')->get();
$homecountrysearch = Country::orderBy('country_order', 'desc')->get();
$pages = AppPage::all();

return view('frontend.layouts.index', compact('pages', 'homecategorysearch', 'homecountrysearch','homelatestproducts', 'homeproducts', 'sliders', 'homeadvert', 'homecategories'));
}

}









share|improve this question
























  • No, the error is happening because it is treating $product as an instance of Query Builder, which makes sense, there is no mainCat() method on a query builder instance, but, this should be an instance of AppProduct, which does have a mainCat(); method. (I edited the word in the error because it was written incorrectly, mainCategory() not mainCat())
    – Omar Tarek
    yesterday








  • 1




    The error quite evidently says you have not finished your query with get(), first() or all()... it is still a builder and no result. -- Personal recommendation on the side: you should use an extra table for field translations that allows for additional languages without having to change code. Your current database structure violates the first normal form.
    – Namoshek
    yesterday










  • what is returned from get_class(AppProduct::first()) in tinker?
    – Amade
    yesterday












  • Do you have data in the product table? Because there isn't first() method ll return null. Please check if you have data in the table.
    – Manuel Eduardo Romero
    yesterday










  • @Namoshek If you read carefully, I specifically used Product::first(); as my query, as for the second note on the database I know that, I got hired while the application is already live, so right now it we're working on other things, but thanks for the recommendation.
    – Omar Tarek
    yesterday
















1














Ok so all of a sudden my dev environment broke, I'll try to explain what happened in points:




  • I was adding a new migration and a new model/controller, when all of a sudden my page didn't load anymore saying that I am trying to load a non-object.

  • I went to inspect inside php artisan tinker, I tried to run a normal query similar to the one on the mentioned page like:

  • $p = Product::first();


  • $p->mainCategory; (which is a method on Product.php),

  • Normally it would return an instance of AppCategory.php with all of its parameters (all relationships are defined and they were working correctly), but instead I got null returned;

  • So I thought, maybe that product doesn't have a matching Category, but then I queried the database with the category_id available on the Product instance, and I found the database record.


  • Eventually, I thought maybe the new migration broke the database somehow, so I deleted the database and imported an sql dump from the server (in the process I also made a git reset --hard to the previous commit, just to be sure everything is as it was).

  • I tried the same query again, and I got null again.

  • So right now, I can get database records for models, but I cannot for the life of me run any method available for that model instance, and of course I can't fetch any relationship.


  • IMPORTANT (I think)

  • When I run something like $p->mainCategory(), I am expecting an instance of a belongsTo relationship, instead I get an error:



BadMethodCallException with message 'Call to undefined method IlluminateDatabaseQueryBuilder::mainCategory()'






  • MAYBE this is the key to solving this issue, because if I try to chain any method on a model instance like above, I get that error.

  • I don't know why it is treated as an instance of QueryBuilder, it should be an instance of AppProduct

  • Here is where it gets even weirder, this happens to all of my models, except one that's called Restaurant.php, that's the only one that I can perform queries/add methods normally to its instace, All others are broken.

  • Below I will put my Product.php, Restaurant.php, and the products_table migration as a reference.


Product.php



<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Product extends Model
{
public function isEnabled()
{
return $this->pro_active == 2;
}

public function getName()
{
return $this->{'pro_name_' . app()->getLocale()};
}


public function offer()
{
return $this->hasOne( AppProductOffer::class );
}


public function cats()
{
return $this->hasMany( AppProductCategory::class );
}


public function mainCategory()
{
return $this->belongsTo( AppCategory::class, 'pro_main_cat_id', 'id' );
}


public function subCat()
{
return $this->belongsTo( AppSubCategory::class, 'pro_sub_cat_id', 'id' );
}

public function subsubcategory()
{
return $this->belongsTo(AppSubsubcategory::class, 'pro_sub_sub_cat_id');
}


Restaurant.php



<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Restaurant extends Model
{
public function products()
{
return $this->belongsToMany(AppProduct::class, 'restaurant_products');
}

public function orders()
{
return $this->hasMany(AppRestaurantOrder::class);
}


public function isAvailable()
{
return $this->status == 1;
}


public function isOpen()
{
return $this->open == 1;
}


public function getLogo()
{
return $this->logo ?? asset('setting/logo/2018-06-10.logo.jpg');
}


public function getName()
{
if ( app()->getLocale() == 'ar' ) {
return $this->name_ar ?? $this->name;
}

return $this->name_en ?? $this->name;
}
}


products_table migration:



<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateProductsTable extends Migration {

/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('pro_special');
$table->string('pro_active');
$table->integer('pro_main_cat_id')->nullable();
$table->integer('pro_sub_cat_id')->nullable();
$table->integer('pro_sub_sub_cat_id')->nullable();
$table->integer('pro_country_id')->nullable();
$table->integer('pro_city_id')->nullable();
$table->integer('pro_price');
$table->integer('pro_discount_percentage')->nullable();
$table->integer('pro_after_discount')->nullable();
$table->string('pro_image');
$table->string('pro_name_ar');
$table->string('pro_name_en');
$table->string('pro_desc_ar')->nullable();
$table->string('pro_desc_en')->nullable();
$table->string('pro_small_desc_ar')->nullable();
$table->string('pro_small_desc_en')->nullable();
$table->string('pro_slogen_ar')->nullable();
$table->string('pro_slogen_en')->nullable();
$table->string('pro_view')->nullable();
$table->integer('user_id')->default(0);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('products');
}

}


As you can see they are all normal classes, they should function similarly, but for unknown reason, they just don't.



Edit



Here's dd(Product::first()); :



AppProduct {#907
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:29 [
"id" => 4
"pro_special" => "2"
"pro_active" => "2"
"pro_main_cat_id" => 2
"pro_sub_cat_id" => 2
"pro_sub_sub_cat_id" => 3
"pro_country_id" => 5
"pro_city_id" => 7
"pro_price" => 0.45
"pro_discount_percentage" => 0
"pro_after_discount" => 0.0
"pro_image" => "upload/product/1529115234.Bruot.jpg"
"pro_name_ar" => "خبز عربي 6 أرغفة"
"pro_name_en" => "ARABISCHES BROT 6 STÜCK"
"pro_desc_ar" => "<p>خبز عربي 6 أرغفة</p>rn"
"pro_desc_en" => "<p>ARABISCHES BROT 6 STÜCK</p>rn"
"pro_small_desc_ar" => "الوصف عربى"
"pro_small_desc_en" => "الوصف المانى"
"pro_slogen_ar" => "خبز-عربي-6-أرغفة"
"pro_slogen_en" => "arabisches-brot-6-stck"
"pro_view" => null
"user_id" => 0
"prod_count" => 988
"pro_keywords_ar" => ""
"pro_keywords_en" => ""
"pro_meta_desc_ar" => ""
"pro_meta_desc_en" => ""
"created_at" => "2018-06-14 06:46:34"
"updated_at" => "2018-11-30 20:06:58"
]
#original: array:29 [
"id" => 4
"pro_special" => "2"
"pro_active" => "2"
"pro_main_cat_id" => 2
"pro_sub_cat_id" => 2
"pro_sub_sub_cat_id" => 3
"pro_country_id" => 5
"pro_city_id" => 7
"pro_price" => 0.45
"pro_discount_percentage" => 0
"pro_after_discount" => 0.0
"pro_image" => "upload/product/1529115234.Bruot.jpg"
"pro_name_ar" => "خبز عربي 6 أرغفة"
"pro_name_en" => "ARABISCHES BROT 6 STÜCK"
"pro_desc_ar" => "<p>خبز عربي 6 أرغفة</p>rn"
"pro_desc_en" => "<p>ARABISCHES BROT 6 STÜCK</p>rn"
"pro_small_desc_ar" => "الوصف عربى"
"pro_small_desc_en" => "الوصف المانى"
"pro_slogen_ar" => "خبز-عربي-6-أرغفة"
"pro_slogen_en" => "arabisches-brot-6-stck"
"pro_view" => null
"user_id" => 0
"prod_count" => 988
"pro_keywords_ar" => ""
"pro_keywords_en" => ""
"pro_meta_desc_ar" => ""
"pro_meta_desc_en" => ""
"created_at" => "2018-06-14 06:46:34"
"updated_at" => "2018-11-30 20:06:58"
]
#relations:
#hidden:
#visible:
#appends:
#fillable:
#guarded: array:1 [
0 => "*"
]
#dates:
#dateFormat: null
#casts:
#touches:
#observables:
#with:
#morphClass: null
+exists: true
+wasRecentlyCreated: false


dd(Category::first());



AppCategory {#907
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:11 [
"id" => 2
"cat_name_ar" => " المواد الغذائية"
"cat_name_en" => " Lebensmittel"
"cat_order" => "1"
"cat_image" => "upload/category/maincat/1529112273.categ.jpg"
"cat_restura" => null
"cat_slogen_ar" => "المواد-الغذائية"
"cat_slogen_en" => "lebensmittel"
"status" => "1"
"created_at" => "2018-06-10 09:26:24"
"updated_at" => "2018-10-11 21:26:22"
]
#original: array:11 [
"id" => 2
"cat_name_ar" => " المواد الغذائية"
"cat_name_en" => " Lebensmittel"
"cat_order" => "1"
"cat_image" => "upload/category/maincat/1529112273.categ.jpg"
"cat_restura" => null
"cat_slogen_ar" => "المواد-الغذائية"
"cat_slogen_en" => "lebensmittel"
"status" => "1"
"created_at" => "2018-06-10 09:26:24"
"updated_at" => "2018-10-11 21:26:22"
]
#relations:
#hidden:
#visible:
#appends:
#fillable:
#guarded: array:1 [
0 => "*"
]
#dates:
#dateFormat: null
#casts:
#touches:
#observables:
#with:
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}


Relevant route in routes.php:



Route::auth();
Route::get('/', 'frontFrontController@index');


FrontController.php



<?php

namespace AppHttpControllersfront;

use IlluminateHttpRequest;
use AppHttpControllersController;
use IlluminateSupportFacadesSession;
use IlluminateSupportFacadesRedirect;
use IlluminateSupportFacadesValidator;
use AppSlider;
use AppHomeAdvert;
use AppCategory;
use AppProduct;
use AppContact;
use AppPage;
use AppCountry;
use AppCity;
use AppSubcategory;

class FrontController extends Controller {

public function index() {
$sliders = Slider::orderBy('slider_order', 'asc')->get();
$homeadvert = HomeAdvert::first();
$homecategories = Category::where('status', '1')->orderBy('cat_order', 'desc')->with('products')->get();
$homeproducts = $homecategories->map(function ($item) {
return ($item->products()->limit(8))->get();
});

$homelatestproducts = Product::where('pro_active', 2)->orderBy('id', 'desc')->get()->take(8);


$homecategorysearch = Category::where('status', '1')->orderBy('cat_order', 'desc')->get();
$homecountrysearch = Country::orderBy('country_order', 'desc')->get();
$pages = AppPage::all();

return view('frontend.layouts.index', compact('pages', 'homecategorysearch', 'homecountrysearch','homelatestproducts', 'homeproducts', 'sliders', 'homeadvert', 'homecategories'));
}

}









share|improve this question
























  • No, the error is happening because it is treating $product as an instance of Query Builder, which makes sense, there is no mainCat() method on a query builder instance, but, this should be an instance of AppProduct, which does have a mainCat(); method. (I edited the word in the error because it was written incorrectly, mainCategory() not mainCat())
    – Omar Tarek
    yesterday








  • 1




    The error quite evidently says you have not finished your query with get(), first() or all()... it is still a builder and no result. -- Personal recommendation on the side: you should use an extra table for field translations that allows for additional languages without having to change code. Your current database structure violates the first normal form.
    – Namoshek
    yesterday










  • what is returned from get_class(AppProduct::first()) in tinker?
    – Amade
    yesterday












  • Do you have data in the product table? Because there isn't first() method ll return null. Please check if you have data in the table.
    – Manuel Eduardo Romero
    yesterday










  • @Namoshek If you read carefully, I specifically used Product::first(); as my query, as for the second note on the database I know that, I got hired while the application is already live, so right now it we're working on other things, but thanks for the recommendation.
    – Omar Tarek
    yesterday














1












1








1







Ok so all of a sudden my dev environment broke, I'll try to explain what happened in points:




  • I was adding a new migration and a new model/controller, when all of a sudden my page didn't load anymore saying that I am trying to load a non-object.

  • I went to inspect inside php artisan tinker, I tried to run a normal query similar to the one on the mentioned page like:

  • $p = Product::first();


  • $p->mainCategory; (which is a method on Product.php),

  • Normally it would return an instance of AppCategory.php with all of its parameters (all relationships are defined and they were working correctly), but instead I got null returned;

  • So I thought, maybe that product doesn't have a matching Category, but then I queried the database with the category_id available on the Product instance, and I found the database record.


  • Eventually, I thought maybe the new migration broke the database somehow, so I deleted the database and imported an sql dump from the server (in the process I also made a git reset --hard to the previous commit, just to be sure everything is as it was).

  • I tried the same query again, and I got null again.

  • So right now, I can get database records for models, but I cannot for the life of me run any method available for that model instance, and of course I can't fetch any relationship.


  • IMPORTANT (I think)

  • When I run something like $p->mainCategory(), I am expecting an instance of a belongsTo relationship, instead I get an error:



BadMethodCallException with message 'Call to undefined method IlluminateDatabaseQueryBuilder::mainCategory()'






  • MAYBE this is the key to solving this issue, because if I try to chain any method on a model instance like above, I get that error.

  • I don't know why it is treated as an instance of QueryBuilder, it should be an instance of AppProduct

  • Here is where it gets even weirder, this happens to all of my models, except one that's called Restaurant.php, that's the only one that I can perform queries/add methods normally to its instace, All others are broken.

  • Below I will put my Product.php, Restaurant.php, and the products_table migration as a reference.


Product.php



<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Product extends Model
{
public function isEnabled()
{
return $this->pro_active == 2;
}

public function getName()
{
return $this->{'pro_name_' . app()->getLocale()};
}


public function offer()
{
return $this->hasOne( AppProductOffer::class );
}


public function cats()
{
return $this->hasMany( AppProductCategory::class );
}


public function mainCategory()
{
return $this->belongsTo( AppCategory::class, 'pro_main_cat_id', 'id' );
}


public function subCat()
{
return $this->belongsTo( AppSubCategory::class, 'pro_sub_cat_id', 'id' );
}

public function subsubcategory()
{
return $this->belongsTo(AppSubsubcategory::class, 'pro_sub_sub_cat_id');
}


Restaurant.php



<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Restaurant extends Model
{
public function products()
{
return $this->belongsToMany(AppProduct::class, 'restaurant_products');
}

public function orders()
{
return $this->hasMany(AppRestaurantOrder::class);
}


public function isAvailable()
{
return $this->status == 1;
}


public function isOpen()
{
return $this->open == 1;
}


public function getLogo()
{
return $this->logo ?? asset('setting/logo/2018-06-10.logo.jpg');
}


public function getName()
{
if ( app()->getLocale() == 'ar' ) {
return $this->name_ar ?? $this->name;
}

return $this->name_en ?? $this->name;
}
}


products_table migration:



<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateProductsTable extends Migration {

/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('pro_special');
$table->string('pro_active');
$table->integer('pro_main_cat_id')->nullable();
$table->integer('pro_sub_cat_id')->nullable();
$table->integer('pro_sub_sub_cat_id')->nullable();
$table->integer('pro_country_id')->nullable();
$table->integer('pro_city_id')->nullable();
$table->integer('pro_price');
$table->integer('pro_discount_percentage')->nullable();
$table->integer('pro_after_discount')->nullable();
$table->string('pro_image');
$table->string('pro_name_ar');
$table->string('pro_name_en');
$table->string('pro_desc_ar')->nullable();
$table->string('pro_desc_en')->nullable();
$table->string('pro_small_desc_ar')->nullable();
$table->string('pro_small_desc_en')->nullable();
$table->string('pro_slogen_ar')->nullable();
$table->string('pro_slogen_en')->nullable();
$table->string('pro_view')->nullable();
$table->integer('user_id')->default(0);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('products');
}

}


As you can see they are all normal classes, they should function similarly, but for unknown reason, they just don't.



Edit



Here's dd(Product::first()); :



AppProduct {#907
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:29 [
"id" => 4
"pro_special" => "2"
"pro_active" => "2"
"pro_main_cat_id" => 2
"pro_sub_cat_id" => 2
"pro_sub_sub_cat_id" => 3
"pro_country_id" => 5
"pro_city_id" => 7
"pro_price" => 0.45
"pro_discount_percentage" => 0
"pro_after_discount" => 0.0
"pro_image" => "upload/product/1529115234.Bruot.jpg"
"pro_name_ar" => "خبز عربي 6 أرغفة"
"pro_name_en" => "ARABISCHES BROT 6 STÜCK"
"pro_desc_ar" => "<p>خبز عربي 6 أرغفة</p>rn"
"pro_desc_en" => "<p>ARABISCHES BROT 6 STÜCK</p>rn"
"pro_small_desc_ar" => "الوصف عربى"
"pro_small_desc_en" => "الوصف المانى"
"pro_slogen_ar" => "خبز-عربي-6-أرغفة"
"pro_slogen_en" => "arabisches-brot-6-stck"
"pro_view" => null
"user_id" => 0
"prod_count" => 988
"pro_keywords_ar" => ""
"pro_keywords_en" => ""
"pro_meta_desc_ar" => ""
"pro_meta_desc_en" => ""
"created_at" => "2018-06-14 06:46:34"
"updated_at" => "2018-11-30 20:06:58"
]
#original: array:29 [
"id" => 4
"pro_special" => "2"
"pro_active" => "2"
"pro_main_cat_id" => 2
"pro_sub_cat_id" => 2
"pro_sub_sub_cat_id" => 3
"pro_country_id" => 5
"pro_city_id" => 7
"pro_price" => 0.45
"pro_discount_percentage" => 0
"pro_after_discount" => 0.0
"pro_image" => "upload/product/1529115234.Bruot.jpg"
"pro_name_ar" => "خبز عربي 6 أرغفة"
"pro_name_en" => "ARABISCHES BROT 6 STÜCK"
"pro_desc_ar" => "<p>خبز عربي 6 أرغفة</p>rn"
"pro_desc_en" => "<p>ARABISCHES BROT 6 STÜCK</p>rn"
"pro_small_desc_ar" => "الوصف عربى"
"pro_small_desc_en" => "الوصف المانى"
"pro_slogen_ar" => "خبز-عربي-6-أرغفة"
"pro_slogen_en" => "arabisches-brot-6-stck"
"pro_view" => null
"user_id" => 0
"prod_count" => 988
"pro_keywords_ar" => ""
"pro_keywords_en" => ""
"pro_meta_desc_ar" => ""
"pro_meta_desc_en" => ""
"created_at" => "2018-06-14 06:46:34"
"updated_at" => "2018-11-30 20:06:58"
]
#relations:
#hidden:
#visible:
#appends:
#fillable:
#guarded: array:1 [
0 => "*"
]
#dates:
#dateFormat: null
#casts:
#touches:
#observables:
#with:
#morphClass: null
+exists: true
+wasRecentlyCreated: false


dd(Category::first());



AppCategory {#907
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:11 [
"id" => 2
"cat_name_ar" => " المواد الغذائية"
"cat_name_en" => " Lebensmittel"
"cat_order" => "1"
"cat_image" => "upload/category/maincat/1529112273.categ.jpg"
"cat_restura" => null
"cat_slogen_ar" => "المواد-الغذائية"
"cat_slogen_en" => "lebensmittel"
"status" => "1"
"created_at" => "2018-06-10 09:26:24"
"updated_at" => "2018-10-11 21:26:22"
]
#original: array:11 [
"id" => 2
"cat_name_ar" => " المواد الغذائية"
"cat_name_en" => " Lebensmittel"
"cat_order" => "1"
"cat_image" => "upload/category/maincat/1529112273.categ.jpg"
"cat_restura" => null
"cat_slogen_ar" => "المواد-الغذائية"
"cat_slogen_en" => "lebensmittel"
"status" => "1"
"created_at" => "2018-06-10 09:26:24"
"updated_at" => "2018-10-11 21:26:22"
]
#relations:
#hidden:
#visible:
#appends:
#fillable:
#guarded: array:1 [
0 => "*"
]
#dates:
#dateFormat: null
#casts:
#touches:
#observables:
#with:
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}


Relevant route in routes.php:



Route::auth();
Route::get('/', 'frontFrontController@index');


FrontController.php



<?php

namespace AppHttpControllersfront;

use IlluminateHttpRequest;
use AppHttpControllersController;
use IlluminateSupportFacadesSession;
use IlluminateSupportFacadesRedirect;
use IlluminateSupportFacadesValidator;
use AppSlider;
use AppHomeAdvert;
use AppCategory;
use AppProduct;
use AppContact;
use AppPage;
use AppCountry;
use AppCity;
use AppSubcategory;

class FrontController extends Controller {

public function index() {
$sliders = Slider::orderBy('slider_order', 'asc')->get();
$homeadvert = HomeAdvert::first();
$homecategories = Category::where('status', '1')->orderBy('cat_order', 'desc')->with('products')->get();
$homeproducts = $homecategories->map(function ($item) {
return ($item->products()->limit(8))->get();
});

$homelatestproducts = Product::where('pro_active', 2)->orderBy('id', 'desc')->get()->take(8);


$homecategorysearch = Category::where('status', '1')->orderBy('cat_order', 'desc')->get();
$homecountrysearch = Country::orderBy('country_order', 'desc')->get();
$pages = AppPage::all();

return view('frontend.layouts.index', compact('pages', 'homecategorysearch', 'homecountrysearch','homelatestproducts', 'homeproducts', 'sliders', 'homeadvert', 'homecategories'));
}

}









share|improve this question















Ok so all of a sudden my dev environment broke, I'll try to explain what happened in points:




  • I was adding a new migration and a new model/controller, when all of a sudden my page didn't load anymore saying that I am trying to load a non-object.

  • I went to inspect inside php artisan tinker, I tried to run a normal query similar to the one on the mentioned page like:

  • $p = Product::first();


  • $p->mainCategory; (which is a method on Product.php),

  • Normally it would return an instance of AppCategory.php with all of its parameters (all relationships are defined and they were working correctly), but instead I got null returned;

  • So I thought, maybe that product doesn't have a matching Category, but then I queried the database with the category_id available on the Product instance, and I found the database record.


  • Eventually, I thought maybe the new migration broke the database somehow, so I deleted the database and imported an sql dump from the server (in the process I also made a git reset --hard to the previous commit, just to be sure everything is as it was).

  • I tried the same query again, and I got null again.

  • So right now, I can get database records for models, but I cannot for the life of me run any method available for that model instance, and of course I can't fetch any relationship.


  • IMPORTANT (I think)

  • When I run something like $p->mainCategory(), I am expecting an instance of a belongsTo relationship, instead I get an error:



BadMethodCallException with message 'Call to undefined method IlluminateDatabaseQueryBuilder::mainCategory()'






  • MAYBE this is the key to solving this issue, because if I try to chain any method on a model instance like above, I get that error.

  • I don't know why it is treated as an instance of QueryBuilder, it should be an instance of AppProduct

  • Here is where it gets even weirder, this happens to all of my models, except one that's called Restaurant.php, that's the only one that I can perform queries/add methods normally to its instace, All others are broken.

  • Below I will put my Product.php, Restaurant.php, and the products_table migration as a reference.


Product.php



<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Product extends Model
{
public function isEnabled()
{
return $this->pro_active == 2;
}

public function getName()
{
return $this->{'pro_name_' . app()->getLocale()};
}


public function offer()
{
return $this->hasOne( AppProductOffer::class );
}


public function cats()
{
return $this->hasMany( AppProductCategory::class );
}


public function mainCategory()
{
return $this->belongsTo( AppCategory::class, 'pro_main_cat_id', 'id' );
}


public function subCat()
{
return $this->belongsTo( AppSubCategory::class, 'pro_sub_cat_id', 'id' );
}

public function subsubcategory()
{
return $this->belongsTo(AppSubsubcategory::class, 'pro_sub_sub_cat_id');
}


Restaurant.php



<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Restaurant extends Model
{
public function products()
{
return $this->belongsToMany(AppProduct::class, 'restaurant_products');
}

public function orders()
{
return $this->hasMany(AppRestaurantOrder::class);
}


public function isAvailable()
{
return $this->status == 1;
}


public function isOpen()
{
return $this->open == 1;
}


public function getLogo()
{
return $this->logo ?? asset('setting/logo/2018-06-10.logo.jpg');
}


public function getName()
{
if ( app()->getLocale() == 'ar' ) {
return $this->name_ar ?? $this->name;
}

return $this->name_en ?? $this->name;
}
}


products_table migration:



<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateProductsTable extends Migration {

/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('pro_special');
$table->string('pro_active');
$table->integer('pro_main_cat_id')->nullable();
$table->integer('pro_sub_cat_id')->nullable();
$table->integer('pro_sub_sub_cat_id')->nullable();
$table->integer('pro_country_id')->nullable();
$table->integer('pro_city_id')->nullable();
$table->integer('pro_price');
$table->integer('pro_discount_percentage')->nullable();
$table->integer('pro_after_discount')->nullable();
$table->string('pro_image');
$table->string('pro_name_ar');
$table->string('pro_name_en');
$table->string('pro_desc_ar')->nullable();
$table->string('pro_desc_en')->nullable();
$table->string('pro_small_desc_ar')->nullable();
$table->string('pro_small_desc_en')->nullable();
$table->string('pro_slogen_ar')->nullable();
$table->string('pro_slogen_en')->nullable();
$table->string('pro_view')->nullable();
$table->integer('user_id')->default(0);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('products');
}

}


As you can see they are all normal classes, they should function similarly, but for unknown reason, they just don't.



Edit



Here's dd(Product::first()); :



AppProduct {#907
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:29 [
"id" => 4
"pro_special" => "2"
"pro_active" => "2"
"pro_main_cat_id" => 2
"pro_sub_cat_id" => 2
"pro_sub_sub_cat_id" => 3
"pro_country_id" => 5
"pro_city_id" => 7
"pro_price" => 0.45
"pro_discount_percentage" => 0
"pro_after_discount" => 0.0
"pro_image" => "upload/product/1529115234.Bruot.jpg"
"pro_name_ar" => "خبز عربي 6 أرغفة"
"pro_name_en" => "ARABISCHES BROT 6 STÜCK"
"pro_desc_ar" => "<p>خبز عربي 6 أرغفة</p>rn"
"pro_desc_en" => "<p>ARABISCHES BROT 6 STÜCK</p>rn"
"pro_small_desc_ar" => "الوصف عربى"
"pro_small_desc_en" => "الوصف المانى"
"pro_slogen_ar" => "خبز-عربي-6-أرغفة"
"pro_slogen_en" => "arabisches-brot-6-stck"
"pro_view" => null
"user_id" => 0
"prod_count" => 988
"pro_keywords_ar" => ""
"pro_keywords_en" => ""
"pro_meta_desc_ar" => ""
"pro_meta_desc_en" => ""
"created_at" => "2018-06-14 06:46:34"
"updated_at" => "2018-11-30 20:06:58"
]
#original: array:29 [
"id" => 4
"pro_special" => "2"
"pro_active" => "2"
"pro_main_cat_id" => 2
"pro_sub_cat_id" => 2
"pro_sub_sub_cat_id" => 3
"pro_country_id" => 5
"pro_city_id" => 7
"pro_price" => 0.45
"pro_discount_percentage" => 0
"pro_after_discount" => 0.0
"pro_image" => "upload/product/1529115234.Bruot.jpg"
"pro_name_ar" => "خبز عربي 6 أرغفة"
"pro_name_en" => "ARABISCHES BROT 6 STÜCK"
"pro_desc_ar" => "<p>خبز عربي 6 أرغفة</p>rn"
"pro_desc_en" => "<p>ARABISCHES BROT 6 STÜCK</p>rn"
"pro_small_desc_ar" => "الوصف عربى"
"pro_small_desc_en" => "الوصف المانى"
"pro_slogen_ar" => "خبز-عربي-6-أرغفة"
"pro_slogen_en" => "arabisches-brot-6-stck"
"pro_view" => null
"user_id" => 0
"prod_count" => 988
"pro_keywords_ar" => ""
"pro_keywords_en" => ""
"pro_meta_desc_ar" => ""
"pro_meta_desc_en" => ""
"created_at" => "2018-06-14 06:46:34"
"updated_at" => "2018-11-30 20:06:58"
]
#relations:
#hidden:
#visible:
#appends:
#fillable:
#guarded: array:1 [
0 => "*"
]
#dates:
#dateFormat: null
#casts:
#touches:
#observables:
#with:
#morphClass: null
+exists: true
+wasRecentlyCreated: false


dd(Category::first());



AppCategory {#907
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:11 [
"id" => 2
"cat_name_ar" => " المواد الغذائية"
"cat_name_en" => " Lebensmittel"
"cat_order" => "1"
"cat_image" => "upload/category/maincat/1529112273.categ.jpg"
"cat_restura" => null
"cat_slogen_ar" => "المواد-الغذائية"
"cat_slogen_en" => "lebensmittel"
"status" => "1"
"created_at" => "2018-06-10 09:26:24"
"updated_at" => "2018-10-11 21:26:22"
]
#original: array:11 [
"id" => 2
"cat_name_ar" => " المواد الغذائية"
"cat_name_en" => " Lebensmittel"
"cat_order" => "1"
"cat_image" => "upload/category/maincat/1529112273.categ.jpg"
"cat_restura" => null
"cat_slogen_ar" => "المواد-الغذائية"
"cat_slogen_en" => "lebensmittel"
"status" => "1"
"created_at" => "2018-06-10 09:26:24"
"updated_at" => "2018-10-11 21:26:22"
]
#relations:
#hidden:
#visible:
#appends:
#fillable:
#guarded: array:1 [
0 => "*"
]
#dates:
#dateFormat: null
#casts:
#touches:
#observables:
#with:
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}


Relevant route in routes.php:



Route::auth();
Route::get('/', 'frontFrontController@index');


FrontController.php



<?php

namespace AppHttpControllersfront;

use IlluminateHttpRequest;
use AppHttpControllersController;
use IlluminateSupportFacadesSession;
use IlluminateSupportFacadesRedirect;
use IlluminateSupportFacadesValidator;
use AppSlider;
use AppHomeAdvert;
use AppCategory;
use AppProduct;
use AppContact;
use AppPage;
use AppCountry;
use AppCity;
use AppSubcategory;

class FrontController extends Controller {

public function index() {
$sliders = Slider::orderBy('slider_order', 'asc')->get();
$homeadvert = HomeAdvert::first();
$homecategories = Category::where('status', '1')->orderBy('cat_order', 'desc')->with('products')->get();
$homeproducts = $homecategories->map(function ($item) {
return ($item->products()->limit(8))->get();
});

$homelatestproducts = Product::where('pro_active', 2)->orderBy('id', 'desc')->get()->take(8);


$homecategorysearch = Category::where('status', '1')->orderBy('cat_order', 'desc')->get();
$homecountrysearch = Country::orderBy('country_order', 'desc')->get();
$pages = AppPage::all();

return view('frontend.layouts.index', compact('pages', 'homecategorysearch', 'homecountrysearch','homelatestproducts', 'homeproducts', 'sliders', 'homeadvert', 'homecategories'));
}

}






php laravel eloquent






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday

























asked yesterday









Omar Tarek

562415




562415












  • No, the error is happening because it is treating $product as an instance of Query Builder, which makes sense, there is no mainCat() method on a query builder instance, but, this should be an instance of AppProduct, which does have a mainCat(); method. (I edited the word in the error because it was written incorrectly, mainCategory() not mainCat())
    – Omar Tarek
    yesterday








  • 1




    The error quite evidently says you have not finished your query with get(), first() or all()... it is still a builder and no result. -- Personal recommendation on the side: you should use an extra table for field translations that allows for additional languages without having to change code. Your current database structure violates the first normal form.
    – Namoshek
    yesterday










  • what is returned from get_class(AppProduct::first()) in tinker?
    – Amade
    yesterday












  • Do you have data in the product table? Because there isn't first() method ll return null. Please check if you have data in the table.
    – Manuel Eduardo Romero
    yesterday










  • @Namoshek If you read carefully, I specifically used Product::first(); as my query, as for the second note on the database I know that, I got hired while the application is already live, so right now it we're working on other things, but thanks for the recommendation.
    – Omar Tarek
    yesterday


















  • No, the error is happening because it is treating $product as an instance of Query Builder, which makes sense, there is no mainCat() method on a query builder instance, but, this should be an instance of AppProduct, which does have a mainCat(); method. (I edited the word in the error because it was written incorrectly, mainCategory() not mainCat())
    – Omar Tarek
    yesterday








  • 1




    The error quite evidently says you have not finished your query with get(), first() or all()... it is still a builder and no result. -- Personal recommendation on the side: you should use an extra table for field translations that allows for additional languages without having to change code. Your current database structure violates the first normal form.
    – Namoshek
    yesterday










  • what is returned from get_class(AppProduct::first()) in tinker?
    – Amade
    yesterday












  • Do you have data in the product table? Because there isn't first() method ll return null. Please check if you have data in the table.
    – Manuel Eduardo Romero
    yesterday










  • @Namoshek If you read carefully, I specifically used Product::first(); as my query, as for the second note on the database I know that, I got hired while the application is already live, so right now it we're working on other things, but thanks for the recommendation.
    – Omar Tarek
    yesterday
















No, the error is happening because it is treating $product as an instance of Query Builder, which makes sense, there is no mainCat() method on a query builder instance, but, this should be an instance of AppProduct, which does have a mainCat(); method. (I edited the word in the error because it was written incorrectly, mainCategory() not mainCat())
– Omar Tarek
yesterday






No, the error is happening because it is treating $product as an instance of Query Builder, which makes sense, there is no mainCat() method on a query builder instance, but, this should be an instance of AppProduct, which does have a mainCat(); method. (I edited the word in the error because it was written incorrectly, mainCategory() not mainCat())
– Omar Tarek
yesterday






1




1




The error quite evidently says you have not finished your query with get(), first() or all()... it is still a builder and no result. -- Personal recommendation on the side: you should use an extra table for field translations that allows for additional languages without having to change code. Your current database structure violates the first normal form.
– Namoshek
yesterday




The error quite evidently says you have not finished your query with get(), first() or all()... it is still a builder and no result. -- Personal recommendation on the side: you should use an extra table for field translations that allows for additional languages without having to change code. Your current database structure violates the first normal form.
– Namoshek
yesterday












what is returned from get_class(AppProduct::first()) in tinker?
– Amade
yesterday






what is returned from get_class(AppProduct::first()) in tinker?
– Amade
yesterday














Do you have data in the product table? Because there isn't first() method ll return null. Please check if you have data in the table.
– Manuel Eduardo Romero
yesterday




Do you have data in the product table? Because there isn't first() method ll return null. Please check if you have data in the table.
– Manuel Eduardo Romero
yesterday












@Namoshek If you read carefully, I specifically used Product::first(); as my query, as for the second note on the database I know that, I got hired while the application is already live, so right now it we're working on other things, but thanks for the recommendation.
– Omar Tarek
yesterday




@Namoshek If you read carefully, I specifically used Product::first(); as my query, as for the second note on the database I know that, I got hired while the application is already live, so right now it we're working on other things, but thanks for the recommendation.
– Omar Tarek
yesterday












1 Answer
1






active

oldest

votes


















0














first() and last() method return an instance of the class, if there isn't they will return null.



You can do this validating the returned data



$product = Product::first(); // or last() for eg.
if($producto) { do something.... }


Or you can get all products with some condition and verify the result collection quantity



$products::where('field','somthing')->get(); //or all()
if($products->count()) { //or > 0 if you want
do something...
}


Check if exists data in the product table, first.



Please try this and let me know how it works.






share|improve this answer





















  • My database queries were working as expected up until some point, something triggered a breaking change in my dev environment, my products table has 854 products, there is data in all of the tables.
    – Omar Tarek
    yesterday












  • Could you paste here this result dd(Product::first());
    – Manuel Eduardo Romero
    yesterday












  • Done, added to the question itself.
    – Omar Tarek
    yesterday










  • And dd(Product::first()->mainCategory); and maybe a dd(Category::first()); to see the structure.
    – Manuel Eduardo Romero
    yesterday










  • The product looks good. Maybe there is some id missing in the category table. But i will see when you add others dumps
    – Manuel Eduardo Romero
    yesterday











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53944280%2flaravel-chaining-any-method-on-any-model-instance-results-in-an-error-all-of-a%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














first() and last() method return an instance of the class, if there isn't they will return null.



You can do this validating the returned data



$product = Product::first(); // or last() for eg.
if($producto) { do something.... }


Or you can get all products with some condition and verify the result collection quantity



$products::where('field','somthing')->get(); //or all()
if($products->count()) { //or > 0 if you want
do something...
}


Check if exists data in the product table, first.



Please try this and let me know how it works.






share|improve this answer





















  • My database queries were working as expected up until some point, something triggered a breaking change in my dev environment, my products table has 854 products, there is data in all of the tables.
    – Omar Tarek
    yesterday












  • Could you paste here this result dd(Product::first());
    – Manuel Eduardo Romero
    yesterday












  • Done, added to the question itself.
    – Omar Tarek
    yesterday










  • And dd(Product::first()->mainCategory); and maybe a dd(Category::first()); to see the structure.
    – Manuel Eduardo Romero
    yesterday










  • The product looks good. Maybe there is some id missing in the category table. But i will see when you add others dumps
    – Manuel Eduardo Romero
    yesterday
















0














first() and last() method return an instance of the class, if there isn't they will return null.



You can do this validating the returned data



$product = Product::first(); // or last() for eg.
if($producto) { do something.... }


Or you can get all products with some condition and verify the result collection quantity



$products::where('field','somthing')->get(); //or all()
if($products->count()) { //or > 0 if you want
do something...
}


Check if exists data in the product table, first.



Please try this and let me know how it works.






share|improve this answer





















  • My database queries were working as expected up until some point, something triggered a breaking change in my dev environment, my products table has 854 products, there is data in all of the tables.
    – Omar Tarek
    yesterday












  • Could you paste here this result dd(Product::first());
    – Manuel Eduardo Romero
    yesterday












  • Done, added to the question itself.
    – Omar Tarek
    yesterday










  • And dd(Product::first()->mainCategory); and maybe a dd(Category::first()); to see the structure.
    – Manuel Eduardo Romero
    yesterday










  • The product looks good. Maybe there is some id missing in the category table. But i will see when you add others dumps
    – Manuel Eduardo Romero
    yesterday














0












0








0






first() and last() method return an instance of the class, if there isn't they will return null.



You can do this validating the returned data



$product = Product::first(); // or last() for eg.
if($producto) { do something.... }


Or you can get all products with some condition and verify the result collection quantity



$products::where('field','somthing')->get(); //or all()
if($products->count()) { //or > 0 if you want
do something...
}


Check if exists data in the product table, first.



Please try this and let me know how it works.






share|improve this answer












first() and last() method return an instance of the class, if there isn't they will return null.



You can do this validating the returned data



$product = Product::first(); // or last() for eg.
if($producto) { do something.... }


Or you can get all products with some condition and verify the result collection quantity



$products::where('field','somthing')->get(); //or all()
if($products->count()) { //or > 0 if you want
do something...
}


Check if exists data in the product table, first.



Please try this and let me know how it works.







share|improve this answer












share|improve this answer



share|improve this answer










answered yesterday









Manuel Eduardo Romero

1515




1515












  • My database queries were working as expected up until some point, something triggered a breaking change in my dev environment, my products table has 854 products, there is data in all of the tables.
    – Omar Tarek
    yesterday












  • Could you paste here this result dd(Product::first());
    – Manuel Eduardo Romero
    yesterday












  • Done, added to the question itself.
    – Omar Tarek
    yesterday










  • And dd(Product::first()->mainCategory); and maybe a dd(Category::first()); to see the structure.
    – Manuel Eduardo Romero
    yesterday










  • The product looks good. Maybe there is some id missing in the category table. But i will see when you add others dumps
    – Manuel Eduardo Romero
    yesterday


















  • My database queries were working as expected up until some point, something triggered a breaking change in my dev environment, my products table has 854 products, there is data in all of the tables.
    – Omar Tarek
    yesterday












  • Could you paste here this result dd(Product::first());
    – Manuel Eduardo Romero
    yesterday












  • Done, added to the question itself.
    – Omar Tarek
    yesterday










  • And dd(Product::first()->mainCategory); and maybe a dd(Category::first()); to see the structure.
    – Manuel Eduardo Romero
    yesterday










  • The product looks good. Maybe there is some id missing in the category table. But i will see when you add others dumps
    – Manuel Eduardo Romero
    yesterday
















My database queries were working as expected up until some point, something triggered a breaking change in my dev environment, my products table has 854 products, there is data in all of the tables.
– Omar Tarek
yesterday






My database queries were working as expected up until some point, something triggered a breaking change in my dev environment, my products table has 854 products, there is data in all of the tables.
– Omar Tarek
yesterday














Could you paste here this result dd(Product::first());
– Manuel Eduardo Romero
yesterday






Could you paste here this result dd(Product::first());
– Manuel Eduardo Romero
yesterday














Done, added to the question itself.
– Omar Tarek
yesterday




Done, added to the question itself.
– Omar Tarek
yesterday












And dd(Product::first()->mainCategory); and maybe a dd(Category::first()); to see the structure.
– Manuel Eduardo Romero
yesterday




And dd(Product::first()->mainCategory); and maybe a dd(Category::first()); to see the structure.
– Manuel Eduardo Romero
yesterday












The product looks good. Maybe there is some id missing in the category table. But i will see when you add others dumps
– Manuel Eduardo Romero
yesterday




The product looks good. Maybe there is some id missing in the category table. But i will see when you add others dumps
– Manuel Eduardo Romero
yesterday


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53944280%2flaravel-chaining-any-method-on-any-model-instance-results-in-an-error-all-of-a%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas