p3ace p3ace - 1 month ago 22
PHP Question

Laravel 5.3 Does protected variables in a Model act as constructor

I'm new to Laravel and I noticed some are similar to Java, some aren't. I guess it's because it uses OOP style.

I'm following a video tutorial for beginners and came across the

protected
modifier (if I'm correct).

I originally learned programming in Java. Below are three php file definitions.

Does the
protected $fillable
in the
Product
class act like a
constructor
in Java which requires you to supply values before you can create an instance of the class? (in this case, Product Class)

ProductTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class ProductTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{

$product = new \App\Product([
'imagePath' => 'someImagePathURL',
'title' => 'Harry Potter',
'description' => 'Super cool - at least as a child.',
'price' => 10
]);
$product->save();
}
}


Product.php



namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
protected $fillable = ['imagePath','title','description','price'];
}


create_products_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('imagePath');
$table->string('title');
$table->text('description');
$table->integer('price');
});
}

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


The line
$product = new \App\Product
I understand to be the
instantiation
part.

I'd appreciate any useful explanation to this.

Thank you.

Answer
protected $fillable = ['imagePath','title','description','price'];

It means, the field names that are given in this array can only be inserted into database from our side. Like, it is only allowed to fill values from us.

In clear, referred from document.

The $fillable property means an array of attributes that you want to be mass assignable

And,

The $guarded property means an array of attributes that you do not want to be mass assignable

Reference : https://laravel.com/docs/5.3/eloquent#mass-assignment

Comments