Laravel 초급 태스크 목록 편집하기

경고: 로그인하지 않았습니다. 편집을 하면 IP 주소가 공개되게 됩니다. 로그인하거나 계정을 생성하면 편집자가 사용자 이름으로 기록되고, 다른 장점도 있습니다.

편집을 취소할 수 있습니다. 이 편집을 되돌리려면 아래의 바뀐 내용을 확인한 후 게시해주세요.

최신판 당신의 편집
10번째 줄: 10번째 줄:
Laravel의 기본 기능들을 샘플로 다루어 보기 위해, 태스크들을 다루는 태스크 목록 애플리케이션을 만들어 보겠습니다. 즉, 전형적인 "할 일" 목록 예제를 다루게 됩니다. 이 프로젝트의 완성된 소스코드는 [https://github.com/laravel/quickstart-basic GitHub에서 확인]할 수 있습니다.
Laravel의 기본 기능들을 샘플로 다루어 보기 위해, 태스크들을 다루는 태스크 목록 애플리케이션을 만들어 보겠습니다. 즉, 전형적인 "할 일" 목록 예제를 다루게 됩니다. 이 프로젝트의 완성된 소스코드는 [https://github.com/laravel/quickstart-basic GitHub에서 확인]할 수 있습니다.


==설치==
==도커 환경==
[[Laravel Homestead|Homestead 가상머신]]을 사용하거나 선택한 로컬 PHP 환경을 사용하여 프레임워크를 실행할 수 있습니다. 여기서는 도커 기반 실습환경에서 진행합니다.
 
===도커 기반 실습환경 (선택사항)===
<syntaxhighlight lang='bash'>
mkdir ~/workspace
cd ~/workspace
docker run --name laravel --rm -it -v ${PWD}:/workspace -w /workspace --network host -h docker --entrypoint="" bitnami/laravel bash
</syntaxhighlight>
<syntaxhighlight lang='console'>
<syntaxhighlight lang='console'>
root@wsl:~# mkdir ~/workspace
testuser@lcoalhost:~$ mkdir ~/workspace && cd ~/workspace
root@wsl:~# cd ~/workspace
testuser@localhost:~/workspace$ docker run --name laravel --rm -it -v ${PWD}:/workspace -w /workspace --entrypoint="" --network host bitnami/laravel:latest bash
root@wsl:~/workspace$ docker run --name laravel --rm -it -v ${PWD}:/workspace -w /workspace --network host -h docker --entrypoint="" bitnami/laravel bash
Unable to find image 'bitnami/laravel:latest' locally
Unable to find image 'bitnami/laravel:latest' locally
latest: Pulling from bitnami/laravel
latest: Pulling from bitnami/laravel
28번째 줄: 19번째 줄:
Digest: sha256:d16af27a0d4c2f6f3f71c730d7def97de91e0b2ea0233e84dc758340521b1629
Digest: sha256:d16af27a0d4c2f6f3f71c730d7def97de91e0b2ea0233e84dc758340521b1629
Status: Downloaded newer image for bitnami/laravel:latest
Status: Downloaded newer image for bitnami/laravel:latest
root@docker:/workspace#
root@localhost:/workspace#  
</syntaxhighlight>
</syntaxhighlight>


===Laravel 설치===
==설치==
환경이 준비되면 Composer를 사용하여 Laravel 프레임워크를 설치할 수 있습니다:
우선, Laravel 프레임워크을 새로 설치해야 합니다. [[Laravel Homestead|Homestead 가상머신]]을 사용하거나 선택한 로컬 PHP 환경을 사용하여 프레임워크를 실행할 수 있습니다. 로컬 환경이 준비되면 Composer를 사용하여 Laravel 프레임워크를 설치할 수 있습니다:


<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
39번째 줄: 30번째 줄:


<syntaxhighlight lang='console'>
<syntaxhighlight lang='console'>
root@docker:/workspace# composer create-project laravel/laravel quickstart --prefer-dist
testuser@localhost:~$ composer create-project laravel/laravel quickstart --prefer-dist
Creating a "laravel/laravel" project at "./quickstart"
Creating a "laravel/laravel" project at "./quickstart"
Installing laravel/laravel (v11.1.1)
Installing laravel/laravel (v11.1.1)
...
...
┌ Would you like to create it? ────────────────────────────────┐
│ ● Yes / ○ No                                                │
└──────────────────────────────────────────────────────────────┘
   INFO  Preparing database.
   INFO  Preparing database.


54번째 줄: 49번째 줄:
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang='console'>
<syntaxhighlight lang='console'>
root@docker:/workspace# cd quickstart/
testuser@localhost:~$ cd quickstart/
root@docker:/workspace/quickstart# find app/ routes/ resources/ | grep .php
testuser@localhost:~/quickstart$ find app/ routes/ resources/ | grep .php
app/Providers/AppServiceProvider.php
app/Providers/AppServiceProvider.php
app/Http/Controllers/Controller.php
app/Http/Controllers/Controller.php
62번째 줄: 57번째 줄:
routes/web.php
routes/web.php
resources/views/welcome.blade.php
resources/views/welcome.blade.php
</syntaxhighlight>
{{소스헤더|개발서버 실행}}
<syntaxhighlight lang='console'>
root@docker:/workspace/quickstart# php artisan serve
  INFO  Server running on [http://127.0.0.1:8000].
  Press Ctrl+C to stop the server
^C
</syntaxhighlight>
</syntaxhighlight>


'''참고''': [[composer create-project laravel/laravel quickstart --prefer-dist]]
'''참고''': [[composer create-project laravel/laravel quickstart --prefer-dist]]
[[파일:Fresh-dark.png|640px]]
===vscode 실행 (선택사항)===
<syntaxhighlight lang='console'>
root@wsl:~# code ~/workspace/quickstart/
root@wsl:~#
</syntaxhighlight>
wsl에서는 docker와 디렉토리를 공유합니다. 따라서 vscode에서 파일 편집은 가능하지만 Artisan CLI 명령어는 실행할 수 없습니다. Artisan CLI 명령어는 docker 컨테이너 내부에서 실행해야 합니다.


==데이터베이스 준비==
==데이터베이스 준비==
99번째 줄: 73번째 줄:
$ php artisan make:migration create_tasks_table --create=tasks
$ php artisan make:migration create_tasks_table --create=tasks


   INFO  Migration [database/migrations/2024_06_15_101234_create_tasks_table.php] created successfully.
   INFO  Migration [database/migrations/2024_06_15_161234_create_tasks_table.php] created successfully.
</syntaxhighlight>
</syntaxhighlight>


마이그레이션 파일은 프로젝트의 <code>database/migrations</code> 디렉토리에 생성됩니다. 아마도 <code>make:migration</code> 명령어가 이미 자동 증가 ID와 타임스탬프를 마이그레이션 파일에 추가한 것을 보셨을 것입니다. 이 파일을 편집하여 작업 이름을 위한 <code>name</code> 문자열 컬럼을 추가해봅시다:
마이그레이션 파일은 프로젝트의 <code>database/migrations</code> 디렉토리에 생성됩니다. 아마도 <code>make:migration</code> 명령어가 이미 자동 증가 ID와 타임스탬프를 마이그레이션 파일에 추가한 것을 보셨을 것입니다. 이 파일을 편집하여 작업 이름을 위한 <code>name</code> 문자열 컬럼을 추가해봅시다:


{{소스헤더|database/migrations/2024_06_15_101234_create_tasks_table.php}}
{{소스헤더|database/migrations/2024_06_15_161234_create_tasks_table.php}}
<syntaxhighlight lang='php' highlight='16'>
<syntaxhighlight lang='php' highlight='16'>
<?php
<?php
146번째 줄: 120번째 줄:
   INFO  Running migrations.
   INFO  Running migrations.


   2024_06_15_101234_create_tasks_table ....................................... 9.24ms DONE
   2024_06_15_161234_create_tasks_table ....................................... 9.24ms DONE
</syntaxhighlight>
</syntaxhighlight>


251번째 줄: 225번째 줄:
     <head>
     <head>
         <title>Laravel Quickstart - Basic</title>
         <title>Laravel Quickstart - Basic</title>
         <link rel="stylesheet" href="https://unpkg.com/bootstrap@5/dist/css/bootstrap.min.css">
 
         <!-- CSS And JavaScript -->
     </head>
     </head>


     <body>
     <body>
         <nav class="navbar navbar-light bg-light border-bottom">
         <div class="container">
             <div class="container-fluid">
             <nav class="navbar navbar-default">
                 Task List
                 <!-- Navbar Contents -->
             </div>
             </nav>
         </nav>
         </div>


         @yield('content')
         @yield('content')
280번째 줄: 255번째 줄:


     <!-- Bootstrap Boilerplate... -->
     <!-- Bootstrap Boilerplate... -->
    <div class="card m-3">
        <div class="card-header">
            New Task
        </div>


        <div class="card-body">
    <div class="panel-body">
            <!-- Display Validation Errors -->
        <!-- Display Validation Errors -->
            @include('common.errors')
        @include('common.errors')
 
        <!-- New Task Form -->
        <form action="{{ url('task') }}" method="POST" class="form-horizontal">
            {{ csrf_field() }}


             <!-- New Task Form -->
             <!-- Task Name -->
             <form action="{{ url('task') }}" method="POST" class="form-horizontal">
             <div class="form-group">
                {{ csrf_field() }}
                <label for="task" class="col-sm-3 control-label">Task</label>


                <!-- Task Name -->
                 <div class="col-sm-6">
                 <div class="mb-3">
                     <input type="text" name="name" id="task-name" class="form-control">
                    <label for="task">Task</label>
                     <input type="text" name="name" id="task" class="form-control">
                 </div>
                 </div>
            </div>


                <!-- Add Task Button -->
            <!-- Add Task Button -->
                 <button type="submit" class="btn btn-primary">
            <div class="form-group">
                    Add Task
                 <div class="col-sm-offset-3 col-sm-6">
                 </button>
                    <button type="submit" class="btn btn-default">
             </form>
                        <i class="fa fa-plus"></i> Add Task
         </div>
                    </button>
                 </div>
             </div>
         </form>
     </div>
     </div>


335번째 줄: 312번째 줄:
{{소스헤더|routes/web.php}}
{{소스헤더|routes/web.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
Route::post('/task', function () {
Route::post('/task', function (Request $request) {
     $validator = Validator::make(Request::all(), [
     $validator = Validator::make($request->all(), [
         'name' => 'required|max:255',
         'name' => 'required|max:255',
     ]);
     ]);
380번째 줄: 357번째 줄:
{{소스헤더|routes/web.php}}
{{소스헤더|routes/web.php}}
<syntaxhighlight lang='php' highlight='12-16'>
<syntaxhighlight lang='php' highlight='12-16'>
Route::post('/task', function () {
Route::post('/task', function (Request $request) {
     $validator = Validator::make(Request::all(), [
     $validator = Validator::make($request->all(), [
         'name' => 'required|max:255',
         'name' => 'required|max:255',
     ]);
     ]);
392번째 줄: 369번째 줄:
   
   
     $task = new Task;
     $task = new Task;
     $task->name = Request::input('name');
     $task->name = $request->name;
     $task->save();
     $task->save();
   
   
405번째 줄: 382번째 줄:


{{소스헤더|routes/web.php}}
{{소스헤더|routes/web.php}}
<syntaxhighlight lang='php' highlight='3,10-14'>
<syntaxhighlight lang='php'>
<?php
 
use App\Models\Task;
use Illuminate\Support\Facades\Route;
 
/**
* Show Task Dashboard
*/
Route::get('/', function () {
Route::get('/', function () {
     $tasks = Task::orderBy('created_at', 'asc')->get();
     $tasks = Task::orderBy('created_at', 'asc')->get();
434번째 줄: 403번째 줄:
     <!-- Current Tasks -->
     <!-- Current Tasks -->
     @if (count($tasks) > 0)
     @if (count($tasks) > 0)
         <div class="card m-3">
         <div class="panel panel-default">
             <div class="card-header">
             <div class="panel-heading">
                 Current Tasks
                 Current Tasks
             </div>
             </div>
   
   
             <div class="card-body">
             <div class="panel-body">
                 <table class="table table-striped">
                 <table class="table table-striped task-table">
   
   
                     <!-- Table Headings -->
                     <!-- Table Headings -->
480번째 줄: 449번째 줄:
                             <tr>
                             <tr>
                                 <!-- Task Name -->
                                 <!-- Task Name -->
                                 <td>
                                 <td class="table-text">
                                     {{ $task->name }}
                                     <div>{{ $task->name }}</div>
                                 </td>
                                 </td>


491번째 줄: 460번째 줄:
   
   
                                         <button type="submit" class="btn btn-danger">
                                         <button type="submit" class="btn btn-danger">
                                             Delete
                                             <i class="fa fa-trash"></i> Delete
                                         </button>
                                         </button>
                                     </form>
                                     </form>

제타위키에서의 모든 기여는 크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0 라이선스로 배포된다는 점을 유의해 주세요(자세한 내용에 대해서는 제타위키:저작권 문서를 읽어주세요). 만약 여기에 동의하지 않는다면 문서를 저장하지 말아 주세요.
또한, 직접 작성했거나 퍼블릭 도메인과 같은 자유 문서에서 가져왔다는 것을 보증해야 합니다. 저작권이 있는 내용을 허가 없이 저장하지 마세요!

취소 편집 도움말 (새 창에서 열림)

이 문서에서 사용한 틀: