我是 Laravel 的初学者。我从 laravel 的网站https://laravel.com/docs/5.8/eloquent#default-attribute-values阅读了一些信息,它说我们可以在模型中设置一些默认属性。详细说的是:
默认属性值如果您想为模型的某些属性定义默认值,您可以在模型上定义 $attributes 属性:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The model's default values for attributes.
* @var array
*/
protected $attributes = [
'delayed' => false,
];
}
现在,我已经在 Laravel 中创建了 CRUD 函数。并在数据库中设置一些示例/默认值,它是 "id"=1,"element1"="ABC","element2"="abc"。最后,我在显示表中找不到任何东西。
Database Table:
...
public function up()
{
Schema::create('cruds', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('element1');
$table->string('element2');
});
}
...
Model:CRUD
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class crud extends Model
{
protected $timestramp = false;
protected $primarykey = "id";
protected $attributes =[
'id' => 1,
'element1' => "ABC",
'element2' => "abc",
];
}
View.blade.php
...
<tbody>
@foreach ($CRUDitems as $item)
<tr>
<th scope="row">{{ ($item->$id) }}</th>
<td>{{ ($item->$element1) }}</td>
<td>{{ ($item->$element2) }}</td>
</tr>
@endforeach
</tbody>
...
CRUDController.php
...
public function index()
{
$CRUDitems = crud::all();
return view('CRUD.viewTable',compact('CRUDitems')) ;
}
...
web.php
<?php
Route::resource('/CRUD', 'CRUDController');
我想设置一些默认值怎么办?谢谢你!
扬帆大鱼