🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Creating Records

Creating a record adds a new row to a table. The create method builds the row and saves it at once.

Create at once

This line creates a task called Read book.

Task::create(['title' => 'Read book', 'done' => false]);

return Task::orderBy('id')->pluck('title')->implode(', ');

Build, then save

These lines build a task and then save it. Creating a record adds a new row to a table.

$task = new Task(['title' => 'Read book', 'done' => false]);
$task->save();

return $task->title;

Title only

The done field falls back to its table default.

$task = Task::create(['title' => 'Read book']);

return $task->title;

Example

Route::get('/tasks/add', function () {
    Task::create(['title' => 'Read book', 'done' => false]);

    return Task::orderBy('id')->pluck('title')->implode(', ');
});

Key points

  • Create: to add a new row to a table.
  • Use Task::create() to build and save a row at once.
  • Use new Task() and save() to build a row in two steps.
  • Fillable: the fields that create() is allowed to set.

In this example, the route answers at /tasks/add. The create call adds a task called Read book. The task is unfinished. The next line reads every title in stored order. The joined titles are Buy milk, Write report, Call Ana, and Read book.

Note

A field missing from the fillable list is ignored by create().

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Task::create() do?