Laravel simple app with database

Create new app

1
laravel new myapp

Tasks without datebase

web.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Route::get('/tasks', function () {
$tasks = [
"Go to store",
"Finish the blog",
"Clean the house'
];

return view('welcome', compact('tasks'));
/*
or other variations for the last line
return view('welcome')->with('tasks', $tasks);
return view('welcome', ['tasks' => $tasks]);
*/
});
welcome.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<title></title>

</head>

<body>
<ul>
@foreach ($tasks as $task)
<li>{{ $task }}</li>
@endforeach
</ul>
</body>

</html>

visit myapp.dev

Tasks with database

.env
1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=

Create some tasks with Sequal Pro, or whatever you like.

1
php artisan make:migration create_tasks_table --create=tasks
database/migrations/2017_06_21_140553_create_tasks_table.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class CreateTasksTable extends Migration
{
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->text('body');
$table->timestamps();
});
}

public function down()
{
Schema::dropIfExists('tasks');
}
}
1
php artisan migrate
1
2
3
4
Route::get('/tasks', function () {
$tasks = DB::table('tasks')->get();
return view('welcome', compact('tasks'));
});

Database use Eloquent

php artisan make:model Task

You can reference the task model in the terminal with tinker

1
php artisan tinker
>>> Task::all()
>>> App\Task::pluck('body').first()
>>> $task = new App\Task
>>> $task->body = 'Go to the market'
>>> $task->save()
web.php
1
2
3
4
Route::get('/tasks', function () {
$tasks = App\Task::all();
return view('welcome', compact('tasks'));
});