My editor shows an error even the field is not a protected, now I wondering if model
is valid column name or it just a bug in PHP debugging tools/extensions.
I am using VScode and I have this php related extensions:
I disabled PHP by DEVSENSE and the errors gone so its likely a bug in an extension?
Error message: Member has protected visibility and is not accessible from the current context.PHP(PHP1416)
I tried to use it and I successfully display the data
ProductController.php
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsProduct;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$products = Product::all();
$products = $products->map(function ($product) {
return [
'id' => $product->id,
'name' => $product->name,
'brand' => $product->brand,
'model' => $product->model,
'description' => $product->description,
'image_url' => $product->image_url,
'price' => $product->price,
'category_name' => $product->category->name ?? 'N/A',
'supplier_name' => $product->supplier->name ?? 'N/A',
];
});
return response()->json($products);
}
}
Product.php in Models
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Product extends Model
{
use HasFactory;
public function category()
{
return $this->belongsTo(Category::class);
}
public function supplier()
{
return $this->belongsTo(Supplier::class);
}
}
Here is how I create the table in migration
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->constrained('categories')->onDelete('restrict');
$table->foreignId('supplier_id')->constrained('suppliers')->onDelete('restrict');
$table->string('name');
$table->string('brand');
$table->string('model');
$table->string('description');
$table->string('image_url');
$table->decimal('price');
$table->timestamps();
});
DB::statement('ALTER TABLE products AUTO_INCREMENT = 100000;');
}