1. TaskController.php 

Task모델을  Json으로 반환하는 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
 
class TaskController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $tasks = Auth::user()->tasks;
 
        //JSON반환처리
        return response()->json([
            'tasks' => $tasks
        ], 200);
    }
cs


2. 브라우저에서 확인 loaclhost/tasks


3. store()메서드

유효성검사, 등록로직만들기, 등록후 메시지 보내기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'body' => 'required'
        ]);
 
        $task = $request->user()->tasks()->create([
            'name' => $request->name,
            'body' => $request->body
        ]);
 
        return response()->json([
            'task' => $task,
            'message' => 'task has been created!'
        ]);
    }
cs


4. update()메서드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required',
            'body' => 'required'
        ]);
 
        $task = $request->user()->tasks()->whereId($id)->update($request->all());
 
        return response()->json([
            'task' => $task,
            'message' => 'task has been updated!'
        ]);
    }
cs


5. destroy()메서드

1
2
3
4
5
6
7
8
9
10
    public function destroy(Task $task)
    {
        $task->delete();
 
        return response()->json([
            'task' => $task,
            'message' => 'task has been deleted!'
        ]);
 
    }
cs


+ Recent posts