douxingsuo8809 2016-10-19 11:13
浏览 63
已采纳

Laravel 5.3模型中的受保护变量是否构成构造函数

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.

  • 写回答

1条回答 默认 最新

  • doumi1099 2016-10-19 11:22
    关注
    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?