0
votes

I am a beginner of laravel. I read some information from the laravel's website, https://laravel.com/docs/5.8/eloquent#default-attribute-values, and it said that we can setup some default attributes in model. The detail what is said:

Default Attribute Values If you would like to define the default values for some of your model's attributes, you may define an $attributes property on your model:

<?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,
    ];
}

Now, i have created CRUD function in the laravel. And setting up with some example/default values in the database, it is "id"=1,"element1"="ABC","element2"="abc". Finally, I find nothing in showing table.

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');

How do i do with i want to setup some default value? thank you!

1
Seems you are trying to query your table before you actually saved anything there?Tpojka
Have you saved any data? You have to make at least one object from your model and save it.Rouhollah Mazarei
my database table is empty and i want to set some example/default data in laravel before using in the interface.Jackyrm

1 Answers

0
votes

You have to make an object from your model. To do so (for test purpose) let's add a route like this:

Route::get('test', 'CRUDController@test');

And in your controller add a test method like this:

public function test(){
    $crud = new Crud();
    $crud->save();
}

You can also use tinker to test your code.

type php artisan tinker in command/console and then make a new instance of your model:

$crud = new App\Crud;
$crud->save();