-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotesController.php
More file actions
81 lines (66 loc) · 2.13 KB
/
Copy pathNotesController.php
File metadata and controls
81 lines (66 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace App\Http\Controllers;
use App\Models\Book;
use App\Models\Note;
use App\Models\User;
use Illuminate\Http\Request;
class NotesController extends Controller
{
/**
* Add a new note for the authenticated user and book.
*/
public function addNote(Request $request)
{
$user = $request->user();
$validatedData = $request->validate([
'text' => 'required|string|max:255',
'book_id' => 'required|exists:books,id',
]);
$note = new Note($validatedData);
$note->user_id = $request->user()->id;
$note->save();
// Increment reading rank by 2
$user->reading_rank += 2;
$user->save();
return response()->json(['note' => $note]);
}
/**
* Update an existing note for the authenticated user and book.
*/
public function updateNote(Request $request, $noteId)
{
$note = Note::where('user_id', $request->user()->id)->findOrFail($noteId);
$validatedData = $request->validate([
'text' => 'required|string|max:255',
'book_id' => 'required|exists:books,id',
]);
$note->update($validatedData);
return response()->json(['note' => $note]);
}
/**
* Get all notes for the authenticated user.
*/
public function viewAllNotes(Request $request)
{
$notes = Note::with('user', 'book')->get();
return response()->json(['notes' => $notes]);
}
/**
* Get all notes for the authenticated user and book.
*/
public function viewNotesByBook(Request $request, $bookId)
{
$notes = Note::where('book_id', $bookId)->get();
return response()->json(['notes' => $notes]);
}
public function deleteNote(Request $request, $id)
{
$note = Note::findOrFail($id);
// check if the authenticated user has permission to delete the note
if ($request->user()->cannot('delete', $note)) {
return response()->json(['error' => 'Unauthorized'], 403);
}
$note->delete();
return response()->json(['message' => 'Note deleted successfully']);
}
}