Reputation: 3
I'm learning to use laravel 8.~ with DB PostgreSQL 12.~ . I want to ask if my approach to fetch data from DB via model method as in the code snippet below is effective or not? Thank you.
This is a model code snippet.
class Product extends Model{
protected $fillable = [
'name',
'price'
];
static function getAllData(){
return Product::get();
}
}
This is a controller code snippet.
use App\Models\Product;
class HomeController extends Controller{
public function getHomePage(){
return view('home', ['productData' => Product::getAllData()]);
}
}
Upvotes: 0
Views: 336
Reputation: 31
Instead of $fillable = ['name','price'] you should use $guarded = [], because in case if you add another column in your Product table you don't have to change your model too.
Upvotes: 0
Reputation: 184
You can use it. Product extends from core model has a method get all data.
use App\Models\Product;
class HomeController extends Controller{
public function getHomePage(){
return view('home', ['productData' => Product::all()]);
}
}
Upvotes: 1