[{"data":1,"prerenderedAt":4808},["ShallowReactive",2],{"series-\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbuilding-a-simple-comment-system-for-user-engagement":3,"series-context-\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api":4596},{"id":4,"title":5,"body":6,"contentId":4583,"date":4584,"description":4585,"extension":4586,"github":4587,"meetTheInstructor":4587,"meta":4588,"navigation":449,"part":346,"path":4589,"rawbody":4590,"robots":4587,"schemaOrg":4587,"seo":4591,"seriesSlug":4592,"sitemap":4593,"stem":4594,"subtitle":4587,"topics":4587,"__hash__":4595},"series\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbuilding-a-simple-comment-system-for-user-engagement.md","Building a Simple Comment System for User Engagement",{"type":7,"value":8,"toc":4574},"minimark",[9,13,16,32,35,43,48,51,54,93,113,123,152,163,166,169,172,186,189,215,234,239,242,251,287,295,315,327,344,354,370,379,382,387,390,394,397,415,418,486,489,549,552,555,581,584,683,686,705,725,728,746,749,821,823,897,900,989,992,1007,1010,1072,1178,1235,1238,1248,1259,1262,1267,1313,1367,1516,1522,1525,1529,1532,1537,1557,1563,1732,1739,1750,1768,1774,1811,1817,1892,1897,1911,1979,1982,1985,2086,2095,2100,2106,2123,2257,2260,2276,2403,2406,2409,2432,2435,2488,2491,2494,2499,2564,2577,2580,2586,2589,2638,2641,2665,2668,2759,2767,2772,2826,2831,2834,2901,2904,2910,2927,3020,3026,3075,3078,3081,3218,3228,3234,3311,3314,3317,3321,3324,3329,3332,3353,3356,3764,3767,3807,3810,3824,3830,3930,3933,3949,3952,4099,4106,4123,4126,4205,4208,4211,4359,4407,4482,4494,4550,4553,4557,4560,4563,4570],[10,11,12],"p",{},"With GitHub authentication in place, we can now build the feature it enables: comments.",[10,14,15],{},"Before writing any code, let's define the first version of the comment system. We want it to support the core interactions without taking on more complexity than necessary:",[17,18,19,23,26,29],"ul",{},[20,21,22],"li",{},"Users should be able to leave comments on blog posts.",[20,24,25],{},"Users should be able to edit or delete their comments.",[20,27,28],{},"Replying to comments is not planned.",[20,30,31],{},"Supporting Markdown is not planned.",[10,33,34],{},"For now, we want a deliberately simple comment system.",[36,37,40],"callout",{"color":38,"icon":39},"info","i-ph-info-duotone",[10,41,42],{},"I want to keep the code simple for two reasons. First, the process and the decisions behind it are more important than the amount of code. Second, more advanced features can be explored in a future series.",[44,45,47],"h2",{"id":46},"building-the-comment-system","Building the comment system",[10,49,50],{},"Now that the requirements are clear, let us map them to the concepts in our application.",[10,52,53],{},"A comment is a message left by a user on a blog post. In our system, the model will have these properties:",[17,55,56,63,69,75,81,87],{},[20,57,58,62],{},[59,60,61],"code",{},"id",": The unique identifier of the comment.",[20,64,65,68],{},[59,66,67],{},"post_id",": The identifier of the post to which the comment belongs.",[20,70,71,74],{},[59,72,73],{},"user_id",": The identifier of the user who left the comment.",[20,76,77,80],{},[59,78,79],{},"content",": The content of the comment.",[20,82,83,86],{},[59,84,85],{},"created_at",": The timestamp when the comment was created.",[20,88,89,92],{},[59,90,91],{},"updated_at",": The timestamp when the comment was last updated.",[10,94,95,97,98,101,102,105,106,109,110,112],{},[59,96,73],{}," references the ",[59,99,100],{},"users"," table, and the ",[59,103,104],{},"User"," model will have a ",[59,107,108],{},"comments"," relationship. What about ",[59,111,67],{},"?",[10,114,115,116,118,119,122],{},"For ",[59,117,67],{},", we need a ",[59,120,121],{},"Post"," model with these properties:",[17,124,125,130,136,142,147],{},[20,126,127,129],{},[59,128,61],{},": The unique identifier of the post.",[20,131,132,135],{},[59,133,134],{},"meta_id",": The unique identifier coming from the frontend.",[20,137,138,141],{},[59,139,140],{},"title",": The title of the post.",[20,143,144,146],{},[59,145,85],{},": The timestamp when the post was created.",[20,148,149,151],{},[59,150,91],{},": The timestamp when the post was last updated.",[10,153,154,155,105,157,159,160,162],{},"The ",[59,156,121],{},[59,158,108],{}," relationship, allowing us to associate multiple comments with each post. We will discuss ",[59,161,134],{}," in the next article, so you can ignore its purpose for now.",[10,164,165],{},"The relationships will look like this:",[10,167,168],{},"With the models and relationships defined, we can design the API for retrieving, creating, editing, and deleting comments.",[10,170,171],{},"First, list the endpoints we need:",[17,173,174,177,180,183],{},[20,175,176],{},"List all comments for a post, from anyone",[20,178,179],{},"Create a comment, from an authenticated user",[20,181,182],{},"Edit a comment, from the user who created it",[20,184,185],{},"Delete a comment, from the user who created it",[10,187,188],{},"Then, we can map the endpoints to routes:",[17,190,191,197,203,209],{},[20,192,193,196],{},[59,194,195],{},"GET    \u002Fposts\u002F{post}\u002Fcomments",": List all comments for a post",[20,198,199,202],{},[59,200,201],{},"POST   \u002Fposts\u002F{post}\u002Fcomments",": Create a comment",[20,204,205,208],{},[59,206,207],{},"PUT    \u002Fcomments\u002F{comment}",": Edit a comment",[20,210,211,214],{},[59,212,213],{},"DELETE \u002Fcomments\u002F{comment}",": Delete a comment",[10,216,217,218,221,222,225,226,233],{},"The mapping is straightforward. Why use ",[59,219,220],{},"\u002Fcomments\u002F{comment}"," instead of ",[59,223,224],{},"\u002Fposts\u002F{post}\u002Fcomments\u002F{comment}"," for the last two routes? A comment ID is unique, so we can identify the comment without repeating the post ID. In Laravel, this is called ",[227,228,232],"a",{"href":229,"rel":230},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F12.x\u002Fcontrollers#shallow-nesting",[231],"nofollow","shallow nesting",".",[235,236,238],"h3",{"id":237},"summary-before-writing-code","Summary before writing code",[10,240,241],{},"Before writing code, we can summarize the implementation steps:",[243,244,245],"ol",{},[20,246,247,248,250],{},"Create a ",[59,249,121],{}," model with its migration.",[252,253,259],"pre",{"className":254,"code":255,"filename":256,"language":257,"meta":258,"style":258},"language-bash shiki shiki-themes github-light github-light github-dark","php artisan make:model Post -m -f\n","terminal","bash","",[59,260,261],{"__ignoreMap":258},[262,263,266,270,274,277,280,284],"span",{"class":264,"line":265},"line",1,[262,267,269],{"class":268},"snPdu","php",[262,271,273],{"class":272},"sIIMD"," artisan",[262,275,276],{"class":272}," make:model",[262,278,279],{"class":272}," Post",[262,281,283],{"class":282},"sBjJW"," -m",[262,285,286],{"class":282}," -f\n",[243,288,290],{"start":289},2,[20,291,247,292,250],{},[59,293,294],{},"Comment",[252,296,298],{"className":254,"code":297,"filename":256,"language":257,"meta":258,"style":258},"php artisan make:model Comment -m -f\n",[59,299,300],{"__ignoreMap":258},[262,301,302,304,306,308,311,313],{"class":264,"line":265},[262,303,269],{"class":268},[262,305,273],{"class":272},[262,307,276],{"class":272},[262,309,310],{"class":272}," Comment",[262,312,283],{"class":282},[262,314,286],{"class":282},[243,316,318],{"start":317},3,[20,319,247,320,323,324,233],{},[59,321,322],{},"CommentController"," in ",[59,325,326],{},"app\u002FHttp\u002FApi",[252,328,330],{"className":254,"code":329,"filename":256,"language":257,"meta":258,"style":258},"php artisan make:controller Api\u002FCommentController\n",[59,331,332],{"__ignoreMap":258},[262,333,334,336,338,341],{"class":264,"line":265},[262,335,269],{"class":268},[262,337,273],{"class":272},[262,339,340],{"class":272}," make:controller",[262,342,343],{"class":272}," Api\u002FCommentController\n",[243,345,347],{"start":346},4,[20,348,247,349,323,352,233],{},[59,350,351],{},"PostCommentController",[59,353,326],{},[252,355,357],{"className":254,"code":356,"filename":256,"language":257,"meta":258,"style":258},"php artisan make:controller Api\u002FPostCommentController\n",[59,358,359],{"__ignoreMap":258},[262,360,361,363,365,367],{"class":264,"line":265},[262,362,269],{"class":268},[262,364,273],{"class":272},[262,366,340],{"class":272},[262,368,369],{"class":272}," Api\u002FPostCommentController\n",[243,371,373],{"start":372},5,[20,374,375,376,233],{},"Add the routes to ",[59,377,378],{},"routes\u002Fapi.php",[10,380,381],{},"We will add the tests as we go.",[36,383,384],{"color":38,"icon":39},[10,385,386],{},"I will not explain every test in detail. I will focus on the most important ones.",[10,388,389],{},"Ready? Let's go!",[44,391,393],{"id":392},"viewing-and-creating-comments","Viewing and creating comments",[10,395,396],{},"Create the post model with Artisan:",[252,398,399],{"className":254,"code":255,"filename":256,"language":257,"meta":258,"style":258},[59,400,401],{"__ignoreMap":258},[262,402,403,405,407,409,411,413],{"class":264,"line":265},[262,404,269],{"class":268},[262,406,273],{"class":272},[262,408,276],{"class":272},[262,410,279],{"class":272},[262,412,283],{"class":282},[262,414,286],{"class":282},[10,416,417],{},"Now, let's jump to the migration file and add the following code:",[252,419,423],{"className":420,"code":421,"filename":422,"language":269,"meta":258,"style":258},"language-php shiki shiki-themes github-light github-light github-dark","return new class extends Migration\n{\n    Schema::create('posts', function (Blueprint $table) {\n        $table->id();\n\n        $table->string('title'); \u002F\u002F [!code ++]\n        $table->unsignedInteger('meta_id')->unique(); \u002F\u002F [!code ++]\n\n        $table->timestamps();\n    });\n};\n","database\u002Fmigrations\u002F2025_03_02_121249_create_posts_table.php",[59,424,425,430,435,440,445,451,457,463,468,474,480],{"__ignoreMap":258},[262,426,427],{"class":264,"line":265},[262,428,429],{},"return new class extends Migration\n",[262,431,432],{"class":264,"line":289},[262,433,434],{},"{\n",[262,436,437],{"class":264,"line":317},[262,438,439],{},"    Schema::create('posts', function (Blueprint $table) {\n",[262,441,442],{"class":264,"line":346},[262,443,444],{},"        $table->id();\n",[262,446,447],{"class":264,"line":372},[262,448,450],{"emptyLinePlaceholder":449},true,"\n",[262,452,454],{"class":264,"line":453},6,[262,455,456],{},"        $table->string('title'); \u002F\u002F [!code ++]\n",[262,458,460],{"class":264,"line":459},7,[262,461,462],{},"        $table->unsignedInteger('meta_id')->unique(); \u002F\u002F [!code ++]\n",[262,464,466],{"class":264,"line":465},8,[262,467,450],{"emptyLinePlaceholder":449},[262,469,471],{"class":264,"line":470},9,[262,472,473],{},"        $table->timestamps();\n",[262,475,477],{"class":264,"line":476},10,[262,478,479],{},"    });\n",[262,481,483],{"class":264,"line":482},11,[262,484,485],{},"};\n",[10,487,488],{},"Update the factory to match the migration:",[252,490,494],{"className":491,"code":492,"filename":493,"language":269,"meta":258,"style":258},"language-php shiki shiki-themes github-light github-light github-dark has-diff","class PostFactory extends Factory\n{\n    public function definition(): array\n    {\n        return [\n            'title' => fake()->sentence(), \u002F\u002F [!code ++]\n            'meta_id' => fake()->unique()->numberBetween(1, 1000), \u002F\u002F [!code ++]\n        ];\n    }\n}\n","database\u002Ffactories\u002FPostFactory.php",[59,495,496,501,505,510,515,520,528,534,539,544],{"__ignoreMap":258},[262,497,498],{"class":264,"line":265},[262,499,500],{},"class PostFactory extends Factory\n",[262,502,503],{"class":264,"line":289},[262,504,434],{},[262,506,507],{"class":264,"line":317},[262,508,509],{},"    public function definition(): array\n",[262,511,512],{"class":264,"line":346},[262,513,514],{},"    {\n",[262,516,517],{"class":264,"line":372},[262,518,519],{},"        return [\n",[262,521,525],{"class":522,"line":453},[264,523,524],"diff","add",[262,526,527],{},"            'title' => fake()->sentence(),",[262,529,531],{"class":530,"line":459},[264,523,524],[262,532,533],{},"            'meta_id' => fake()->unique()->numberBetween(1, 1000),",[262,535,536],{"class":264,"line":465},[262,537,538],{},"        ];\n",[262,540,541],{"class":264,"line":470},[262,542,543],{},"    }\n",[262,545,546],{"class":264,"line":476},[262,547,548],{},"}\n",[10,550,551],{},"Add a test to ensure that the model has the expected shape.",[10,553,554],{},"First, we need to create a test file:",[252,556,558],{"className":254,"code":557,"filename":256,"language":257,"meta":258,"style":258},"mkdir -p tests\u002FUnit\u002FModels && touch tests\u002FUnit\u002FModels\u002FPostTest.php\n",[59,559,560],{"__ignoreMap":258},[262,561,562,565,568,571,575,578],{"class":264,"line":265},[262,563,564],{"class":268},"mkdir",[262,566,567],{"class":282}," -p",[262,569,570],{"class":272}," tests\u002FUnit\u002FModels",[262,572,574],{"class":573},"sxrX7"," && ",[262,576,577],{"class":268},"touch",[262,579,580],{"class":272}," tests\u002FUnit\u002FModels\u002FPostTest.php\n",[10,582,583],{},"Then, we can add the following code to the test file:",[252,585,588],{"className":420,"code":586,"filename":587,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Post;\n\ntest('to array', function () {\n    $post = Post::factory()->create()->fresh();\n\n    expect(array_keys($post->toArray()))\n        ->toEqual([\n            'id',\n            'title',\n            'meta_id',\n            'created_at',\n            'updated_at',\n        ]);\n});\n","tests\u002FUnit\u002FModels\u002FPostTest.php",[59,589,590,595,599,604,608,613,617,622,627,631,636,641,647,653,659,665,671,677],{"__ignoreMap":258},[262,591,592],{"class":264,"line":265},[262,593,594],{},"\u003C?php\n",[262,596,597],{"class":264,"line":289},[262,598,450],{"emptyLinePlaceholder":449},[262,600,601],{"class":264,"line":317},[262,602,603],{},"declare(strict_types=1);\n",[262,605,606],{"class":264,"line":346},[262,607,450],{"emptyLinePlaceholder":449},[262,609,610],{"class":264,"line":372},[262,611,612],{},"use App\\Models\\Post;\n",[262,614,615],{"class":264,"line":453},[262,616,450],{"emptyLinePlaceholder":449},[262,618,619],{"class":264,"line":459},[262,620,621],{},"test('to array', function () {\n",[262,623,624],{"class":264,"line":465},[262,625,626],{},"    $post = Post::factory()->create()->fresh();\n",[262,628,629],{"class":264,"line":470},[262,630,450],{"emptyLinePlaceholder":449},[262,632,633],{"class":264,"line":476},[262,634,635],{},"    expect(array_keys($post->toArray()))\n",[262,637,638],{"class":264,"line":482},[262,639,640],{},"        ->toEqual([\n",[262,642,644],{"class":264,"line":643},12,[262,645,646],{},"            'id',\n",[262,648,650],{"class":264,"line":649},13,[262,651,652],{},"            'title',\n",[262,654,656],{"class":264,"line":655},14,[262,657,658],{},"            'meta_id',\n",[262,660,662],{"class":264,"line":661},15,[262,663,664],{},"            'created_at',\n",[262,666,668],{"class":264,"line":667},16,[262,669,670],{},"            'updated_at',\n",[262,672,674],{"class":264,"line":673},17,[262,675,676],{},"        ]);\n",[262,678,680],{"class":264,"line":679},18,[262,681,682],{},"});\n",[10,684,685],{},"This minimal test verifies the model's persisted properties. It can catch an accidental column removal or addition in a migration. We will add a similar test for each model we create.",[10,687,688,689,692,693,696,697,700,701,704],{},"To make sure that our test is working, we need to enable the ",[59,690,691],{},"tests\u002FUnit"," folder to have access to a working database. To do this, we can add ",[59,694,695],{},"Unit"," to the ",[59,698,699],{},"in"," method of the ",[59,702,703],{},"tests\u002FPest.php"," file:",[252,706,708],{"className":420,"code":707,"filename":703,"language":269,"meta":258,"style":258},"pest()->extend(Tests\\TestCase::class)\n    ->use(Illuminate\\Foundation\\Testing\\RefreshDatabase::class)\n    ->in('Http', 'Unit');\n",[59,709,710,715,720],{"__ignoreMap":258},[262,711,712],{"class":264,"line":265},[262,713,714],{},"pest()->extend(Tests\\TestCase::class)\n",[262,716,717],{"class":264,"line":289},[262,718,719],{},"    ->use(Illuminate\\Foundation\\Testing\\RefreshDatabase::class)\n",[262,721,722],{"class":264,"line":317},[262,723,724],{},"    ->in('Http', 'Unit');\n",[10,726,727],{},"Create the comment model in the same way:",[252,729,730],{"className":254,"code":297,"filename":256,"language":257,"meta":258,"style":258},[59,731,732],{"__ignoreMap":258},[262,733,734,736,738,740,742,744],{"class":264,"line":265},[262,735,269],{"class":268},[262,737,273],{"class":272},[262,739,276],{"class":272},[262,741,310],{"class":272},[262,743,283],{"class":282},[262,745,286],{"class":282},[10,747,748],{},"Update its migration:",[252,750,753],{"className":420,"code":751,"filename":752,"language":269,"meta":258,"style":258},"use App\\Models\\Post; \u002F\u002F [!code ++]\nuse App\\Models\\User; \u002F\u002F [!code ++]\n\nreturn new class extends Migration\n{\n    Schema::create('comments', function (Blueprint $table) {\n        $table->id();\n\n        $table->foreignIdFor(Post::class)->constrained()->cascadeOnDelete(); \u002F\u002F [!code ++]\n        $table->foreignIdFor(User::class)->constrained()->cascadeOnDelete(); \u002F\u002F [!code ++]\n        $table->text('content'); \u002F\u002F [!code ++]\n\n        $table->timestamps();\n    });\n};\n","database\u002Fmigrations\u002F2025_03_02_121249_create_comments_table.php",[59,754,755,760,765,769,773,777,782,786,790,795,800,805,809,813,817],{"__ignoreMap":258},[262,756,757],{"class":264,"line":265},[262,758,759],{},"use App\\Models\\Post; \u002F\u002F [!code ++]\n",[262,761,762],{"class":264,"line":289},[262,763,764],{},"use App\\Models\\User; \u002F\u002F [!code ++]\n",[262,766,767],{"class":264,"line":317},[262,768,450],{"emptyLinePlaceholder":449},[262,770,771],{"class":264,"line":346},[262,772,429],{},[262,774,775],{"class":264,"line":372},[262,776,434],{},[262,778,779],{"class":264,"line":453},[262,780,781],{},"    Schema::create('comments', function (Blueprint $table) {\n",[262,783,784],{"class":264,"line":459},[262,785,444],{},[262,787,788],{"class":264,"line":465},[262,789,450],{"emptyLinePlaceholder":449},[262,791,792],{"class":264,"line":470},[262,793,794],{},"        $table->foreignIdFor(Post::class)->constrained()->cascadeOnDelete(); \u002F\u002F [!code ++]\n",[262,796,797],{"class":264,"line":476},[262,798,799],{},"        $table->foreignIdFor(User::class)->constrained()->cascadeOnDelete(); \u002F\u002F [!code ++]\n",[262,801,802],{"class":264,"line":482},[262,803,804],{},"        $table->text('content'); \u002F\u002F [!code ++]\n",[262,806,807],{"class":264,"line":643},[262,808,450],{"emptyLinePlaceholder":449},[262,810,811],{"class":264,"line":649},[262,812,473],{},[262,814,815],{"class":264,"line":655},[262,816,479],{},[262,818,819],{"class":264,"line":661},[262,820,485],{},[10,822,488],{},[252,824,827],{"className":491,"code":825,"filename":826,"language":269,"meta":258,"style":258},"use App\\Models\\Post; \u002F\u002F [!code ++]\nuse App\\Models\\User; \u002F\u002F [!code ++]\n\n\u002F\u002F ...\nclass CommentFactory extends Factory\n{\n    public function definition(): array\n    {\n        return [\n            'post_id' => Post::factory(), \u002F\u002F [!code ++]\n            'user_id' => User::factory(), \u002F\u002F [!code ++]\n            'content' => fake()->paragraph(), \u002F\u002F [!code ++]\n        ];\n    }\n}\n","database\u002Ffactories\u002FCommentFactory.php",[59,828,829,833,837,841,846,851,855,859,863,867,873,879,885,889,893],{"__ignoreMap":258},[262,830,831],{"class":264,"line":265},[262,832,759],{},[262,834,835],{"class":264,"line":289},[262,836,764],{},[262,838,839],{"class":264,"line":317},[262,840,450],{"emptyLinePlaceholder":449},[262,842,843],{"class":264,"line":346},[262,844,845],{},"\u002F\u002F ...\n",[262,847,848],{"class":264,"line":372},[262,849,850],{},"class CommentFactory extends Factory\n",[262,852,853],{"class":264,"line":453},[262,854,434],{},[262,856,857],{"class":264,"line":459},[262,858,509],{},[262,860,861],{"class":264,"line":465},[262,862,514],{},[262,864,865],{"class":264,"line":470},[262,866,519],{},[262,868,870],{"class":869,"line":476},[264,523,524],[262,871,872],{},"            'post_id' => Post::factory(),",[262,874,876],{"class":875,"line":482},[264,523,524],[262,877,878],{},"            'user_id' => User::factory(),",[262,880,882],{"class":881,"line":643},[264,523,524],[262,883,884],{},"            'content' => fake()->paragraph(),",[262,886,887],{"class":264,"line":649},[262,888,538],{},[262,890,891],{"class":264,"line":655},[262,892,543],{},[262,894,895],{"class":264,"line":661},[262,896,548],{},[10,898,899],{},"Add the corresponding test:",[252,901,904],{"className":420,"code":902,"filename":903,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\n\ntest('to array', function () {\n    $comment = Comment::factory()->create()->fresh();\n\n    expect(array_keys($comment->toArray()))\n        ->toEqual([\n            'id',\n            'post_id',\n            'user_id',\n            'content',\n            'created_at',\n            'updated_at',\n        ]);\n});\n","tests\u002FUnit\u002FModels\u002FCommentTest.php",[59,905,906,910,914,918,922,927,931,935,940,944,949,953,957,962,967,972,976,980,984],{"__ignoreMap":258},[262,907,908],{"class":264,"line":265},[262,909,594],{},[262,911,912],{"class":264,"line":289},[262,913,450],{"emptyLinePlaceholder":449},[262,915,916],{"class":264,"line":317},[262,917,603],{},[262,919,920],{"class":264,"line":346},[262,921,450],{"emptyLinePlaceholder":449},[262,923,924],{"class":264,"line":372},[262,925,926],{},"use App\\Models\\Comment;\n",[262,928,929],{"class":264,"line":453},[262,930,450],{"emptyLinePlaceholder":449},[262,932,933],{"class":264,"line":459},[262,934,621],{},[262,936,937],{"class":264,"line":465},[262,938,939],{},"    $comment = Comment::factory()->create()->fresh();\n",[262,941,942],{"class":264,"line":470},[262,943,450],{"emptyLinePlaceholder":449},[262,945,946],{"class":264,"line":476},[262,947,948],{},"    expect(array_keys($comment->toArray()))\n",[262,950,951],{"class":264,"line":482},[262,952,640],{},[262,954,955],{"class":264,"line":643},[262,956,646],{},[262,958,959],{"class":264,"line":649},[262,960,961],{},"            'post_id',\n",[262,963,964],{"class":264,"line":655},[262,965,966],{},"            'user_id',\n",[262,968,969],{"class":264,"line":661},[262,970,971],{},"            'content',\n",[262,973,974],{"class":264,"line":667},[262,975,664],{},[262,977,978],{"class":264,"line":673},[262,979,670],{},[262,981,982],{"class":264,"line":679},[262,983,676],{},[262,985,987],{"class":264,"line":986},19,[262,988,682],{},[10,990,991],{},"Now add the relationships. A post has many comments, a comment belongs to a post, a comment belongs to a user, and a user has many comments.",[36,993,994],{"color":38,"icon":39},[10,995,996,997,221,1000,1003,1004,1006],{},"We use ",[59,998,999],{},"belongs to",[59,1001,1002],{},"has one"," because a comment is a child of a post and cannot exist without one. A ",[59,1005,1002],{}," relationship describes a parent model's single child, such as a user having one profile while the profile belongs to the user.",[10,1008,1009],{},"These relationships are defined as follows:",[252,1011,1014],{"className":420,"code":1012,"filename":1013,"language":269,"meta":258,"style":258},"class Post extends Model\n{\n    \u002F**\n     * Get all of the comments for the Post\n     *\n     * @return HasMany\u003CComment, covariant Post>\n     *\u002F\n    public function comments(): HasMany\n    {\n        return $this->hasMany(Comment::class);\n    }\n}\n","app\u002FModels\u002FPost.php",[59,1015,1016,1021,1025,1030,1035,1040,1045,1050,1055,1059,1064,1068],{"__ignoreMap":258},[262,1017,1018],{"class":264,"line":265},[262,1019,1020],{},"class Post extends Model\n",[262,1022,1023],{"class":264,"line":289},[262,1024,434],{},[262,1026,1027],{"class":264,"line":317},[262,1028,1029],{},"    \u002F**\n",[262,1031,1032],{"class":264,"line":346},[262,1033,1034],{},"     * Get all of the comments for the Post\n",[262,1036,1037],{"class":264,"line":372},[262,1038,1039],{},"     *\n",[262,1041,1042],{"class":264,"line":453},[262,1043,1044],{},"     * @return HasMany\u003CComment, covariant Post>\n",[262,1046,1047],{"class":264,"line":459},[262,1048,1049],{},"     *\u002F\n",[262,1051,1052],{"class":264,"line":465},[262,1053,1054],{},"    public function comments(): HasMany\n",[262,1056,1057],{"class":264,"line":470},[262,1058,514],{},[262,1060,1061],{"class":264,"line":476},[262,1062,1063],{},"        return $this->hasMany(Comment::class);\n",[262,1065,1066],{"class":264,"line":482},[262,1067,543],{},[262,1069,1070],{"class":264,"line":643},[262,1071,548],{},[252,1073,1076],{"className":420,"code":1074,"filename":1075,"language":269,"meta":258,"style":258},"class Comment extends Model\n{\n    \u002F**\n     * Get the post that owns the comment.\n     *\n     * @return BelongsTo\u003CPost, covariant Comment>\n     *\u002F\n    public function post(): BelongsTo\n    {\n        return $this->belongsTo(Post::class);\n    }\n\n    \u002F**\n     * Get the user that owns the comment.\n     *\n     * @return BelongsTo\u003CUser, covariant Comment>\n     *\u002F\n    public function user(): BelongsTo\n    {\n        return $this->belongsTo(User::class);\n    }\n}\n","app\u002FModels\u002FComment.php",[59,1077,1078,1083,1087,1091,1096,1100,1105,1109,1114,1118,1123,1127,1131,1135,1140,1144,1149,1153,1158,1162,1168,1173],{"__ignoreMap":258},[262,1079,1080],{"class":264,"line":265},[262,1081,1082],{},"class Comment extends Model\n",[262,1084,1085],{"class":264,"line":289},[262,1086,434],{},[262,1088,1089],{"class":264,"line":317},[262,1090,1029],{},[262,1092,1093],{"class":264,"line":346},[262,1094,1095],{},"     * Get the post that owns the comment.\n",[262,1097,1098],{"class":264,"line":372},[262,1099,1039],{},[262,1101,1102],{"class":264,"line":453},[262,1103,1104],{},"     * @return BelongsTo\u003CPost, covariant Comment>\n",[262,1106,1107],{"class":264,"line":459},[262,1108,1049],{},[262,1110,1111],{"class":264,"line":465},[262,1112,1113],{},"    public function post(): BelongsTo\n",[262,1115,1116],{"class":264,"line":470},[262,1117,514],{},[262,1119,1120],{"class":264,"line":476},[262,1121,1122],{},"        return $this->belongsTo(Post::class);\n",[262,1124,1125],{"class":264,"line":482},[262,1126,543],{},[262,1128,1129],{"class":264,"line":643},[262,1130,450],{"emptyLinePlaceholder":449},[262,1132,1133],{"class":264,"line":649},[262,1134,1029],{},[262,1136,1137],{"class":264,"line":655},[262,1138,1139],{},"     * Get the user that owns the comment.\n",[262,1141,1142],{"class":264,"line":661},[262,1143,1039],{},[262,1145,1146],{"class":264,"line":667},[262,1147,1148],{},"     * @return BelongsTo\u003CUser, covariant Comment>\n",[262,1150,1151],{"class":264,"line":673},[262,1152,1049],{},[262,1154,1155],{"class":264,"line":679},[262,1156,1157],{},"    public function user(): BelongsTo\n",[262,1159,1160],{"class":264,"line":986},[262,1161,514],{},[262,1163,1165],{"class":264,"line":1164},20,[262,1166,1167],{},"        return $this->belongsTo(User::class);\n",[262,1169,1171],{"class":264,"line":1170},21,[262,1172,543],{},[262,1174,1176],{"class":264,"line":1175},22,[262,1177,548],{},[252,1179,1182],{"className":420,"code":1180,"filename":1181,"language":269,"meta":258,"style":258},"class User extends Authenticatable\n{\n    \u002F**\n     * Get comments that belong to the user.\n     *\n     * @return HasMany\u003CComment, covariant User>\n     *\u002F\n    public function comments(): HasMany\n    {\n        return $this->hasMany(Comment::class);\n    }\n}\n","app\u002FModels\u002FUser.php",[59,1183,1184,1189,1193,1197,1202,1206,1211,1215,1219,1223,1227,1231],{"__ignoreMap":258},[262,1185,1186],{"class":264,"line":265},[262,1187,1188],{},"class User extends Authenticatable\n",[262,1190,1191],{"class":264,"line":289},[262,1192,434],{},[262,1194,1195],{"class":264,"line":317},[262,1196,1029],{},[262,1198,1199],{"class":264,"line":346},[262,1200,1201],{},"     * Get comments that belong to the user.\n",[262,1203,1204],{"class":264,"line":372},[262,1205,1039],{},[262,1207,1208],{"class":264,"line":453},[262,1209,1210],{},"     * @return HasMany\u003CComment, covariant User>\n",[262,1212,1213],{"class":264,"line":459},[262,1214,1049],{},[262,1216,1217],{"class":264,"line":465},[262,1218,1054],{},[262,1220,1221],{"class":264,"line":470},[262,1222,514],{},[262,1224,1225],{"class":264,"line":476},[262,1226,1063],{},[262,1228,1229],{"class":264,"line":482},[262,1230,543],{},[262,1232,1233],{"class":264,"line":643},[262,1234,548],{},[10,1236,1237],{},"These relationships simplify Eloquent queries. To get all comments for a post, we can write:",[252,1239,1242],{"className":420,"code":1240,"filename":1241,"language":269,"meta":258,"style":258},"Post::find(1)->comments;\n","Example",[59,1243,1244],{"__ignoreMap":258},[262,1245,1246],{"class":264,"line":265},[262,1247,1240],{},[10,1249,1250,1251,1254,1255,1258],{},"They also help when using factory methods such as ",[59,1252,1253],{},"has"," and ",[59,1256,1257],{},"for"," to create related models.",[10,1260,1261],{},"Add relationship tests to ensure that the models are connected as expected.",[36,1263,1264],{"color":38,"icon":39},[10,1265,1266],{},"When working with models, I often write the tests after the first implementation because the design can change quickly. Writing the model helps me clarify what the tests should verify.",[252,1268,1270],{"className":420,"code":1269,"filename":587,"language":269,"meta":258,"style":258},"use App\\Models\\Comment;\n\ntest('relations', function () {\n    $post = Post::factory()\n        ->hasComments(1)\n        ->create();\n\n    expect($post->comments)->each->toBeInstanceOf(Comment::class);\n});\n",[59,1271,1272,1276,1280,1285,1290,1295,1300,1304,1309],{"__ignoreMap":258},[262,1273,1274],{"class":264,"line":265},[262,1275,926],{},[262,1277,1278],{"class":264,"line":289},[262,1279,450],{"emptyLinePlaceholder":449},[262,1281,1282],{"class":264,"line":317},[262,1283,1284],{},"test('relations', function () {\n",[262,1286,1287],{"class":264,"line":346},[262,1288,1289],{},"    $post = Post::factory()\n",[262,1291,1292],{"class":264,"line":372},[262,1293,1294],{},"        ->hasComments(1)\n",[262,1296,1297],{"class":264,"line":453},[262,1298,1299],{},"        ->create();\n",[262,1301,1302],{"class":264,"line":459},[262,1303,450],{"emptyLinePlaceholder":449},[262,1305,1306],{"class":264,"line":465},[262,1307,1308],{},"    expect($post->comments)->each->toBeInstanceOf(Comment::class);\n",[262,1310,1311],{"class":264,"line":470},[262,1312,682],{},[252,1314,1316],{"className":420,"code":1315,"filename":903,"language":269,"meta":258,"style":258},"use App\\Models\\Post;\nuse App\\Models\\User;\n\ntest('relations', function () {\n    $comment = Comment::factory()\n        ->forPost()\n        ->create();\n\n    expect($comment->post)->toBeInstanceOf(Post::class)\n        ->and($comment->user)->toBeInstanceOf(User::class);\n});\n",[59,1317,1318,1322,1327,1331,1335,1340,1345,1349,1353,1358,1363],{"__ignoreMap":258},[262,1319,1320],{"class":264,"line":265},[262,1321,612],{},[262,1323,1324],{"class":264,"line":289},[262,1325,1326],{},"use App\\Models\\User;\n",[262,1328,1329],{"class":264,"line":317},[262,1330,450],{"emptyLinePlaceholder":449},[262,1332,1333],{"class":264,"line":346},[262,1334,1284],{},[262,1336,1337],{"class":264,"line":372},[262,1338,1339],{},"    $comment = Comment::factory()\n",[262,1341,1342],{"class":264,"line":453},[262,1343,1344],{},"        ->forPost()\n",[262,1346,1347],{"class":264,"line":459},[262,1348,1299],{},[262,1350,1351],{"class":264,"line":465},[262,1352,450],{"emptyLinePlaceholder":449},[262,1354,1355],{"class":264,"line":470},[262,1356,1357],{},"    expect($comment->post)->toBeInstanceOf(Post::class)\n",[262,1359,1360],{"class":264,"line":476},[262,1361,1362],{},"        ->and($comment->user)->toBeInstanceOf(User::class);\n",[262,1364,1365],{"class":264,"line":482},[262,1366,682],{},[252,1368,1371],{"className":420,"code":1369,"filename":1370,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\nuse App\\Models\\User;\n\ntest('to array', function () {\n    $user = User::factory()->create()->fresh();\n\n    expect(array_keys($user->toArray()))\n        ->toEqual([\n            'id',\n            'name',\n            'username',\n            'email',\n            'email_verified_at',\n            'github_id',\n            'avatar',\n            'created_at',\n            'updated_at',\n        ]);\n});\n\ntest('relations', function () {\n    $user = User::factory()\n        ->hasComments(1)\n        ->create();\n\n    expect($user->comments)->each->toBeInstanceOf(Comment::class);\n});\n","tests\u002FUnit\u002FModels\u002FUserTest.php",[59,1372,1373,1377,1381,1385,1389,1393,1397,1401,1405,1410,1414,1419,1423,1427,1432,1437,1442,1447,1452,1457,1461,1465,1469,1474,1479,1484,1490,1495,1500,1505,1511],{"__ignoreMap":258},[262,1374,1375],{"class":264,"line":265},[262,1376,594],{},[262,1378,1379],{"class":264,"line":289},[262,1380,450],{"emptyLinePlaceholder":449},[262,1382,1383],{"class":264,"line":317},[262,1384,603],{},[262,1386,1387],{"class":264,"line":346},[262,1388,450],{"emptyLinePlaceholder":449},[262,1390,1391],{"class":264,"line":372},[262,1392,926],{},[262,1394,1395],{"class":264,"line":453},[262,1396,1326],{},[262,1398,1399],{"class":264,"line":459},[262,1400,450],{"emptyLinePlaceholder":449},[262,1402,1403],{"class":264,"line":465},[262,1404,621],{},[262,1406,1407],{"class":264,"line":470},[262,1408,1409],{},"    $user = User::factory()->create()->fresh();\n",[262,1411,1412],{"class":264,"line":476},[262,1413,450],{"emptyLinePlaceholder":449},[262,1415,1416],{"class":264,"line":482},[262,1417,1418],{},"    expect(array_keys($user->toArray()))\n",[262,1420,1421],{"class":264,"line":643},[262,1422,640],{},[262,1424,1425],{"class":264,"line":649},[262,1426,646],{},[262,1428,1429],{"class":264,"line":655},[262,1430,1431],{},"            'name',\n",[262,1433,1434],{"class":264,"line":661},[262,1435,1436],{},"            'username',\n",[262,1438,1439],{"class":264,"line":667},[262,1440,1441],{},"            'email',\n",[262,1443,1444],{"class":264,"line":673},[262,1445,1446],{},"            'email_verified_at',\n",[262,1448,1449],{"class":264,"line":679},[262,1450,1451],{},"            'github_id',\n",[262,1453,1454],{"class":264,"line":986},[262,1455,1456],{},"            'avatar',\n",[262,1458,1459],{"class":264,"line":1164},[262,1460,664],{},[262,1462,1463],{"class":264,"line":1170},[262,1464,670],{},[262,1466,1467],{"class":264,"line":1175},[262,1468,676],{},[262,1470,1472],{"class":264,"line":1471},23,[262,1473,682],{},[262,1475,1477],{"class":264,"line":1476},24,[262,1478,450],{"emptyLinePlaceholder":449},[262,1480,1482],{"class":264,"line":1481},25,[262,1483,1284],{},[262,1485,1487],{"class":264,"line":1486},26,[262,1488,1489],{},"    $user = User::factory()\n",[262,1491,1493],{"class":264,"line":1492},27,[262,1494,1294],{},[262,1496,1498],{"class":264,"line":1497},28,[262,1499,1299],{},[262,1501,1503],{"class":264,"line":1502},29,[262,1504,450],{"emptyLinePlaceholder":449},[262,1506,1508],{"class":264,"line":1507},30,[262,1509,1510],{},"    expect($user->comments)->each->toBeInstanceOf(Comment::class);\n",[262,1512,1514],{"class":264,"line":1513},31,[262,1515,682],{},[10,1517,1518,1519,1521],{},"We had not added any tests for ",[59,1520,104],{},", so this is a good opportunity to add its array-shape test as well.",[10,1523,1524],{},"The pattern is consistent, and Laravel makes each step straightforward.",[44,1526,1528],{"id":1527},"creating-the-controllers","Creating the controllers",[10,1530,1531],{},"Now that the models are ready, we can create the controllers.",[10,1533,1534,1536],{},[59,1535,351],{}," will have two methods:",[17,1538,1539,1548],{},[20,1540,1541,1544,1545,233],{},[59,1542,1543],{},"index",": lists all comments for a post through ",[59,1546,1547],{},"GET \u002Fposts\u002F{post}\u002Fcomments",[20,1549,1550,1553,1554,233],{},[59,1551,1552],{},"store",": creates a comment through ",[59,1555,1556],{},"POST \u002Fposts\u002F{post}\u002Fcomments",[10,1558,1559,1560,1562],{},"As in the previous article, let's start by writing a test for the ",[59,1561,1543],{}," method:",[252,1564,1567],{"className":420,"code":1565,"filename":1566,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\nuse App\\Models\\Post;\nuse Illuminate\\Testing\\Fluent\\AssertableJson;\n\nit('returns comments', function () {\n    $post = Post::factory()->create();\n    $comments = Comment::factory()\n        ->count(2)\n        ->for($post)\n        ->create();\n\n    $this->getJson(route('posts.comments', $post))\n        ->assertJson(\n            fn (AssertableJson $json) => $json\n                ->has(\n                    'data',\n                    2,\n                    fn (AssertableJson $json) => $json\n                        ->where('id', $comments->first()->id)\n                        ->where('content', $comments->first()->content)\n                        ->has(\n                            'author',\n                            fn (AssertableJson $json) => $json\n                                ->where('name', $comments->first()->user->name)\n                                ->where('username', $comments->first()->user->username)\n                                ->where('avatar', $comments->first()->user->avatar)\n                        )\n                )\n        );\n});\n","tests\u002FFeature\u002FHttp\u002FApi\u002FPost\u002FComment\u002FIndexTest.php",[59,1568,1569,1573,1577,1581,1585,1589,1593,1598,1602,1607,1612,1617,1622,1627,1631,1635,1640,1645,1650,1655,1660,1665,1670,1675,1680,1685,1690,1695,1700,1705,1710,1715,1721,1727],{"__ignoreMap":258},[262,1570,1571],{"class":264,"line":265},[262,1572,594],{},[262,1574,1575],{"class":264,"line":289},[262,1576,450],{"emptyLinePlaceholder":449},[262,1578,1579],{"class":264,"line":317},[262,1580,603],{},[262,1582,1583],{"class":264,"line":346},[262,1584,450],{"emptyLinePlaceholder":449},[262,1586,1587],{"class":264,"line":372},[262,1588,926],{},[262,1590,1591],{"class":264,"line":453},[262,1592,612],{},[262,1594,1595],{"class":264,"line":459},[262,1596,1597],{},"use Illuminate\\Testing\\Fluent\\AssertableJson;\n",[262,1599,1600],{"class":264,"line":465},[262,1601,450],{"emptyLinePlaceholder":449},[262,1603,1604],{"class":264,"line":470},[262,1605,1606],{},"it('returns comments', function () {\n",[262,1608,1609],{"class":264,"line":476},[262,1610,1611],{},"    $post = Post::factory()->create();\n",[262,1613,1614],{"class":264,"line":482},[262,1615,1616],{},"    $comments = Comment::factory()\n",[262,1618,1619],{"class":264,"line":643},[262,1620,1621],{},"        ->count(2)\n",[262,1623,1624],{"class":264,"line":649},[262,1625,1626],{},"        ->for($post)\n",[262,1628,1629],{"class":264,"line":655},[262,1630,1299],{},[262,1632,1633],{"class":264,"line":661},[262,1634,450],{"emptyLinePlaceholder":449},[262,1636,1637],{"class":264,"line":667},[262,1638,1639],{},"    $this->getJson(route('posts.comments', $post))\n",[262,1641,1642],{"class":264,"line":673},[262,1643,1644],{},"        ->assertJson(\n",[262,1646,1647],{"class":264,"line":679},[262,1648,1649],{},"            fn (AssertableJson $json) => $json\n",[262,1651,1652],{"class":264,"line":986},[262,1653,1654],{},"                ->has(\n",[262,1656,1657],{"class":264,"line":1164},[262,1658,1659],{},"                    'data',\n",[262,1661,1662],{"class":264,"line":1170},[262,1663,1664],{},"                    2,\n",[262,1666,1667],{"class":264,"line":1175},[262,1668,1669],{},"                    fn (AssertableJson $json) => $json\n",[262,1671,1672],{"class":264,"line":1471},[262,1673,1674],{},"                        ->where('id', $comments->first()->id)\n",[262,1676,1677],{"class":264,"line":1476},[262,1678,1679],{},"                        ->where('content', $comments->first()->content)\n",[262,1681,1682],{"class":264,"line":1481},[262,1683,1684],{},"                        ->has(\n",[262,1686,1687],{"class":264,"line":1486},[262,1688,1689],{},"                            'author',\n",[262,1691,1692],{"class":264,"line":1492},[262,1693,1694],{},"                            fn (AssertableJson $json) => $json\n",[262,1696,1697],{"class":264,"line":1497},[262,1698,1699],{},"                                ->where('name', $comments->first()->user->name)\n",[262,1701,1702],{"class":264,"line":1502},[262,1703,1704],{},"                                ->where('username', $comments->first()->user->username)\n",[262,1706,1707],{"class":264,"line":1507},[262,1708,1709],{},"                                ->where('avatar', $comments->first()->user->avatar)\n",[262,1711,1712],{"class":264,"line":1513},[262,1713,1714],{},"                        )\n",[262,1716,1718],{"class":264,"line":1717},32,[262,1719,1720],{},"                )\n",[262,1722,1724],{"class":264,"line":1723},33,[262,1725,1726],{},"        );\n",[262,1728,1730],{"class":264,"line":1729},34,[262,1731,682],{},[10,1733,1734,1735,1738],{},"For HTTP tests, I use the ",[59,1736,1737],{},"AAA"," pattern:",[17,1740,1741,1744,1747],{},[20,1742,1743],{},"Arrange: prepare the data",[20,1745,1746],{},"Act: call the method",[20,1748,1749],{},"Assert: check the result",[10,1751,1752,1753,1756,1757,1759,1760,1763,1764,1767],{},"In this test, we create a post and two comments for it. That is the ",[59,1754,1755],{},"Arrange"," step. We then call ",[59,1758,1547],{},", which is the ",[59,1761,1762],{},"Act"," step. Finally, we verify that the response contains two comments and has the expected structure, which is the ",[59,1765,1766],{},"Assert"," step.",[10,1769,1770,1771,1773],{},"The failing test tells us to add a route in ",[59,1772,378],{},":",[252,1775,1777],{"className":420,"code":1776,"filename":378,"language":269,"meta":258,"style":258},"\u003C?php\n\nuse Illuminate\\Support\\Facades\\Route;\nuse App\\Http\\Controllers\\Api\\PostCommentController;\n\nRoute::get('\u002Fposts\u002F{post}\u002Fcomments', [PostCommentController::class, 'index'])\n    ->name('posts.comments');\n",[59,1778,1779,1783,1787,1792,1797,1801,1806],{"__ignoreMap":258},[262,1780,1781],{"class":264,"line":265},[262,1782,594],{},[262,1784,1785],{"class":264,"line":289},[262,1786,450],{"emptyLinePlaceholder":449},[262,1788,1789],{"class":264,"line":317},[262,1790,1791],{},"use Illuminate\\Support\\Facades\\Route;\n",[262,1793,1794],{"class":264,"line":346},[262,1795,1796],{},"use App\\Http\\Controllers\\Api\\PostCommentController;\n",[262,1798,1799],{"class":264,"line":372},[262,1800,450],{"emptyLinePlaceholder":449},[262,1802,1803],{"class":264,"line":453},[262,1804,1805],{},"Route::get('\u002Fposts\u002F{post}\u002Fcomments', [PostCommentController::class, 'index'])\n",[262,1807,1808],{"class":264,"line":459},[262,1809,1810],{},"    ->name('posts.comments');\n",[10,1812,1813,1814,704],{},"Then, we must instruct Laravel to read this file by updating the ",[59,1815,1816],{},"bootstrap\u002Fapp.php",[252,1818,1820],{"className":420,"code":1819,"filename":1816,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse Illuminate\\Foundation\\Application;\nuse Illuminate\\Foundation\\Configuration\\Exceptions;\nuse Illuminate\\Foundation\\Configuration\\Middleware;\n\nreturn Application::configure(basePath: dirname(__DIR__))\n    ->withRouting(\n        web: __DIR__.'\u002F..\u002Froutes\u002Fweb.php',\n        api: __DIR__.'\u002F..\u002Froutes\u002Fapi.php', \u002F\u002F [!code ++]\n        commands: __DIR__.'\u002F..\u002Froutes\u002Fconsole.php',\n        health: '\u002Fup',\n    )\n",[59,1821,1822,1826,1830,1834,1838,1843,1848,1853,1857,1862,1867,1872,1877,1882,1887],{"__ignoreMap":258},[262,1823,1824],{"class":264,"line":265},[262,1825,594],{},[262,1827,1828],{"class":264,"line":289},[262,1829,450],{"emptyLinePlaceholder":449},[262,1831,1832],{"class":264,"line":317},[262,1833,603],{},[262,1835,1836],{"class":264,"line":346},[262,1837,450],{"emptyLinePlaceholder":449},[262,1839,1840],{"class":264,"line":372},[262,1841,1842],{},"use Illuminate\\Foundation\\Application;\n",[262,1844,1845],{"class":264,"line":453},[262,1846,1847],{},"use Illuminate\\Foundation\\Configuration\\Exceptions;\n",[262,1849,1850],{"class":264,"line":459},[262,1851,1852],{},"use Illuminate\\Foundation\\Configuration\\Middleware;\n",[262,1854,1855],{"class":264,"line":465},[262,1856,450],{"emptyLinePlaceholder":449},[262,1858,1859],{"class":264,"line":470},[262,1860,1861],{},"return Application::configure(basePath: dirname(__DIR__))\n",[262,1863,1864],{"class":264,"line":476},[262,1865,1866],{},"    ->withRouting(\n",[262,1868,1869],{"class":264,"line":482},[262,1870,1871],{},"        web: __DIR__.'\u002F..\u002Froutes\u002Fweb.php',\n",[262,1873,1874],{"class":264,"line":643},[262,1875,1876],{},"        api: __DIR__.'\u002F..\u002Froutes\u002Fapi.php', \u002F\u002F [!code ++]\n",[262,1878,1879],{"class":264,"line":649},[262,1880,1881],{},"        commands: __DIR__.'\u002F..\u002Froutes\u002Fconsole.php',\n",[262,1883,1884],{"class":264,"line":655},[262,1885,1886],{},"        health: '\u002Fup',\n",[262,1888,1889],{"class":264,"line":661},[262,1890,1891],{},"    )\n",[10,1893,1894,1895,1562],{},"Finally, create the controller with an ",[59,1896,1543],{},[252,1898,1899],{"className":254,"code":356,"filename":256,"language":257,"meta":258,"style":258},[59,1900,1901],{"__ignoreMap":258},[262,1902,1903,1905,1907,1909],{"class":264,"line":265},[262,1904,269],{"class":268},[262,1906,273],{"class":272},[262,1908,340],{"class":272},[262,1910,369],{"class":272},[252,1912,1915],{"className":420,"code":1913,"filename":1914,"language":269,"meta":258,"style":258},"\u003C?php\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Controllers\\Controller;\nuse Illuminate\\Http\\Request;\n\nclass PostCommentController extends Controller\n{\n    public function index(Request $request)\n    {\n        \u002F\u002F\n    }\n}\n","app\u002FHttp\u002FApi\u002FPostCommentController.php",[59,1916,1917,1921,1925,1930,1934,1939,1944,1948,1953,1957,1962,1966,1971,1975],{"__ignoreMap":258},[262,1918,1919],{"class":264,"line":265},[262,1920,594],{},[262,1922,1923],{"class":264,"line":289},[262,1924,450],{"emptyLinePlaceholder":449},[262,1926,1927],{"class":264,"line":317},[262,1928,1929],{},"namespace App\\Http\\Controllers\\Api;\n",[262,1931,1932],{"class":264,"line":346},[262,1933,450],{"emptyLinePlaceholder":449},[262,1935,1936],{"class":264,"line":372},[262,1937,1938],{},"use App\\Http\\Controllers\\Controller;\n",[262,1940,1941],{"class":264,"line":453},[262,1942,1943],{},"use Illuminate\\Http\\Request;\n",[262,1945,1946],{"class":264,"line":459},[262,1947,450],{"emptyLinePlaceholder":449},[262,1949,1950],{"class":264,"line":465},[262,1951,1952],{},"class PostCommentController extends Controller\n",[262,1954,1955],{"class":264,"line":470},[262,1956,434],{},[262,1958,1959],{"class":264,"line":476},[262,1960,1961],{},"    public function index(Request $request)\n",[262,1963,1964],{"class":264,"line":482},[262,1965,514],{},[262,1967,1968],{"class":264,"line":643},[262,1969,1970],{},"        \u002F\u002F\n",[262,1972,1973],{"class":264,"line":649},[262,1974,543],{},[262,1976,1977],{"class":264,"line":655},[262,1978,548],{},[10,1980,1981],{},"The route now exists, but the test reports that the response is not valid JSON because the controller does not return anything. 😄",[10,1983,1984],{},"Use that failure as the next implementation step:",[252,1986,1988],{"className":420,"code":1987,"filename":1914,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Controllers\\Controller;\nuse App\\Http\\Resources\\CommentResource;\nuse App\\Models\\Comment;\nuse Illuminate\\Http\\Resources\\Json\\ResourceCollection;\n\nfinal class PostCommentController extends Controller\n{\n    public function index(): ResourceCollection\n    {\n        $comments = Comment::query()\n          ->with('user')\n          ->get();\n\n        return CommentResource::collection($comments);\n    }\n}\n",[59,1989,1990,1994,1998,2002,2006,2010,2014,2018,2023,2027,2032,2036,2041,2045,2050,2054,2059,2064,2069,2073,2078,2082],{"__ignoreMap":258},[262,1991,1992],{"class":264,"line":265},[262,1993,594],{},[262,1995,1996],{"class":264,"line":289},[262,1997,450],{"emptyLinePlaceholder":449},[262,1999,2000],{"class":264,"line":317},[262,2001,603],{},[262,2003,2004],{"class":264,"line":346},[262,2005,450],{"emptyLinePlaceholder":449},[262,2007,2008],{"class":264,"line":372},[262,2009,1929],{},[262,2011,2012],{"class":264,"line":453},[262,2013,450],{"emptyLinePlaceholder":449},[262,2015,2016],{"class":264,"line":459},[262,2017,1938],{},[262,2019,2020],{"class":264,"line":465},[262,2021,2022],{},"use App\\Http\\Resources\\CommentResource;\n",[262,2024,2025],{"class":264,"line":470},[262,2026,926],{},[262,2028,2029],{"class":264,"line":476},[262,2030,2031],{},"use Illuminate\\Http\\Resources\\Json\\ResourceCollection;\n",[262,2033,2034],{"class":264,"line":482},[262,2035,450],{"emptyLinePlaceholder":449},[262,2037,2038],{"class":264,"line":643},[262,2039,2040],{},"final class PostCommentController extends Controller\n",[262,2042,2043],{"class":264,"line":649},[262,2044,434],{},[262,2046,2047],{"class":264,"line":655},[262,2048,2049],{},"    public function index(): ResourceCollection\n",[262,2051,2052],{"class":264,"line":661},[262,2053,514],{},[262,2055,2056],{"class":264,"line":667},[262,2057,2058],{},"        $comments = Comment::query()\n",[262,2060,2061],{"class":264,"line":673},[262,2062,2063],{},"          ->with('user')\n",[262,2065,2066],{"class":264,"line":679},[262,2067,2068],{},"          ->get();\n",[262,2070,2071],{"class":264,"line":986},[262,2072,450],{"emptyLinePlaceholder":449},[262,2074,2075],{"class":264,"line":1164},[262,2076,2077],{},"        return CommentResource::collection($comments);\n",[262,2079,2080],{"class":264,"line":1170},[262,2081,543],{},[262,2083,2084],{"class":264,"line":1175},[262,2085,548],{},[10,2087,154,2088,2090,2091,2094],{},[59,2089,1543],{}," method retrieves the comments, eager-loads the user relationship, and returns a ",[59,2092,2093],{},"CommentResource"," collection.",[36,2096,2097],{"color":38,"icon":39},[10,2098,2099],{},"Retrieving every record is usually not a good practice; pagination is safer for a large collection. In this example, we expect only a small number of comments, so returning the collection is acceptable. Pagination can be added later if that assumption changes.",[10,2101,2102,2103,2105],{},"Now, we need to create the ",[59,2104,2093],{}," class:",[252,2107,2109],{"className":254,"code":2108,"filename":256,"language":257,"meta":258,"style":258},"php artisan make:resource CommentResource\n",[59,2110,2111],{"__ignoreMap":258},[262,2112,2113,2115,2117,2120],{"class":264,"line":265},[262,2114,269],{"class":268},[262,2116,273],{"class":272},[262,2118,2119],{"class":272}," make:resource",[262,2121,2122],{"class":272}," CommentResource\n",[252,2124,2127],{"className":420,"code":2125,"filename":2126,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Resources;\n\nuse App\\Models\\Comment;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\n\u002F**\n * @mixin Comment\n *\u002F\nfinal class CommentResource extends JsonResource\n{\n    \u002F**\n     * Transform the resource into an array.\n     *\n     * @return array\u003Cstring, mixed>\n     *\u002F\n    public function toArray(Request $request): array\n    {\n        return [\n            'id' => $this->id,\n            'content' => $this->content,\n            'author' => UserResource::make($this->whenLoaded('user')),\n        ];\n    }\n}\n","app\u002FHttp\u002FResources\u002FCommentResource.php",[59,2128,2129,2133,2137,2141,2145,2150,2154,2158,2162,2167,2171,2176,2181,2186,2191,2195,2199,2204,2208,2213,2217,2222,2226,2230,2235,2240,2245,2249,2253],{"__ignoreMap":258},[262,2130,2131],{"class":264,"line":265},[262,2132,594],{},[262,2134,2135],{"class":264,"line":289},[262,2136,450],{"emptyLinePlaceholder":449},[262,2138,2139],{"class":264,"line":317},[262,2140,603],{},[262,2142,2143],{"class":264,"line":346},[262,2144,450],{"emptyLinePlaceholder":449},[262,2146,2147],{"class":264,"line":372},[262,2148,2149],{},"namespace App\\Http\\Resources;\n",[262,2151,2152],{"class":264,"line":453},[262,2153,450],{"emptyLinePlaceholder":449},[262,2155,2156],{"class":264,"line":459},[262,2157,926],{},[262,2159,2160],{"class":264,"line":465},[262,2161,1943],{},[262,2163,2164],{"class":264,"line":470},[262,2165,2166],{},"use Illuminate\\Http\\Resources\\Json\\JsonResource;\n",[262,2168,2169],{"class":264,"line":476},[262,2170,450],{"emptyLinePlaceholder":449},[262,2172,2173],{"class":264,"line":482},[262,2174,2175],{},"\u002F**\n",[262,2177,2178],{"class":264,"line":643},[262,2179,2180],{}," * @mixin Comment\n",[262,2182,2183],{"class":264,"line":649},[262,2184,2185],{}," *\u002F\n",[262,2187,2188],{"class":264,"line":655},[262,2189,2190],{},"final class CommentResource extends JsonResource\n",[262,2192,2193],{"class":264,"line":661},[262,2194,434],{},[262,2196,2197],{"class":264,"line":667},[262,2198,1029],{},[262,2200,2201],{"class":264,"line":673},[262,2202,2203],{},"     * Transform the resource into an array.\n",[262,2205,2206],{"class":264,"line":679},[262,2207,1039],{},[262,2209,2210],{"class":264,"line":986},[262,2211,2212],{},"     * @return array\u003Cstring, mixed>\n",[262,2214,2215],{"class":264,"line":1164},[262,2216,1049],{},[262,2218,2219],{"class":264,"line":1170},[262,2220,2221],{},"    public function toArray(Request $request): array\n",[262,2223,2224],{"class":264,"line":1175},[262,2225,514],{},[262,2227,2228],{"class":264,"line":1471},[262,2229,519],{},[262,2231,2232],{"class":264,"line":1476},[262,2233,2234],{},"            'id' => $this->id,\n",[262,2236,2237],{"class":264,"line":1481},[262,2238,2239],{},"            'content' => $this->content,\n",[262,2241,2242],{"class":264,"line":1486},[262,2243,2244],{},"            'author' => UserResource::make($this->whenLoaded('user')),\n",[262,2246,2247],{"class":264,"line":1492},[262,2248,538],{},[262,2250,2251],{"class":264,"line":1497},[262,2252,543],{},[262,2254,2255],{"class":264,"line":1502},[262,2256,548],{},[10,2258,2259],{},"And a second resource for the author:",[252,2261,2263],{"className":254,"code":2262,"filename":256,"language":257,"meta":258,"style":258},"php artisan make:resource UserResource\n",[59,2264,2265],{"__ignoreMap":258},[262,2266,2267,2269,2271,2273],{"class":264,"line":265},[262,2268,269],{"class":268},[262,2270,273],{"class":272},[262,2272,2119],{"class":272},[262,2274,2275],{"class":272}," UserResource\n",[252,2277,2280],{"className":420,"code":2278,"filename":2279,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Resources;\n\nuse App\\Models\\User;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\n\u002F**\n * @mixin User\n *\u002F\nfinal class UserResource extends JsonResource\n{\n    \u002F**\n     * Transform the resource into an array.\n     *\n     * @return array\u003Cstring, mixed>\n     *\u002F\n    public function toArray(Request $request): array\n    {\n        return [\n            'name' => $this->name,\n            'username' => $this->username,\n            'avatar' => $this->avatar,\n        ];\n    }\n}\n","app\u002FHttp\u002FResources\u002FUserResource.php",[59,2281,2282,2286,2290,2294,2298,2302,2306,2310,2314,2318,2322,2326,2331,2335,2340,2344,2348,2352,2356,2360,2364,2368,2372,2376,2381,2386,2391,2395,2399],{"__ignoreMap":258},[262,2283,2284],{"class":264,"line":265},[262,2285,594],{},[262,2287,2288],{"class":264,"line":289},[262,2289,450],{"emptyLinePlaceholder":449},[262,2291,2292],{"class":264,"line":317},[262,2293,603],{},[262,2295,2296],{"class":264,"line":346},[262,2297,450],{"emptyLinePlaceholder":449},[262,2299,2300],{"class":264,"line":372},[262,2301,2149],{},[262,2303,2304],{"class":264,"line":453},[262,2305,450],{"emptyLinePlaceholder":449},[262,2307,2308],{"class":264,"line":459},[262,2309,1326],{},[262,2311,2312],{"class":264,"line":465},[262,2313,1943],{},[262,2315,2316],{"class":264,"line":470},[262,2317,2166],{},[262,2319,2320],{"class":264,"line":476},[262,2321,450],{"emptyLinePlaceholder":449},[262,2323,2324],{"class":264,"line":482},[262,2325,2175],{},[262,2327,2328],{"class":264,"line":643},[262,2329,2330],{}," * @mixin User\n",[262,2332,2333],{"class":264,"line":649},[262,2334,2185],{},[262,2336,2337],{"class":264,"line":655},[262,2338,2339],{},"final class UserResource extends JsonResource\n",[262,2341,2342],{"class":264,"line":661},[262,2343,434],{},[262,2345,2346],{"class":264,"line":667},[262,2347,1029],{},[262,2349,2350],{"class":264,"line":673},[262,2351,2203],{},[262,2353,2354],{"class":264,"line":679},[262,2355,1039],{},[262,2357,2358],{"class":264,"line":986},[262,2359,2212],{},[262,2361,2362],{"class":264,"line":1164},[262,2363,1049],{},[262,2365,2366],{"class":264,"line":1170},[262,2367,2221],{},[262,2369,2370],{"class":264,"line":1175},[262,2371,514],{},[262,2373,2374],{"class":264,"line":1471},[262,2375,519],{},[262,2377,2378],{"class":264,"line":1476},[262,2379,2380],{},"            'name' => $this->name,\n",[262,2382,2383],{"class":264,"line":1481},[262,2384,2385],{},"            'username' => $this->username,\n",[262,2387,2388],{"class":264,"line":1486},[262,2389,2390],{},"            'avatar' => $this->avatar,\n",[262,2392,2393],{"class":264,"line":1492},[262,2394,538],{},[262,2396,2397],{"class":264,"line":1497},[262,2398,543],{},[262,2400,2401],{"class":264,"line":1502},[262,2402,548],{},[10,2404,2405],{},"What are these resources?",[10,2407,2408],{},"A resource is a transformation layer between our Eloquent models and the JSON responses sent to the client. It defines how a model is transformed into JSON.",[10,2410,2411,2412,2414,2415,2417,2418,2421,2422,2414,2425,2417,2428,2431],{},"Here, we return a comment's ",[59,2413,61],{},", ",[59,2416,79],{},", and ",[59,2419,2420],{},"author",". The nested author resource exposes only the user's ",[59,2423,2424],{},"name",[59,2426,2427],{},"username",[59,2429,2430],{},"avatar",". This lets us change the response shape without changing the controller and prevents accidental exposure of fields such as the user's email.",[10,2433,2434],{},"Now, we can run our test and it should pass. But let's not be too hasty and add a test to verify that this method only returns the comments for the post:",[252,2436,2438],{"className":420,"code":2437,"filename":1566,"language":269,"meta":258,"style":258},"it('returns comments for a post', function () {\n    Comment::factory()\n        ->count(2)\n        ->create();\n\n    $this->getJson(route('posts.comments', Post::factory()->create()))\n        ->assertJson(\n            fn (AssertableJson $json) => $json\n                ->has('data', 0)\n        );\n});\n",[59,2439,2440,2445,2450,2454,2458,2462,2467,2471,2475,2480,2484],{"__ignoreMap":258},[262,2441,2442],{"class":264,"line":265},[262,2443,2444],{},"it('returns comments for a post', function () {\n",[262,2446,2447],{"class":264,"line":289},[262,2448,2449],{},"    Comment::factory()\n",[262,2451,2452],{"class":264,"line":317},[262,2453,1621],{},[262,2455,2456],{"class":264,"line":346},[262,2457,1299],{},[262,2459,2460],{"class":264,"line":372},[262,2461,450],{"emptyLinePlaceholder":449},[262,2463,2464],{"class":264,"line":453},[262,2465,2466],{},"    $this->getJson(route('posts.comments', Post::factory()->create()))\n",[262,2468,2469],{"class":264,"line":459},[262,2470,1644],{},[262,2472,2473],{"class":264,"line":465},[262,2474,1649],{},[262,2476,2477],{"class":264,"line":470},[262,2478,2479],{},"                ->has('data', 0)\n",[262,2481,2482],{"class":264,"line":476},[262,2483,1726],{},[262,2485,2486],{"class":264,"line":482},[262,2487,682],{},[10,2489,2490],{},"This test creates two comments for one post, calls the route with another post, and expects an empty response.",[10,2492,2493],{},"The test fails because the controller is not filtering comments by post.",[10,2495,2496,2497,1562],{},"To fix this, we can update the ",[59,2498,1543],{},[252,2500,2502],{"className":420,"code":2501,"filename":1914,"language":269,"meta":258,"style":258},"use App\\Models\\Post;\n\nfinal class PostCommentController extends Controller\n{\n    public function index(Post $post): ResourceCollection\n    {\n        $comments = Comment::query()\n            ->whereBelongsTo($post)\n            ->with('user')\n            ->get();\n\n        return CommentResource::collection($comments);\n    }\n}\n",[59,2503,2504,2508,2512,2516,2520,2525,2529,2533,2538,2543,2548,2552,2556,2560],{"__ignoreMap":258},[262,2505,2506],{"class":264,"line":265},[262,2507,612],{},[262,2509,2510],{"class":264,"line":289},[262,2511,450],{"emptyLinePlaceholder":449},[262,2513,2514],{"class":264,"line":317},[262,2515,2040],{},[262,2517,2518],{"class":264,"line":346},[262,2519,434],{},[262,2521,2522],{"class":264,"line":372},[262,2523,2524],{},"    public function index(Post $post): ResourceCollection\n",[262,2526,2527],{"class":264,"line":453},[262,2528,514],{},[262,2530,2531],{"class":264,"line":459},[262,2532,2058],{},[262,2534,2535],{"class":264,"line":465},[262,2536,2537],{},"            ->whereBelongsTo($post)\n",[262,2539,2540],{"class":264,"line":470},[262,2541,2542],{},"            ->with('user')\n",[262,2544,2545],{"class":264,"line":476},[262,2546,2547],{},"            ->get();\n",[262,2549,2550],{"class":264,"line":482},[262,2551,450],{"emptyLinePlaceholder":449},[262,2553,2554],{"class":264,"line":643},[262,2555,2077],{},[262,2557,2558],{"class":264,"line":649},[262,2559,543],{},[262,2561,2562],{"class":264,"line":655},[262,2563,548],{},[10,2565,2566,2567,2569,2570,2573,2574,2576],{},"Laravel's route model binding gives us the ",[59,2568,121],{}," instance directly. Because the route contains ",[59,2571,2572],{},"{post}"," and the method accepts a ",[59,2575,121],{},", Laravel finds the matching record and injects it. This keeps the controller concise.",[10,2578,2579],{},"Now, we can run our tests and they should pass. 👌",[10,2581,2582,2583,2585],{},"Now move on to the ",[59,2584,1552],{}," method.",[10,2587,2588],{},"You know the drill, let's start by writing a test:",[252,2590,2593],{"className":420,"code":2591,"filename":2592,"language":269,"meta":258,"style":258},"\u003C?php\n\nuse App\\Models\\Post;\n\nit('requires authentication', function () {\n    $post = Post::factory()->create();\n\n    $this->postJson(route('posts.comments.store', $post))\n        ->assertUnauthorized();\n});\n","tests\u002FFeature\u002FHttp\u002FApi\u002FPost\u002FComment\u002FStoreTest.php",[59,2594,2595,2599,2603,2607,2611,2616,2620,2624,2629,2634],{"__ignoreMap":258},[262,2596,2597],{"class":264,"line":265},[262,2598,594],{},[262,2600,2601],{"class":264,"line":289},[262,2602,450],{"emptyLinePlaceholder":449},[262,2604,2605],{"class":264,"line":317},[262,2606,612],{},[262,2608,2609],{"class":264,"line":346},[262,2610,450],{"emptyLinePlaceholder":449},[262,2612,2613],{"class":264,"line":372},[262,2614,2615],{},"it('requires authentication', function () {\n",[262,2617,2618],{"class":264,"line":453},[262,2619,1611],{},[262,2621,2622],{"class":264,"line":459},[262,2623,450],{"emptyLinePlaceholder":449},[262,2625,2626],{"class":264,"line":465},[262,2627,2628],{},"    $this->postJson(route('posts.comments.store', $post))\n",[262,2630,2631],{"class":264,"line":470},[262,2632,2633],{},"        ->assertUnauthorized();\n",[262,2635,2636],{"class":264,"line":476},[262,2637,682],{},[10,2639,2640],{},"This test verifies that authentication is required. Add the route:",[252,2642,2644],{"className":420,"code":2643,"filename":378,"language":269,"meta":258,"style":258},"Route::middleware('auth')->group(function () {\n    Route::post('\u002Fposts\u002F{post}\u002Fcomments', [PostCommentController::class, 'store'])\n        ->name('posts.comments.store');\n});\n",[59,2645,2646,2651,2656,2661],{"__ignoreMap":258},[262,2647,2648],{"class":264,"line":265},[262,2649,2650],{},"Route::middleware('auth')->group(function () {\n",[262,2652,2653],{"class":264,"line":289},[262,2654,2655],{},"    Route::post('\u002Fposts\u002F{post}\u002Fcomments', [PostCommentController::class, 'store'])\n",[262,2657,2658],{"class":264,"line":317},[262,2659,2660],{},"        ->name('posts.comments.store');\n",[262,2662,2663],{"class":264,"line":346},[262,2664,682],{},[10,2666,2667],{},"Continuing with another test:",[252,2669,2671],{"className":420,"code":2670,"filename":2592,"language":269,"meta":258,"style":258},"use App\\Models\\User;\n\n\u002F\u002F ...\n\nit('stores a comment', function () {\n    $user = User::factory()->create();\n    $post = Post::factory()->create();\n\n    $this->actingAs($user)\n        ->postJson(route('posts.comments.store', $post), [\n            'content' => 'This is a comment',\n        ]);\n\n    $this->assertDatabaseHas('comments', [\n        'post_id' => $post->id,\n        'user_id' => $user->id,\n        'content' => 'This is a comment',\n    ]);\n});\n",[59,2672,2673,2677,2681,2685,2689,2694,2699,2703,2707,2712,2717,2722,2726,2730,2735,2740,2745,2750,2755],{"__ignoreMap":258},[262,2674,2675],{"class":264,"line":265},[262,2676,1326],{},[262,2678,2679],{"class":264,"line":289},[262,2680,450],{"emptyLinePlaceholder":449},[262,2682,2683],{"class":264,"line":317},[262,2684,845],{},[262,2686,2687],{"class":264,"line":346},[262,2688,450],{"emptyLinePlaceholder":449},[262,2690,2691],{"class":264,"line":372},[262,2692,2693],{},"it('stores a comment', function () {\n",[262,2695,2696],{"class":264,"line":453},[262,2697,2698],{},"    $user = User::factory()->create();\n",[262,2700,2701],{"class":264,"line":459},[262,2702,1611],{},[262,2704,2705],{"class":264,"line":465},[262,2706,450],{"emptyLinePlaceholder":449},[262,2708,2709],{"class":264,"line":470},[262,2710,2711],{},"    $this->actingAs($user)\n",[262,2713,2714],{"class":264,"line":476},[262,2715,2716],{},"        ->postJson(route('posts.comments.store', $post), [\n",[262,2718,2719],{"class":264,"line":482},[262,2720,2721],{},"            'content' => 'This is a comment',\n",[262,2723,2724],{"class":264,"line":643},[262,2725,676],{},[262,2727,2728],{"class":264,"line":649},[262,2729,450],{"emptyLinePlaceholder":449},[262,2731,2732],{"class":264,"line":655},[262,2733,2734],{},"    $this->assertDatabaseHas('comments', [\n",[262,2736,2737],{"class":264,"line":661},[262,2738,2739],{},"        'post_id' => $post->id,\n",[262,2741,2742],{"class":264,"line":667},[262,2743,2744],{},"        'user_id' => $user->id,\n",[262,2746,2747],{"class":264,"line":673},[262,2748,2749],{},"        'content' => 'This is a comment',\n",[262,2751,2752],{"class":264,"line":679},[262,2753,2754],{},"    ]);\n",[262,2756,2757],{"class":264,"line":986},[262,2758,682],{},[10,2760,2761,2762,2414,2764,2766],{},"This test verifies that the comment is stored with the correct ",[59,2763,67],{},[59,2765,73],{},", and content. The controller sets the two foreign keys.",[10,2768,2769,2770,1562],{},"Now, we can implement the ",[59,2771,1552],{},[252,2773,2775],{"className":420,"code":2774,"filename":1914,"language":269,"meta":258,"style":258},"final class PostCommentController extends Controller\n{\n    public function store(Request $request, Post $post)\n    {\n        Comment::create([\n            'post_id' => $post->id,\n            'user_id' => $request->user()->id,\n            'content' => $request->input('content')\n        ]);\n    }\n}\n",[59,2776,2777,2781,2785,2790,2794,2799,2804,2809,2814,2818,2822],{"__ignoreMap":258},[262,2778,2779],{"class":264,"line":265},[262,2780,2040],{},[262,2782,2783],{"class":264,"line":289},[262,2784,434],{},[262,2786,2787],{"class":264,"line":317},[262,2788,2789],{},"    public function store(Request $request, Post $post)\n",[262,2791,2792],{"class":264,"line":346},[262,2793,514],{},[262,2795,2796],{"class":264,"line":372},[262,2797,2798],{},"        Comment::create([\n",[262,2800,2801],{"class":264,"line":453},[262,2802,2803],{},"            'post_id' => $post->id,\n",[262,2805,2806],{"class":264,"line":459},[262,2807,2808],{},"            'user_id' => $request->user()->id,\n",[262,2810,2811],{"class":264,"line":465},[262,2812,2813],{},"            'content' => $request->input('content')\n",[262,2815,2816],{"class":264,"line":470},[262,2817,676],{},[262,2819,2820],{"class":264,"line":476},[262,2821,543],{},[262,2823,2824],{"class":264,"line":482},[262,2825,548],{},[36,2827,2828],{"color":38,"icon":39},[10,2829,2830],{},"We are writing only the minimum code needed to make the tests pass. That does not mean the implementation is complete. For example, the request still needs validation, which we will add with the next test.",[10,2832,2833],{},"Add a test for request validation:",[252,2835,2837],{"className":420,"code":2836,"filename":2592,"language":269,"meta":258,"style":258},"it('requires a valid data', function (array $badData, array|string $errors) {\n    $post = Post::factory()->create();\n\n    $response = $this->actingAs(User::factory()->create())\n        ->postJson(route('posts.comments.store', $post), $badData);\n\n    $response->assertJsonValidationErrors($errors);\n})->with([\n    [['content' => ''], ['content' => 'The content field is required.']],\n    [['content' => 1], ['content' => 'The content field must be a string.']],\n    [['content' => 'a'], ['content' => 'The content field must be at least 6 characters.']],\n    [['content' => 'a'.str_repeat('a', 2001)], ['content' => 'The content field must not be greater than 2000 characters.']],\n]);\n",[59,2838,2839,2844,2848,2852,2857,2862,2866,2871,2876,2881,2886,2891,2896],{"__ignoreMap":258},[262,2840,2841],{"class":264,"line":265},[262,2842,2843],{},"it('requires a valid data', function (array $badData, array|string $errors) {\n",[262,2845,2846],{"class":264,"line":289},[262,2847,1611],{},[262,2849,2850],{"class":264,"line":317},[262,2851,450],{"emptyLinePlaceholder":449},[262,2853,2854],{"class":264,"line":346},[262,2855,2856],{},"    $response = $this->actingAs(User::factory()->create())\n",[262,2858,2859],{"class":264,"line":372},[262,2860,2861],{},"        ->postJson(route('posts.comments.store', $post), $badData);\n",[262,2863,2864],{"class":264,"line":453},[262,2865,450],{"emptyLinePlaceholder":449},[262,2867,2868],{"class":264,"line":459},[262,2869,2870],{},"    $response->assertJsonValidationErrors($errors);\n",[262,2872,2873],{"class":264,"line":465},[262,2874,2875],{},"})->with([\n",[262,2877,2878],{"class":264,"line":470},[262,2879,2880],{},"    [['content' => ''], ['content' => 'The content field is required.']],\n",[262,2882,2883],{"class":264,"line":476},[262,2884,2885],{},"    [['content' => 1], ['content' => 'The content field must be a string.']],\n",[262,2887,2888],{"class":264,"line":482},[262,2889,2890],{},"    [['content' => 'a'], ['content' => 'The content field must be at least 6 characters.']],\n",[262,2892,2893],{"class":264,"line":643},[262,2894,2895],{},"    [['content' => 'a'.str_repeat('a', 2001)], ['content' => 'The content field must not be greater than 2000 characters.']],\n",[262,2897,2898],{"class":264,"line":649},[262,2899,2900],{},"]);\n",[10,2902,2903],{},"Pest runs this test four times with different data. A dataset lets us cover several invalid inputs without duplicating the test body.",[10,2905,247,2906,2909],{},[59,2907,2908],{},"StoreCommentRequest"," class to hold these rules:",[252,2911,2913],{"className":254,"code":2912,"filename":256,"language":257,"meta":258,"style":258},"php artisan make:request StoreCommentRequest\n",[59,2914,2915],{"__ignoreMap":258},[262,2916,2917,2919,2921,2924],{"class":264,"line":265},[262,2918,269],{"class":268},[262,2920,273],{"class":272},[262,2922,2923],{"class":272}," make:request",[262,2925,2926],{"class":272}," StoreCommentRequest\n",[252,2928,2931],{"className":420,"code":2929,"filename":2930,"language":269,"meta":258,"style":258},"\u003C?php\n\nnamespace App\\Http\\Requests;\n\nuse Illuminate\\Foundation\\Http\\FormRequest;\n\nclass StoreCommentRequest extends FormRequest\n{\n    \u002F**\n     * Get the validation rules that apply to the request.\n     *\n     * @return array\u003Cstring, \\Illuminate\\Contracts\\Validation\\ValidationRule|array\u003Cmixed>|string>\n     *\u002F\n    public function rules(): array\n    {\n        return [\n            'content' => ['required', 'string', 'max:2000', 'min:6'],\n        ];\n    }\n}\n","app\u002FHttp\u002FRequests\u002FStoreCommentRequest.php",[59,2932,2933,2937,2941,2946,2950,2955,2959,2964,2968,2972,2977,2981,2986,2990,2995,2999,3003,3008,3012,3016],{"__ignoreMap":258},[262,2934,2935],{"class":264,"line":265},[262,2936,594],{},[262,2938,2939],{"class":264,"line":289},[262,2940,450],{"emptyLinePlaceholder":449},[262,2942,2943],{"class":264,"line":317},[262,2944,2945],{},"namespace App\\Http\\Requests;\n",[262,2947,2948],{"class":264,"line":346},[262,2949,450],{"emptyLinePlaceholder":449},[262,2951,2952],{"class":264,"line":372},[262,2953,2954],{},"use Illuminate\\Foundation\\Http\\FormRequest;\n",[262,2956,2957],{"class":264,"line":453},[262,2958,450],{"emptyLinePlaceholder":449},[262,2960,2961],{"class":264,"line":459},[262,2962,2963],{},"class StoreCommentRequest extends FormRequest\n",[262,2965,2966],{"class":264,"line":465},[262,2967,434],{},[262,2969,2970],{"class":264,"line":470},[262,2971,1029],{},[262,2973,2974],{"class":264,"line":476},[262,2975,2976],{},"     * Get the validation rules that apply to the request.\n",[262,2978,2979],{"class":264,"line":482},[262,2980,1039],{},[262,2982,2983],{"class":264,"line":643},[262,2984,2985],{},"     * @return array\u003Cstring, \\Illuminate\\Contracts\\Validation\\ValidationRule|array\u003Cmixed>|string>\n",[262,2987,2988],{"class":264,"line":649},[262,2989,1049],{},[262,2991,2992],{"class":264,"line":655},[262,2993,2994],{},"    public function rules(): array\n",[262,2996,2997],{"class":264,"line":661},[262,2998,514],{},[262,3000,3001],{"class":264,"line":667},[262,3002,519],{},[262,3004,3005],{"class":264,"line":673},[262,3006,3007],{},"            'content' => ['required', 'string', 'max:2000', 'min:6'],\n",[262,3009,3010],{"class":264,"line":679},[262,3011,538],{},[262,3013,3014],{"class":264,"line":986},[262,3015,543],{},[262,3017,3018],{"class":264,"line":1164},[262,3019,548],{},[10,3021,3022,3023,3025],{},"Update ",[59,3024,1552],{}," to use the new request:",[252,3027,3029],{"className":420,"code":3028,"filename":1914,"language":269,"meta":258,"style":258},"use App\\Http\\Requests\\StoreCommentRequest; \u002F\u002F [!code --]\nuse Illuminate\\Http\\Request; \u002F\u002F [!code --]\n\nfinal class PostCommentController extends Controller\n{\n    public function store(StoreCommentRequest $request, Post $post) \u002F\u002F [!code highlight]\n    {\n        \u002F\u002F ...\n    }\n}\n",[59,3030,3031,3036,3041,3045,3049,3053,3058,3062,3067,3071],{"__ignoreMap":258},[262,3032,3033],{"class":264,"line":265},[262,3034,3035],{},"use App\\Http\\Requests\\StoreCommentRequest; \u002F\u002F [!code --]\n",[262,3037,3038],{"class":264,"line":289},[262,3039,3040],{},"use Illuminate\\Http\\Request; \u002F\u002F [!code --]\n",[262,3042,3043],{"class":264,"line":317},[262,3044,450],{"emptyLinePlaceholder":449},[262,3046,3047],{"class":264,"line":346},[262,3048,2040],{},[262,3050,3051],{"class":264,"line":372},[262,3052,434],{},[262,3054,3055],{"class":264,"line":453},[262,3056,3057],{},"    public function store(StoreCommentRequest $request, Post $post) \u002F\u002F [!code highlight]\n",[262,3059,3060],{"class":264,"line":459},[262,3061,514],{},[262,3063,3064],{"class":264,"line":465},[262,3065,3066],{},"        \u002F\u002F ...\n",[262,3068,3069],{"class":264,"line":470},[262,3070,543],{},[262,3072,3073],{"class":264,"line":476},[262,3074,548],{},[10,3076,3077],{},"Laravel now validates the request before the controller runs. ✨",[10,3079,3080],{},"Finally, we can add a test to check that the returned data is correct:",[252,3082,3084],{"className":420,"code":3083,"filename":2592,"language":269,"meta":258,"style":258},"it('returns the created comment', function () {\n    $user = User::factory()->create();\n    $post = Post::factory()->create();\n    $comment = Comment::factory()->make();\n\n    $response = $this->actingAs($user)\n        ->postJson(route('posts.comments.store', $post), [\n            'content' => $comment->content,\n        ]);\n\n    $comment = Comment::first();\n    $response\n        ->assertCreated()\n        ->assertJson(\n            fn (AssertableJson $json) => $json\n                ->has(\n                    'data',\n                    fn (AssertableJson $json) => $json\n                        ->where('id', $comment->id)\n                        ->where('content', $comment->content)\n                        ->has(\n                            'author',\n                            fn (AssertableJson $json) => $json\n                                ->where('name', $user->name)\n                                ->where('username', $user->username)\n                                ->where('avatar', $user->avatar)\n                        )\n                )\n        );\n});\n",[59,3085,3086,3091,3095,3099,3104,3108,3113,3117,3122,3126,3130,3135,3140,3145,3149,3153,3157,3161,3165,3170,3175,3179,3183,3187,3192,3197,3202,3206,3210,3214],{"__ignoreMap":258},[262,3087,3088],{"class":264,"line":265},[262,3089,3090],{},"it('returns the created comment', function () {\n",[262,3092,3093],{"class":264,"line":289},[262,3094,2698],{},[262,3096,3097],{"class":264,"line":317},[262,3098,1611],{},[262,3100,3101],{"class":264,"line":346},[262,3102,3103],{},"    $comment = Comment::factory()->make();\n",[262,3105,3106],{"class":264,"line":372},[262,3107,450],{"emptyLinePlaceholder":449},[262,3109,3110],{"class":264,"line":453},[262,3111,3112],{},"    $response = $this->actingAs($user)\n",[262,3114,3115],{"class":264,"line":459},[262,3116,2716],{},[262,3118,3119],{"class":264,"line":465},[262,3120,3121],{},"            'content' => $comment->content,\n",[262,3123,3124],{"class":264,"line":470},[262,3125,676],{},[262,3127,3128],{"class":264,"line":476},[262,3129,450],{"emptyLinePlaceholder":449},[262,3131,3132],{"class":264,"line":482},[262,3133,3134],{},"    $comment = Comment::first();\n",[262,3136,3137],{"class":264,"line":643},[262,3138,3139],{},"    $response\n",[262,3141,3142],{"class":264,"line":649},[262,3143,3144],{},"        ->assertCreated()\n",[262,3146,3147],{"class":264,"line":655},[262,3148,1644],{},[262,3150,3151],{"class":264,"line":661},[262,3152,1649],{},[262,3154,3155],{"class":264,"line":667},[262,3156,1654],{},[262,3158,3159],{"class":264,"line":673},[262,3160,1659],{},[262,3162,3163],{"class":264,"line":679},[262,3164,1669],{},[262,3166,3167],{"class":264,"line":986},[262,3168,3169],{},"                        ->where('id', $comment->id)\n",[262,3171,3172],{"class":264,"line":1164},[262,3173,3174],{},"                        ->where('content', $comment->content)\n",[262,3176,3177],{"class":264,"line":1170},[262,3178,1684],{},[262,3180,3181],{"class":264,"line":1175},[262,3182,1689],{},[262,3184,3185],{"class":264,"line":1471},[262,3186,1694],{},[262,3188,3189],{"class":264,"line":1476},[262,3190,3191],{},"                                ->where('name', $user->name)\n",[262,3193,3194],{"class":264,"line":1481},[262,3195,3196],{},"                                ->where('username', $user->username)\n",[262,3198,3199],{"class":264,"line":1486},[262,3200,3201],{},"                                ->where('avatar', $user->avatar)\n",[262,3203,3204],{"class":264,"line":1492},[262,3205,1714],{},[262,3207,3208],{"class":264,"line":1497},[262,3209,1720],{},[262,3211,3212],{"class":264,"line":1502},[262,3213,1726],{},[262,3215,3216],{"class":264,"line":1507},[262,3217,682],{},[10,3219,3220,3221,3224,3225,233],{},"This test verifies the response data and checks that the status code is ",[59,3222,3223],{},"201 Created"," with ",[59,3226,3227],{},"assertCreated",[10,3229,3230,3231,3233],{},"Now, let's update the ",[59,3232,1552],{}," method to return the created comment:",[252,3235,3237],{"className":420,"code":3236,"filename":1914,"language":269,"meta":258,"style":258},"use Illuminate\\Http\\Resources\\Json\\JsonResource;\n\nfinal class PostCommentController extends Controller\n{\n    public function store(StoreCommentRequest $request, Post $post): JsonResource\n    {\n        $comment = Comment::create([ \u002F\u002F [!code highlight]\n            'post_id' => $post->id,\n            'user_id' => $request->user()->id,\n            'content' => $request->input('content')\n        ]);\n\n        $comment->load('user'); \u002F\u002F [!code ++]\n\n        return CommentResource::make($comment); \u002F\u002F [!code ++]\n    }\n}\n",[59,3238,3239,3243,3247,3251,3255,3260,3264,3269,3273,3277,3281,3285,3289,3294,3298,3303,3307],{"__ignoreMap":258},[262,3240,3241],{"class":264,"line":265},[262,3242,2166],{},[262,3244,3245],{"class":264,"line":289},[262,3246,450],{"emptyLinePlaceholder":449},[262,3248,3249],{"class":264,"line":317},[262,3250,2040],{},[262,3252,3253],{"class":264,"line":346},[262,3254,434],{},[262,3256,3257],{"class":264,"line":372},[262,3258,3259],{},"    public function store(StoreCommentRequest $request, Post $post): JsonResource\n",[262,3261,3262],{"class":264,"line":453},[262,3263,514],{},[262,3265,3266],{"class":264,"line":459},[262,3267,3268],{},"        $comment = Comment::create([ \u002F\u002F [!code highlight]\n",[262,3270,3271],{"class":264,"line":465},[262,3272,2803],{},[262,3274,3275],{"class":264,"line":470},[262,3276,2808],{},[262,3278,3279],{"class":264,"line":476},[262,3280,2813],{},[262,3282,3283],{"class":264,"line":482},[262,3284,676],{},[262,3286,3287],{"class":264,"line":643},[262,3288,450],{"emptyLinePlaceholder":449},[262,3290,3291],{"class":264,"line":649},[262,3292,3293],{},"        $comment->load('user'); \u002F\u002F [!code ++]\n",[262,3295,3296],{"class":264,"line":655},[262,3297,450],{"emptyLinePlaceholder":449},[262,3299,3300],{"class":264,"line":661},[262,3301,3302],{},"        return CommentResource::make($comment); \u002F\u002F [!code ++]\n",[262,3304,3305],{"class":264,"line":667},[262,3306,543],{},[262,3308,3309],{"class":264,"line":673},[262,3310,548],{},[10,3312,3313],{},"All tests should now pass.",[10,3315,3316],{},"These tests are representative of the tests you can write for other controllers.",[44,3318,3320],{"id":3319},"editing-and-deleting-comments","Editing and deleting comments",[10,3322,3323],{},"Now we can implement comment editing and deletion.",[36,3325,3326],{"color":38,"icon":39},[10,3327,3328],{},"I will move faster here because the workflow is familiar. The complete tests are included so you can still follow each requirement.",[10,3330,3331],{},"For the edition, we need to create a new test file:",[252,3333,3335],{"className":254,"code":3334,"filename":256,"language":257,"meta":258,"style":258},"mkdir -p tests\u002FHttp\u002FApi\u002FComment && touch tests\u002FHttp\u002FApi\u002FComment\u002FUpdateTest.php\n",[59,3336,3337],{"__ignoreMap":258},[262,3338,3339,3341,3343,3346,3348,3350],{"class":264,"line":265},[262,3340,564],{"class":268},[262,3342,567],{"class":282},[262,3344,3345],{"class":272}," tests\u002FHttp\u002FApi\u002FComment",[262,3347,574],{"class":573},[262,3349,577],{"class":268},[262,3351,3352],{"class":272}," tests\u002FHttp\u002FApi\u002FComment\u002FUpdateTest.php\n",[10,3354,3355],{},"Then, we can add the following test:",[252,3357,3360],{"className":420,"code":3358,"filename":3359,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\nuse App\\Models\\User;\nuse Illuminate\\Testing\\Fluent\\AssertableJson;\n\nit('requires authentication', function () {\n    $comment = Comment::factory()->create();\n\n    $this->putJson(route('comments.update', $comment))\n        ->assertUnauthorized();\n});\n\nit('requires the user to be the author of the comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->create();\n\n    $this->actingAs($user)\n        ->putJson(route('comments.update', $comment), [\n            'content' => 'Updated content',\n        ])\n        ->assertForbidden();\n});\n\nit('updates a comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()\n        ->for($user)\n        ->create();\n\n    $this->actingAs($user)\n        ->putJson(route('comments.update', $comment), [\n            'content' => 'Updated content',\n        ]);\n\n    $this->assertDatabaseHas('comments', [\n        'id' => $comment->id,\n        'content' => 'Updated content',\n    ]);\n});\n\nit('requires a valid data', function (array $badData, array|string $errors) {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->for($user)->create();\n\n    $this->actingAs($user)\n        ->putJson(route('comments.update', $comment), $badData)\n        ->assertJsonValidationErrors($errors);\n})->with([\n    [['content' => ''], ['content' => 'The content field is required.']],\n    [['content' => 1], ['content' => 'The content field must be a string.']],\n    [['content' => 'a'], ['content' => 'The content field must be at least 6 characters.']],\n    [['content' => 'a' . str_repeat('a', 2001)], ['content' => 'The content field must not be greater than 2000 characters.']],\n]);\n\nit('returns the comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->for($user)->create();\n\n    $this->actingAs($user)\n        ->putJson(route('comments.update', $comment), [\n            'content' => 'Updated content',\n        ])\n        ->assertOk()\n        ->assertJson(\n            fn(AssertableJson $json) => $json\n                ->has(\n                    'data',\n                    fn(AssertableJson $json) => $json\n                        ->where('id', $comment->id)\n                        ->where('content', 'Updated content')\n                        ->has(\n                            'author',\n                            fn(AssertableJson $json) => $json\n                                ->where('name', $user->name)\n                                ->where('username', $user->username)\n                                ->where('avatar', $user->avatar)\n                        )\n                )\n        );\n});\n","tests\u002FHttp\u002FApi\u002FComment\u002FUpdateTest.php",[59,3361,3362,3366,3370,3374,3378,3382,3386,3390,3394,3398,3403,3407,3412,3416,3420,3424,3429,3433,3437,3441,3445,3450,3455,3460,3465,3469,3473,3478,3482,3486,3491,3495,3499,3503,3507,3512,3517,3522,3527,3533,3539,3544,3549,3554,3559,3564,3570,3575,3580,3586,3592,3597,3602,3607,3612,3618,3623,3628,3634,3639,3644,3649,3654,3659,3664,3669,3675,3680,3686,3691,3696,3702,3707,3713,3718,3723,3729,3734,3739,3744,3749,3754,3759],{"__ignoreMap":258},[262,3363,3364],{"class":264,"line":265},[262,3365,594],{},[262,3367,3368],{"class":264,"line":289},[262,3369,450],{"emptyLinePlaceholder":449},[262,3371,3372],{"class":264,"line":317},[262,3373,603],{},[262,3375,3376],{"class":264,"line":346},[262,3377,450],{"emptyLinePlaceholder":449},[262,3379,3380],{"class":264,"line":372},[262,3381,926],{},[262,3383,3384],{"class":264,"line":453},[262,3385,1326],{},[262,3387,3388],{"class":264,"line":459},[262,3389,1597],{},[262,3391,3392],{"class":264,"line":465},[262,3393,450],{"emptyLinePlaceholder":449},[262,3395,3396],{"class":264,"line":470},[262,3397,2615],{},[262,3399,3400],{"class":264,"line":476},[262,3401,3402],{},"    $comment = Comment::factory()->create();\n",[262,3404,3405],{"class":264,"line":482},[262,3406,450],{"emptyLinePlaceholder":449},[262,3408,3409],{"class":264,"line":643},[262,3410,3411],{},"    $this->putJson(route('comments.update', $comment))\n",[262,3413,3414],{"class":264,"line":649},[262,3415,2633],{},[262,3417,3418],{"class":264,"line":655},[262,3419,682],{},[262,3421,3422],{"class":264,"line":661},[262,3423,450],{"emptyLinePlaceholder":449},[262,3425,3426],{"class":264,"line":667},[262,3427,3428],{},"it('requires the user to be the author of the comment', function () {\n",[262,3430,3431],{"class":264,"line":673},[262,3432,2698],{},[262,3434,3435],{"class":264,"line":679},[262,3436,3402],{},[262,3438,3439],{"class":264,"line":986},[262,3440,450],{"emptyLinePlaceholder":449},[262,3442,3443],{"class":264,"line":1164},[262,3444,2711],{},[262,3446,3447],{"class":264,"line":1170},[262,3448,3449],{},"        ->putJson(route('comments.update', $comment), [\n",[262,3451,3452],{"class":264,"line":1175},[262,3453,3454],{},"            'content' => 'Updated content',\n",[262,3456,3457],{"class":264,"line":1471},[262,3458,3459],{},"        ])\n",[262,3461,3462],{"class":264,"line":1476},[262,3463,3464],{},"        ->assertForbidden();\n",[262,3466,3467],{"class":264,"line":1481},[262,3468,682],{},[262,3470,3471],{"class":264,"line":1486},[262,3472,450],{"emptyLinePlaceholder":449},[262,3474,3475],{"class":264,"line":1492},[262,3476,3477],{},"it('updates a comment', function () {\n",[262,3479,3480],{"class":264,"line":1497},[262,3481,2698],{},[262,3483,3484],{"class":264,"line":1502},[262,3485,1339],{},[262,3487,3488],{"class":264,"line":1507},[262,3489,3490],{},"        ->for($user)\n",[262,3492,3493],{"class":264,"line":1513},[262,3494,1299],{},[262,3496,3497],{"class":264,"line":1717},[262,3498,450],{"emptyLinePlaceholder":449},[262,3500,3501],{"class":264,"line":1723},[262,3502,2711],{},[262,3504,3505],{"class":264,"line":1729},[262,3506,3449],{},[262,3508,3510],{"class":264,"line":3509},35,[262,3511,3454],{},[262,3513,3515],{"class":264,"line":3514},36,[262,3516,676],{},[262,3518,3520],{"class":264,"line":3519},37,[262,3521,450],{"emptyLinePlaceholder":449},[262,3523,3525],{"class":264,"line":3524},38,[262,3526,2734],{},[262,3528,3530],{"class":264,"line":3529},39,[262,3531,3532],{},"        'id' => $comment->id,\n",[262,3534,3536],{"class":264,"line":3535},40,[262,3537,3538],{},"        'content' => 'Updated content',\n",[262,3540,3542],{"class":264,"line":3541},41,[262,3543,2754],{},[262,3545,3547],{"class":264,"line":3546},42,[262,3548,682],{},[262,3550,3552],{"class":264,"line":3551},43,[262,3553,450],{"emptyLinePlaceholder":449},[262,3555,3557],{"class":264,"line":3556},44,[262,3558,2843],{},[262,3560,3562],{"class":264,"line":3561},45,[262,3563,2698],{},[262,3565,3567],{"class":264,"line":3566},46,[262,3568,3569],{},"    $comment = Comment::factory()->for($user)->create();\n",[262,3571,3573],{"class":264,"line":3572},47,[262,3574,450],{"emptyLinePlaceholder":449},[262,3576,3578],{"class":264,"line":3577},48,[262,3579,2711],{},[262,3581,3583],{"class":264,"line":3582},49,[262,3584,3585],{},"        ->putJson(route('comments.update', $comment), $badData)\n",[262,3587,3589],{"class":264,"line":3588},50,[262,3590,3591],{},"        ->assertJsonValidationErrors($errors);\n",[262,3593,3595],{"class":264,"line":3594},51,[262,3596,2875],{},[262,3598,3600],{"class":264,"line":3599},52,[262,3601,2880],{},[262,3603,3605],{"class":264,"line":3604},53,[262,3606,2885],{},[262,3608,3610],{"class":264,"line":3609},54,[262,3611,2890],{},[262,3613,3615],{"class":264,"line":3614},55,[262,3616,3617],{},"    [['content' => 'a' . str_repeat('a', 2001)], ['content' => 'The content field must not be greater than 2000 characters.']],\n",[262,3619,3621],{"class":264,"line":3620},56,[262,3622,2900],{},[262,3624,3626],{"class":264,"line":3625},57,[262,3627,450],{"emptyLinePlaceholder":449},[262,3629,3631],{"class":264,"line":3630},58,[262,3632,3633],{},"it('returns the comment', function () {\n",[262,3635,3637],{"class":264,"line":3636},59,[262,3638,2698],{},[262,3640,3642],{"class":264,"line":3641},60,[262,3643,3569],{},[262,3645,3647],{"class":264,"line":3646},61,[262,3648,450],{"emptyLinePlaceholder":449},[262,3650,3652],{"class":264,"line":3651},62,[262,3653,2711],{},[262,3655,3657],{"class":264,"line":3656},63,[262,3658,3449],{},[262,3660,3662],{"class":264,"line":3661},64,[262,3663,3454],{},[262,3665,3667],{"class":264,"line":3666},65,[262,3668,3459],{},[262,3670,3672],{"class":264,"line":3671},66,[262,3673,3674],{},"        ->assertOk()\n",[262,3676,3678],{"class":264,"line":3677},67,[262,3679,1644],{},[262,3681,3683],{"class":264,"line":3682},68,[262,3684,3685],{},"            fn(AssertableJson $json) => $json\n",[262,3687,3689],{"class":264,"line":3688},69,[262,3690,1654],{},[262,3692,3694],{"class":264,"line":3693},70,[262,3695,1659],{},[262,3697,3699],{"class":264,"line":3698},71,[262,3700,3701],{},"                    fn(AssertableJson $json) => $json\n",[262,3703,3705],{"class":264,"line":3704},72,[262,3706,3169],{},[262,3708,3710],{"class":264,"line":3709},73,[262,3711,3712],{},"                        ->where('content', 'Updated content')\n",[262,3714,3716],{"class":264,"line":3715},74,[262,3717,1684],{},[262,3719,3721],{"class":264,"line":3720},75,[262,3722,1689],{},[262,3724,3726],{"class":264,"line":3725},76,[262,3727,3728],{},"                            fn(AssertableJson $json) => $json\n",[262,3730,3732],{"class":264,"line":3731},77,[262,3733,3191],{},[262,3735,3737],{"class":264,"line":3736},78,[262,3738,3196],{},[262,3740,3742],{"class":264,"line":3741},79,[262,3743,3201],{},[262,3745,3747],{"class":264,"line":3746},80,[262,3748,1714],{},[262,3750,3752],{"class":264,"line":3751},81,[262,3753,1720],{},[262,3755,3757],{"class":264,"line":3756},82,[262,3758,1726],{},[262,3760,3762],{"class":264,"line":3761},83,[262,3763,682],{},[10,3765,3766],{},"Then, we can add the route:",[252,3768,3770],{"className":420,"code":3769,"filename":378,"language":269,"meta":258,"style":258},"\u003C?php\n\nuse App\\Http\\Controllers\\Api\\CommentController; \u002F\u002F [!code ++]\n\nRoute::middleware('auth')->group(function () {\n    Route::put('\u002Fcomments\u002F{comment}', [CommentController::class, 'update']) \u002F\u002F [!code ++]\n        ->name('comments.update'); \u002F\u002F [!code ++]\n});\n",[59,3771,3772,3776,3780,3785,3789,3793,3798,3803],{"__ignoreMap":258},[262,3773,3774],{"class":264,"line":265},[262,3775,594],{},[262,3777,3778],{"class":264,"line":289},[262,3779,450],{"emptyLinePlaceholder":449},[262,3781,3782],{"class":264,"line":317},[262,3783,3784],{},"use App\\Http\\Controllers\\Api\\CommentController; \u002F\u002F [!code ++]\n",[262,3786,3787],{"class":264,"line":346},[262,3788,450],{"emptyLinePlaceholder":449},[262,3790,3791],{"class":264,"line":372},[262,3792,2650],{},[262,3794,3795],{"class":264,"line":453},[262,3796,3797],{},"    Route::put('\u002Fcomments\u002F{comment}', [CommentController::class, 'update']) \u002F\u002F [!code ++]\n",[262,3799,3800],{"class":264,"line":459},[262,3801,3802],{},"        ->name('comments.update'); \u002F\u002F [!code ++]\n",[262,3804,3805],{"class":264,"line":465},[262,3806,682],{},[10,3808,3809],{},"Create the controller:",[252,3811,3812],{"className":254,"code":329,"filename":256,"language":257,"meta":258,"style":258},[59,3813,3814],{"__ignoreMap":258},[262,3815,3816,3818,3820,3822],{"class":264,"line":265},[262,3817,269],{"class":268},[262,3819,273],{"class":272},[262,3821,340],{"class":272},[262,3823,343],{"class":272},[10,3825,3826,3827,1562],{},"Implement the ",[59,3828,3829],{},"update",[252,3831,3834],{"className":420,"code":3832,"filename":3833,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Controllers\\Controller;\nuse App\\Http\\Requests\\UpdateCommentRequest;\nuse App\\Http\\Resources\\CommentResource;\nuse App\\Models\\Comment;\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\nfinal class CommentController extends Controller\n{\n    public function update(UpdateCommentRequest $request, Comment $comment): JsonResource\n    {\n        $comment->update($request->validated());\n        $comment->load('user');\n\n        return CommentResource::make($comment);\n    }\n}\n","app\u002FHttp\u002FApi\u002FCommentController.php",[59,3835,3836,3840,3844,3848,3852,3856,3860,3864,3869,3873,3877,3881,3885,3890,3894,3899,3903,3908,3913,3917,3922,3926],{"__ignoreMap":258},[262,3837,3838],{"class":264,"line":265},[262,3839,594],{},[262,3841,3842],{"class":264,"line":289},[262,3843,450],{"emptyLinePlaceholder":449},[262,3845,3846],{"class":264,"line":317},[262,3847,603],{},[262,3849,3850],{"class":264,"line":346},[262,3851,450],{"emptyLinePlaceholder":449},[262,3853,3854],{"class":264,"line":372},[262,3855,1929],{},[262,3857,3858],{"class":264,"line":453},[262,3859,450],{"emptyLinePlaceholder":449},[262,3861,3862],{"class":264,"line":459},[262,3863,1938],{},[262,3865,3866],{"class":264,"line":465},[262,3867,3868],{},"use App\\Http\\Requests\\UpdateCommentRequest;\n",[262,3870,3871],{"class":264,"line":470},[262,3872,2022],{},[262,3874,3875],{"class":264,"line":476},[262,3876,926],{},[262,3878,3879],{"class":264,"line":482},[262,3880,2166],{},[262,3882,3883],{"class":264,"line":643},[262,3884,450],{"emptyLinePlaceholder":449},[262,3886,3887],{"class":264,"line":649},[262,3888,3889],{},"final class CommentController extends Controller\n",[262,3891,3892],{"class":264,"line":655},[262,3893,434],{},[262,3895,3896],{"class":264,"line":661},[262,3897,3898],{},"    public function update(UpdateCommentRequest $request, Comment $comment): JsonResource\n",[262,3900,3901],{"class":264,"line":667},[262,3902,514],{},[262,3904,3905],{"class":264,"line":673},[262,3906,3907],{},"        $comment->update($request->validated());\n",[262,3909,3910],{"class":264,"line":679},[262,3911,3912],{},"        $comment->load('user');\n",[262,3914,3915],{"class":264,"line":986},[262,3916,450],{"emptyLinePlaceholder":449},[262,3918,3919],{"class":264,"line":1164},[262,3920,3921],{},"        return CommentResource::make($comment);\n",[262,3923,3924],{"class":264,"line":1170},[262,3925,543],{},[262,3927,3928],{"class":264,"line":1175},[262,3929,548],{},[10,3931,3932],{},"This method needs a dedicated form request:",[252,3934,3936],{"className":254,"code":3935,"filename":256,"language":257,"meta":258,"style":258},"php artisan make:request UpdateCommentRequest\n",[59,3937,3938],{"__ignoreMap":258},[262,3939,3940,3942,3944,3946],{"class":264,"line":265},[262,3941,269],{"class":268},[262,3943,273],{"class":272},[262,3945,2923],{"class":272},[262,3947,3948],{"class":272}," UpdateCommentRequest\n",[10,3950,3951],{},"Then, we can implement the request:",[252,3953,3956],{"className":420,"code":3954,"filename":3955,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Requests;\n\nuse App\\Models\\Comment;\nuse Illuminate\\Foundation\\Http\\FormRequest;\n\n\u002F**\n * @property Comment $comment\n *\u002F\nfinal class UpdateCommentRequest extends FormRequest\n{\n    \u002F**\n     * Determine if the user is authorized to make this request.\n     *\u002F\n    public function authorize(): bool\n    {\n        return $this->user()->can('update', $this->comment);\n    }\n\n    \u002F**\n     * Get the validation rules that apply to the request.\n     *\n     * @return array\u003Cstring, \\Illuminate\\Contracts\\Validation\\ValidationRule|array\u003Cmixed>|string>\n     *\u002F\n    public function rules(): array\n    {\n        return [\n            'content' => ['required', 'string', 'max:2000', 'min:6'],\n        ];\n    }\n}\n","app\u002FHttp\u002FRequests\u002FUpdateCommentRequest.php",[59,3957,3958,3962,3966,3970,3974,3978,3982,3986,3990,3994,3998,4003,4007,4012,4016,4020,4025,4029,4034,4038,4043,4047,4051,4055,4059,4063,4067,4071,4075,4079,4083,4087,4091,4095],{"__ignoreMap":258},[262,3959,3960],{"class":264,"line":265},[262,3961,594],{},[262,3963,3964],{"class":264,"line":289},[262,3965,450],{"emptyLinePlaceholder":449},[262,3967,3968],{"class":264,"line":317},[262,3969,603],{},[262,3971,3972],{"class":264,"line":346},[262,3973,450],{"emptyLinePlaceholder":449},[262,3975,3976],{"class":264,"line":372},[262,3977,2945],{},[262,3979,3980],{"class":264,"line":453},[262,3981,450],{"emptyLinePlaceholder":449},[262,3983,3984],{"class":264,"line":459},[262,3985,926],{},[262,3987,3988],{"class":264,"line":465},[262,3989,2954],{},[262,3991,3992],{"class":264,"line":470},[262,3993,450],{"emptyLinePlaceholder":449},[262,3995,3996],{"class":264,"line":476},[262,3997,2175],{},[262,3999,4000],{"class":264,"line":482},[262,4001,4002],{}," * @property Comment $comment\n",[262,4004,4005],{"class":264,"line":643},[262,4006,2185],{},[262,4008,4009],{"class":264,"line":649},[262,4010,4011],{},"final class UpdateCommentRequest extends FormRequest\n",[262,4013,4014],{"class":264,"line":655},[262,4015,434],{},[262,4017,4018],{"class":264,"line":661},[262,4019,1029],{},[262,4021,4022],{"class":264,"line":667},[262,4023,4024],{},"     * Determine if the user is authorized to make this request.\n",[262,4026,4027],{"class":264,"line":673},[262,4028,1049],{},[262,4030,4031],{"class":264,"line":679},[262,4032,4033],{},"    public function authorize(): bool\n",[262,4035,4036],{"class":264,"line":986},[262,4037,514],{},[262,4039,4040],{"class":264,"line":1164},[262,4041,4042],{},"        return $this->user()->can('update', $this->comment);\n",[262,4044,4045],{"class":264,"line":1170},[262,4046,543],{},[262,4048,4049],{"class":264,"line":1175},[262,4050,450],{"emptyLinePlaceholder":449},[262,4052,4053],{"class":264,"line":1471},[262,4054,1029],{},[262,4056,4057],{"class":264,"line":1476},[262,4058,2976],{},[262,4060,4061],{"class":264,"line":1481},[262,4062,1039],{},[262,4064,4065],{"class":264,"line":1486},[262,4066,2985],{},[262,4068,4069],{"class":264,"line":1492},[262,4070,1049],{},[262,4072,4073],{"class":264,"line":1497},[262,4074,2994],{},[262,4076,4077],{"class":264,"line":1502},[262,4078,514],{},[262,4080,4081],{"class":264,"line":1507},[262,4082,519],{},[262,4084,4085],{"class":264,"line":1513},[262,4086,3007],{},[262,4088,4089],{"class":264,"line":1717},[262,4090,538],{},[262,4092,4093],{"class":264,"line":1723},[262,4094,543],{},[262,4096,4097],{"class":264,"line":1729},[262,4098,548],{},[10,4100,4101,4102,4105],{},"The request's ",[59,4103,4104],{},"authorize"," method checks whether the current user may update the comment. It delegates that decision to a policy, which we need to create.",[252,4107,4109],{"className":254,"code":4108,"filename":256,"language":257,"meta":258,"style":258},"php artisan make:policy CommentPolicy\n",[59,4110,4111],{"__ignoreMap":258},[262,4112,4113,4115,4117,4120],{"class":264,"line":265},[262,4114,269],{"class":268},[262,4116,273],{"class":272},[262,4118,4119],{"class":272}," make:policy",[262,4121,4122],{"class":272}," CommentPolicy\n",[10,4124,4125],{},"Then, we can implement the policy:",[252,4127,4130],{"className":420,"code":4128,"filename":4129,"language":269,"meta":258,"style":258},"\u003C?php\n\nnamespace App\\Policies;\n\nuse App\\Models\\Comment;\nuse App\\Models\\User;\n\nclass CommentPolicy\n{\n    \u002F**\n     * Determine whether the user can update the model.\n     *\u002F\n    public function update(User $user, Comment $comment): bool\n    {\n        return $user->id === $comment->user_id;\n    }\n}\n","app\u002FPolicies\u002FCommentPolicy.php",[59,4131,4132,4136,4140,4145,4149,4153,4157,4161,4166,4170,4174,4179,4183,4188,4192,4197,4201],{"__ignoreMap":258},[262,4133,4134],{"class":264,"line":265},[262,4135,594],{},[262,4137,4138],{"class":264,"line":289},[262,4139,450],{"emptyLinePlaceholder":449},[262,4141,4142],{"class":264,"line":317},[262,4143,4144],{},"namespace App\\Policies;\n",[262,4146,4147],{"class":264,"line":346},[262,4148,450],{"emptyLinePlaceholder":449},[262,4150,4151],{"class":264,"line":372},[262,4152,926],{},[262,4154,4155],{"class":264,"line":453},[262,4156,1326],{},[262,4158,4159],{"class":264,"line":459},[262,4160,450],{"emptyLinePlaceholder":449},[262,4162,4163],{"class":264,"line":465},[262,4164,4165],{},"class CommentPolicy\n",[262,4167,4168],{"class":264,"line":470},[262,4169,434],{},[262,4171,4172],{"class":264,"line":476},[262,4173,1029],{},[262,4175,4176],{"class":264,"line":482},[262,4177,4178],{},"     * Determine whether the user can update the model.\n",[262,4180,4181],{"class":264,"line":643},[262,4182,1049],{},[262,4184,4185],{"class":264,"line":649},[262,4186,4187],{},"    public function update(User $user, Comment $comment): bool\n",[262,4189,4190],{"class":264,"line":655},[262,4191,514],{},[262,4193,4194],{"class":264,"line":661},[262,4195,4196],{},"        return $user->id === $comment->user_id;\n",[262,4198,4199],{"class":264,"line":667},[262,4200,543],{},[262,4202,4203],{"class":264,"line":673},[262,4204,548],{},[10,4206,4207],{},"The update flow is now complete.",[10,4209,4210],{},"Finish the article by adding comment deletion:",[252,4212,4215],{"className":420,"code":4213,"filename":4214,"language":269,"meta":258,"style":258},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\nuse App\\Models\\User;\n\nit('requires authentification', function () {\n    $comment = Comment::factory()->create();\n\n    $this->deleteJson(route('comments.destroy', $comment))\n        ->assertUnauthorized();\n});\n\nit('requires the user to be the author of the comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->create();\n\n    $this->actingAs($user)\n        ->deleteJson(route('comments.destroy', $comment))\n        ->assertForbidden();\n});\n\nit('deletes a comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->for($user)->create();\n\n    $this->actingAs($user)\n        ->deleteJson(route('comments.destroy', $comment));\n\n    $this->assertDatabaseMissing('comments', [\n        'id' => $comment->id,\n    ]);\n});\n","tests\u002FHttp\u002FApi\u002FComment\u002FDestroyTest.php",[59,4216,4217,4221,4225,4229,4233,4237,4241,4245,4250,4254,4258,4263,4267,4271,4275,4279,4283,4287,4291,4295,4300,4304,4308,4312,4317,4321,4325,4329,4333,4338,4342,4347,4351,4355],{"__ignoreMap":258},[262,4218,4219],{"class":264,"line":265},[262,4220,594],{},[262,4222,4223],{"class":264,"line":289},[262,4224,450],{"emptyLinePlaceholder":449},[262,4226,4227],{"class":264,"line":317},[262,4228,603],{},[262,4230,4231],{"class":264,"line":346},[262,4232,450],{"emptyLinePlaceholder":449},[262,4234,4235],{"class":264,"line":372},[262,4236,926],{},[262,4238,4239],{"class":264,"line":453},[262,4240,1326],{},[262,4242,4243],{"class":264,"line":459},[262,4244,450],{"emptyLinePlaceholder":449},[262,4246,4247],{"class":264,"line":465},[262,4248,4249],{},"it('requires authentification', function () {\n",[262,4251,4252],{"class":264,"line":470},[262,4253,3402],{},[262,4255,4256],{"class":264,"line":476},[262,4257,450],{"emptyLinePlaceholder":449},[262,4259,4260],{"class":264,"line":482},[262,4261,4262],{},"    $this->deleteJson(route('comments.destroy', $comment))\n",[262,4264,4265],{"class":264,"line":643},[262,4266,2633],{},[262,4268,4269],{"class":264,"line":649},[262,4270,682],{},[262,4272,4273],{"class":264,"line":655},[262,4274,450],{"emptyLinePlaceholder":449},[262,4276,4277],{"class":264,"line":661},[262,4278,3428],{},[262,4280,4281],{"class":264,"line":667},[262,4282,2698],{},[262,4284,4285],{"class":264,"line":673},[262,4286,3402],{},[262,4288,4289],{"class":264,"line":679},[262,4290,450],{"emptyLinePlaceholder":449},[262,4292,4293],{"class":264,"line":986},[262,4294,2711],{},[262,4296,4297],{"class":264,"line":1164},[262,4298,4299],{},"        ->deleteJson(route('comments.destroy', $comment))\n",[262,4301,4302],{"class":264,"line":1170},[262,4303,3464],{},[262,4305,4306],{"class":264,"line":1175},[262,4307,682],{},[262,4309,4310],{"class":264,"line":1471},[262,4311,450],{"emptyLinePlaceholder":449},[262,4313,4314],{"class":264,"line":1476},[262,4315,4316],{},"it('deletes a comment', function () {\n",[262,4318,4319],{"class":264,"line":1481},[262,4320,2698],{},[262,4322,4323],{"class":264,"line":1486},[262,4324,3569],{},[262,4326,4327],{"class":264,"line":1492},[262,4328,450],{"emptyLinePlaceholder":449},[262,4330,4331],{"class":264,"line":1497},[262,4332,2711],{},[262,4334,4335],{"class":264,"line":1502},[262,4336,4337],{},"        ->deleteJson(route('comments.destroy', $comment));\n",[262,4339,4340],{"class":264,"line":1507},[262,4341,450],{"emptyLinePlaceholder":449},[262,4343,4344],{"class":264,"line":1513},[262,4345,4346],{},"    $this->assertDatabaseMissing('comments', [\n",[262,4348,4349],{"class":264,"line":1717},[262,4350,3532],{},[262,4352,4353],{"class":264,"line":1723},[262,4354,2754],{},[262,4356,4357],{"class":264,"line":1729},[262,4358,682],{},[252,4360,4362],{"className":420,"code":4361,"filename":378,"language":269,"meta":258,"style":258},"\u003C?php\n\n\u002F\u002F ...\n\nRoute::middleware('auth')->group(function () {\n    \u002F\u002F ...\n\n    Route::delete('\u002Fcomments\u002F{comment}', [CommentController::class, 'destroy'])\n        ->name('comments.destroy');\n});\n\n",[59,4363,4364,4368,4372,4376,4380,4384,4389,4393,4398,4403],{"__ignoreMap":258},[262,4365,4366],{"class":264,"line":265},[262,4367,594],{},[262,4369,4370],{"class":264,"line":289},[262,4371,450],{"emptyLinePlaceholder":449},[262,4373,4374],{"class":264,"line":317},[262,4375,845],{},[262,4377,4378],{"class":264,"line":346},[262,4379,450],{"emptyLinePlaceholder":449},[262,4381,4382],{"class":264,"line":372},[262,4383,2650],{},[262,4385,4386],{"class":264,"line":453},[262,4387,4388],{},"    \u002F\u002F ...\n",[262,4390,4391],{"class":264,"line":459},[262,4392,450],{"emptyLinePlaceholder":449},[262,4394,4395],{"class":264,"line":465},[262,4396,4397],{},"    Route::delete('\u002Fcomments\u002F{comment}', [CommentController::class, 'destroy'])\n",[262,4399,4400],{"class":264,"line":470},[262,4401,4402],{},"        ->name('comments.destroy');\n",[262,4404,4405],{"class":264,"line":476},[262,4406,682],{},[252,4408,4410],{"className":420,"code":4409,"filename":3833,"language":269,"meta":258,"style":258},"use Illuminate\\Http\\Response;\nuse Illuminate\\Support\\Facades\\Gate;\n\nfinal class CommentController extends Controller\n{\n    \u002F\u002F ...\n\n    public function destroy(Comment $comment): Response\n    {\n        Gate::authorize('delete', $comment);\n\n        $comment->delete();\n\n        return response()->noContent();\n    }\n}\n",[59,4411,4412,4417,4422,4426,4430,4434,4438,4442,4447,4451,4456,4460,4465,4469,4474,4478],{"__ignoreMap":258},[262,4413,4414],{"class":264,"line":265},[262,4415,4416],{},"use Illuminate\\Http\\Response;\n",[262,4418,4419],{"class":264,"line":289},[262,4420,4421],{},"use Illuminate\\Support\\Facades\\Gate;\n",[262,4423,4424],{"class":264,"line":317},[262,4425,450],{"emptyLinePlaceholder":449},[262,4427,4428],{"class":264,"line":346},[262,4429,3889],{},[262,4431,4432],{"class":264,"line":372},[262,4433,434],{},[262,4435,4436],{"class":264,"line":453},[262,4437,4388],{},[262,4439,4440],{"class":264,"line":459},[262,4441,450],{"emptyLinePlaceholder":449},[262,4443,4444],{"class":264,"line":465},[262,4445,4446],{},"    public function destroy(Comment $comment): Response\n",[262,4448,4449],{"class":264,"line":470},[262,4450,514],{},[262,4452,4453],{"class":264,"line":476},[262,4454,4455],{},"        Gate::authorize('delete', $comment);\n",[262,4457,4458],{"class":264,"line":482},[262,4459,450],{"emptyLinePlaceholder":449},[262,4461,4462],{"class":264,"line":643},[262,4463,4464],{},"        $comment->delete();\n",[262,4466,4467],{"class":264,"line":649},[262,4468,450],{"emptyLinePlaceholder":449},[262,4470,4471],{"class":264,"line":655},[262,4472,4473],{},"        return response()->noContent();\n",[262,4475,4476],{"class":264,"line":661},[262,4477,543],{},[262,4479,4480],{"class":264,"line":667},[262,4481,548],{},[10,4483,154,4484,4487,4488,4491,4492,233],{},[59,4485,4486],{},"Gate"," facade authorizes the deletion. Laravel resolves ",[59,4489,4490],{},"CommentPolicy"," from the model passed to ",[59,4493,4104],{},[252,4495,4497],{"className":420,"code":4496,"filename":4129,"language":269,"meta":258,"style":258},"final class CommentPolicy\n{\n    \u002F\u002F ...\n\n    \u002F**\n     * Determine whether the user can delete the model.\n     *\u002F\n    public function delete(User $user, Comment $comment): bool\n    {\n        return $user->id === $comment->user_id;\n    }\n}\n",[59,4498,4499,4504,4508,4512,4516,4520,4525,4529,4534,4538,4542,4546],{"__ignoreMap":258},[262,4500,4501],{"class":264,"line":265},[262,4502,4503],{},"final class CommentPolicy\n",[262,4505,4506],{"class":264,"line":289},[262,4507,434],{},[262,4509,4510],{"class":264,"line":317},[262,4511,4388],{},[262,4513,4514],{"class":264,"line":346},[262,4515,450],{"emptyLinePlaceholder":449},[262,4517,4518],{"class":264,"line":372},[262,4519,1029],{},[262,4521,4522],{"class":264,"line":453},[262,4523,4524],{},"     * Determine whether the user can delete the model.\n",[262,4526,4527],{"class":264,"line":459},[262,4528,1049],{},[262,4530,4531],{"class":264,"line":465},[262,4532,4533],{},"    public function delete(User $user, Comment $comment): bool\n",[262,4535,4536],{"class":264,"line":470},[262,4537,514],{},[262,4539,4540],{"class":264,"line":476},[262,4541,4196],{},[262,4543,4544],{"class":264,"line":482},[262,4545,543],{},[262,4547,4548],{"class":264,"line":643},[262,4549,548],{},[10,4551,4552],{},"The comment system is ready, and the tests give us confidence that its main behaviors work without requiring a manual click-through.",[44,4554,4556],{"id":4555},"whats-next","What's next",[10,4558,4559],{},"The comment API is now in place. It supports listing, creating, updating, and deleting comments, and the tests describe the behavior and permissions that keep those operations safe.",[10,4561,4562],{},"Working test-first kept the implementation focused: each failure pointed to the next piece of behavior, and the completed tests now protect us from regressions.",[10,4564,4565,4566,4569],{},"Next, we will connect the static frontend to the backend. We will generate post metadata during the VitePress build and use Laravel to synchronize the ",[59,4567,4568],{},"posts"," table automatically.",[4571,4572,4573],"style",{},"html pre.shiki code .snPdu, html code.shiki .snPdu{--shiki-light:#6F42C1;--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .sIIMD, html code.shiki .sIIMD{--shiki-light:#032F62;--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .sBjJW, html code.shiki .sBjJW{--shiki-light:#005CC5;--shiki-default:#005CC5;--shiki-dark:#79B8FF}html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sxrX7, html code.shiki .sxrX7{--shiki-light:#24292E;--shiki-default:#24292E;--shiki-dark:#E1E4E8}",{"title":258,"searchDepth":289,"depth":289,"links":4575},[4576,4579,4580,4581,4582],{"id":46,"depth":289,"text":47,"children":4577},[4578],{"id":237,"depth":317,"text":238},{"id":392,"depth":289,"text":393},{"id":1527,"depth":289,"text":1528},{"id":3319,"depth":289,"text":3320},{"id":4555,"depth":289,"text":4556},"b07ec3b5-ca56-4d14-ae2f-8c0702218293","2025-02-25","Build a Laravel comment API with models, migrations, resources, policies, form requests, controllers, routes, and comprehensive tests.","md",null,{},"\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbuilding-a-simple-comment-system-for-user-engagement","---\ncontentId: b07ec3b5-ca56-4d14-ae2f-8c0702218293\npart: 4\ntitle: Building a Simple Comment System for User Engagement\ndescription: Build a Laravel comment API with models, migrations, resources, policies, form requests, controllers, routes, and comprehensive tests.\ndate: 2025-02-25\nseriesSlug: empower-and-dynamize-our-vitepress-blog-with-a-laravel-api\n---\n\nWith GitHub authentication in place, we can now build the feature it enables: comments.\n\nBefore writing any code, let's define the first version of the comment system. We want it to support the core interactions without taking on more complexity than necessary:\n\n- Users should be able to leave comments on blog posts.\n- Users should be able to edit or delete their comments.\n- Replying to comments is not planned.\n- Supporting Markdown is not planned.\n\nFor now, we want a deliberately simple comment system.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nI want to keep the code simple for two reasons. First, the process and the decisions behind it are more important than the amount of code. Second, more advanced features can be explored in a future series.\n::\n\n## Building the comment system\n\nNow that the requirements are clear, let us map them to the concepts in our application.\n\nA comment is a message left by a user on a blog post. In our system, the model will have these properties:\n\n- `id`: The unique identifier of the comment.\n- `post_id`: The identifier of the post to which the comment belongs.\n- `user_id`: The identifier of the user who left the comment.\n- `content`: The content of the comment.\n- `created_at`: The timestamp when the comment was created.\n- `updated_at`: The timestamp when the comment was last updated.\n\n`user_id` references the `users` table, and the `User` model will have a `comments` relationship. What about `post_id`?\n\nFor `post_id`, we need a `Post` model with these properties:\n\n- `id`: The unique identifier of the post.\n- `meta_id`: The unique identifier coming from the frontend.\n- `title`: The title of the post.\n- `created_at`: The timestamp when the post was created.\n- `updated_at`: The timestamp when the post was last updated.\n\nThe `Post` model will have a `comments` relationship, allowing us to associate multiple comments with each post. We will discuss `meta_id` in the next article, so you can ignore its purpose for now.\n\nThe relationships will look like this:\n\n\u003C!-- TODO: add a drawsql image -->\n\nWith the models and relationships defined, we can design the API for retrieving, creating, editing, and deleting comments.\n\nFirst, list the endpoints we need:\n\n- List all comments for a post, from anyone\n- Create a comment, from an authenticated user\n- Edit a comment, from the user who created it\n- Delete a comment, from the user who created it\n\nThen, we can map the endpoints to routes:\n\n- `GET    \u002Fposts\u002F{post}\u002Fcomments`: List all comments for a post\n- `POST   \u002Fposts\u002F{post}\u002Fcomments`: Create a comment\n- `PUT    \u002Fcomments\u002F{comment}`: Edit a comment\n- `DELETE \u002Fcomments\u002F{comment}`: Delete a comment\n\nThe mapping is straightforward. Why use `\u002Fcomments\u002F{comment}` instead of `\u002Fposts\u002F{post}\u002Fcomments\u002F{comment}` for the last two routes? A comment ID is unique, so we can identify the comment without repeating the post ID. In Laravel, this is called [shallow nesting](https:\u002F\u002Flaravel.com\u002Fdocs\u002F12.x\u002Fcontrollers#shallow-nesting).\n\n### Summary before writing code\n\nBefore writing code, we can summarize the implementation steps:\n\n1. Create a `Post` model with its migration.\n\n```bash [terminal]\nphp artisan make:model Post -m -f\n```\n\n2. Create a `Comment` model with its migration.\n\n```bash [terminal]\nphp artisan make:model Comment -m -f\n```\n\n3. Create a `CommentController` in `app\u002FHttp\u002FApi`.\n\n```bash [terminal]\nphp artisan make:controller Api\u002FCommentController\n```\n\n4. Create a `PostCommentController` in `app\u002FHttp\u002FApi`.\n\n```bash [terminal]\nphp artisan make:controller Api\u002FPostCommentController\n```\n\n5. Add the routes to `routes\u002Fapi.php`.\n\nWe will add the tests as we go.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nI will not explain every test in detail. I will focus on the most important ones.\n::\n\nReady? Let's go!\n\n## Viewing and creating comments\n\nCreate the post model with Artisan:\n\n```bash [terminal]\nphp artisan make:model Post -m -f\n```\n\nNow, let's jump to the migration file and add the following code:\n\n```php [database\u002Fmigrations\u002F2025_03_02_121249_create_posts_table.php]\nreturn new class extends Migration\n{\n    Schema::create('posts', function (Blueprint $table) {\n        $table->id();\n\n        $table->string('title'); \u002F\u002F [!code ++]\n        $table->unsignedInteger('meta_id')->unique(); \u002F\u002F [!code ++]\n\n        $table->timestamps();\n    });\n};\n```\n\nUpdate the factory to match the migration:\n\n```php [database\u002Ffactories\u002FPostFactory.php]\nclass PostFactory extends Factory\n{\n    public function definition(): array\n    {\n        return [\n            'title' => fake()->sentence(), \u002F\u002F [!code ++]\n            'meta_id' => fake()->unique()->numberBetween(1, 1000), \u002F\u002F [!code ++]\n        ];\n    }\n}\n```\n\nAdd a test to ensure that the model has the expected shape.\n\nFirst, we need to create a test file:\n\n```bash [terminal]\nmkdir -p tests\u002FUnit\u002FModels && touch tests\u002FUnit\u002FModels\u002FPostTest.php\n```\n\nThen, we can add the following code to the test file:\n\n```php [tests\u002FUnit\u002FModels\u002FPostTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Post;\n\ntest('to array', function () {\n    $post = Post::factory()->create()->fresh();\n\n    expect(array_keys($post->toArray()))\n        ->toEqual([\n            'id',\n            'title',\n            'meta_id',\n            'created_at',\n            'updated_at',\n        ]);\n});\n```\n\nThis minimal test verifies the model's persisted properties. It can catch an accidental column removal or addition in a migration. We will add a similar test for each model we create.\n\nTo make sure that our test is working, we need to enable the `tests\u002FUnit` folder to have access to a working database. To do this, we can add `Unit` to the `in` method of the `tests\u002FPest.php` file:\n\n```php [tests\u002FPest.php]\npest()->extend(Tests\\TestCase::class)\n    ->use(Illuminate\\Foundation\\Testing\\RefreshDatabase::class)\n    ->in('Http', 'Unit');\n```\n\nCreate the comment model in the same way:\n\n```bash [terminal]\nphp artisan make:model Comment -m -f\n```\n\nUpdate its migration:\n\n```php [database\u002Fmigrations\u002F2025_03_02_121249_create_comments_table.php]\nuse App\\Models\\Post; \u002F\u002F [!code ++]\nuse App\\Models\\User; \u002F\u002F [!code ++]\n\nreturn new class extends Migration\n{\n    Schema::create('comments', function (Blueprint $table) {\n        $table->id();\n\n        $table->foreignIdFor(Post::class)->constrained()->cascadeOnDelete(); \u002F\u002F [!code ++]\n        $table->foreignIdFor(User::class)->constrained()->cascadeOnDelete(); \u002F\u002F [!code ++]\n        $table->text('content'); \u002F\u002F [!code ++]\n\n        $table->timestamps();\n    });\n};\n```\n\nUpdate the factory to match the migration:\n\n```php [database\u002Ffactories\u002FCommentFactory.php]\nuse App\\Models\\Post; \u002F\u002F [!code ++]\nuse App\\Models\\User; \u002F\u002F [!code ++]\n\n\u002F\u002F ...\nclass CommentFactory extends Factory\n{\n    public function definition(): array\n    {\n        return [\n            'post_id' => Post::factory(), \u002F\u002F [!code ++]\n            'user_id' => User::factory(), \u002F\u002F [!code ++]\n            'content' => fake()->paragraph(), \u002F\u002F [!code ++]\n        ];\n    }\n}\n```\n\nAdd the corresponding test:\n\n```php [tests\u002FUnit\u002FModels\u002FCommentTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\n\ntest('to array', function () {\n    $comment = Comment::factory()->create()->fresh();\n\n    expect(array_keys($comment->toArray()))\n        ->toEqual([\n            'id',\n            'post_id',\n            'user_id',\n            'content',\n            'created_at',\n            'updated_at',\n        ]);\n});\n```\n\nNow add the relationships. A post has many comments, a comment belongs to a post, a comment belongs to a user, and a user has many comments.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nWe use `belongs to` instead of `has one` because a comment is a child of a post and cannot exist without one. A `has one` relationship describes a parent model's single child, such as a user having one profile while the profile belongs to the user.\n::\n\nThese relationships are defined as follows:\n\n```php [app\u002FModels\u002FPost.php]\nclass Post extends Model\n{\n    \u002F**\n     * Get all of the comments for the Post\n     *\n     * @return HasMany\u003CComment, covariant Post>\n     *\u002F\n    public function comments(): HasMany\n    {\n        return $this->hasMany(Comment::class);\n    }\n}\n```\n\n```php [app\u002FModels\u002FComment.php]\nclass Comment extends Model\n{\n    \u002F**\n     * Get the post that owns the comment.\n     *\n     * @return BelongsTo\u003CPost, covariant Comment>\n     *\u002F\n    public function post(): BelongsTo\n    {\n        return $this->belongsTo(Post::class);\n    }\n\n    \u002F**\n     * Get the user that owns the comment.\n     *\n     * @return BelongsTo\u003CUser, covariant Comment>\n     *\u002F\n    public function user(): BelongsTo\n    {\n        return $this->belongsTo(User::class);\n    }\n}\n```\n\n```php [app\u002FModels\u002FUser.php]\nclass User extends Authenticatable\n{\n    \u002F**\n     * Get comments that belong to the user.\n     *\n     * @return HasMany\u003CComment, covariant User>\n     *\u002F\n    public function comments(): HasMany\n    {\n        return $this->hasMany(Comment::class);\n    }\n}\n```\n\nThese relationships simplify Eloquent queries. To get all comments for a post, we can write:\n\n```php [Example]\nPost::find(1)->comments;\n```\n\nThey also help when using factory methods such as `has` and `for` to create related models.\n\nAdd relationship tests to ensure that the models are connected as expected.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nWhen working with models, I often write the tests after the first implementation because the design can change quickly. Writing the model helps me clarify what the tests should verify.\n::\n\n```php [tests\u002FUnit\u002FModels\u002FPostTest.php]\nuse App\\Models\\Comment;\n\ntest('relations', function () {\n    $post = Post::factory()\n        ->hasComments(1)\n        ->create();\n\n    expect($post->comments)->each->toBeInstanceOf(Comment::class);\n});\n```\n\n```php [tests\u002FUnit\u002FModels\u002FCommentTest.php]\nuse App\\Models\\Post;\nuse App\\Models\\User;\n\ntest('relations', function () {\n    $comment = Comment::factory()\n        ->forPost()\n        ->create();\n\n    expect($comment->post)->toBeInstanceOf(Post::class)\n        ->and($comment->user)->toBeInstanceOf(User::class);\n});\n```\n\n```php [tests\u002FUnit\u002FModels\u002FUserTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\nuse App\\Models\\User;\n\ntest('to array', function () {\n    $user = User::factory()->create()->fresh();\n\n    expect(array_keys($user->toArray()))\n        ->toEqual([\n            'id',\n            'name',\n            'username',\n            'email',\n            'email_verified_at',\n            'github_id',\n            'avatar',\n            'created_at',\n            'updated_at',\n        ]);\n});\n\ntest('relations', function () {\n    $user = User::factory()\n        ->hasComments(1)\n        ->create();\n\n    expect($user->comments)->each->toBeInstanceOf(Comment::class);\n});\n```\n\nWe had not added any tests for `User`, so this is a good opportunity to add its array-shape test as well.\n\nThe pattern is consistent, and Laravel makes each step straightforward.\n\n## Creating the controllers\n\nNow that the models are ready, we can create the controllers.\n\n`PostCommentController` will have two methods:\n\n- `index`: lists all comments for a post through `GET \u002Fposts\u002F{post}\u002Fcomments`.\n- `store`: creates a comment through `POST \u002Fposts\u002F{post}\u002Fcomments`.\n\nAs in the previous article, let's start by writing a test for the `index` method:\n\n```php [tests\u002FFeature\u002FHttp\u002FApi\u002FPost\u002FComment\u002FIndexTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\nuse App\\Models\\Post;\nuse Illuminate\\Testing\\Fluent\\AssertableJson;\n\nit('returns comments', function () {\n    $post = Post::factory()->create();\n    $comments = Comment::factory()\n        ->count(2)\n        ->for($post)\n        ->create();\n\n    $this->getJson(route('posts.comments', $post))\n        ->assertJson(\n            fn (AssertableJson $json) => $json\n                ->has(\n                    'data',\n                    2,\n                    fn (AssertableJson $json) => $json\n                        ->where('id', $comments->first()->id)\n                        ->where('content', $comments->first()->content)\n                        ->has(\n                            'author',\n                            fn (AssertableJson $json) => $json\n                                ->where('name', $comments->first()->user->name)\n                                ->where('username', $comments->first()->user->username)\n                                ->where('avatar', $comments->first()->user->avatar)\n                        )\n                )\n        );\n});\n```\n\nFor HTTP tests, I use the `AAA` pattern:\n\n- Arrange: prepare the data\n- Act: call the method\n- Assert: check the result\n\nIn this test, we create a post and two comments for it. That is the `Arrange` step. We then call `GET \u002Fposts\u002F{post}\u002Fcomments`, which is the `Act` step. Finally, we verify that the response contains two comments and has the expected structure, which is the `Assert` step.\n\nThe failing test tells us to add a route in `routes\u002Fapi.php`:\n\n```php [routes\u002Fapi.php]\n\u003C?php\n\nuse Illuminate\\Support\\Facades\\Route;\nuse App\\Http\\Controllers\\Api\\PostCommentController;\n\nRoute::get('\u002Fposts\u002F{post}\u002Fcomments', [PostCommentController::class, 'index'])\n    ->name('posts.comments');\n```\n\nThen, we must instruct Laravel to read this file by updating the `bootstrap\u002Fapp.php` file:\n\n```php [bootstrap\u002Fapp.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse Illuminate\\Foundation\\Application;\nuse Illuminate\\Foundation\\Configuration\\Exceptions;\nuse Illuminate\\Foundation\\Configuration\\Middleware;\n\nreturn Application::configure(basePath: dirname(__DIR__))\n    ->withRouting(\n        web: __DIR__.'\u002F..\u002Froutes\u002Fweb.php',\n        api: __DIR__.'\u002F..\u002Froutes\u002Fapi.php', \u002F\u002F [!code ++]\n        commands: __DIR__.'\u002F..\u002Froutes\u002Fconsole.php',\n        health: '\u002Fup',\n    )\n```\n\nFinally, create the controller with an `index` method:\n\n```bash [terminal]\nphp artisan make:controller Api\u002FPostCommentController\n```\n\n```php [app\u002FHttp\u002FApi\u002FPostCommentController.php]\n\u003C?php\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Controllers\\Controller;\nuse Illuminate\\Http\\Request;\n\nclass PostCommentController extends Controller\n{\n    public function index(Request $request)\n    {\n        \u002F\u002F\n    }\n}\n```\n\nThe route now exists, but the test reports that the response is not valid JSON because the controller does not return anything. 😄\n\nUse that failure as the next implementation step:\n\n```php [app\u002FHttp\u002FApi\u002FPostCommentController.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Controllers\\Controller;\nuse App\\Http\\Resources\\CommentResource;\nuse App\\Models\\Comment;\nuse Illuminate\\Http\\Resources\\Json\\ResourceCollection;\n\nfinal class PostCommentController extends Controller\n{\n    public function index(): ResourceCollection\n    {\n        $comments = Comment::query()\n          ->with('user')\n          ->get();\n\n        return CommentResource::collection($comments);\n    }\n}\n```\n\nThe `index` method retrieves the comments, eager-loads the user relationship, and returns a `CommentResource` collection.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nRetrieving every record is usually not a good practice; pagination is safer for a large collection. In this example, we expect only a small number of comments, so returning the collection is acceptable. Pagination can be added later if that assumption changes.\n::\n\nNow, we need to create the `CommentResource` class:\n\n```bash [terminal]\nphp artisan make:resource CommentResource\n```\n\n```php [app\u002FHttp\u002FResources\u002FCommentResource.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Resources;\n\nuse App\\Models\\Comment;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\n\u002F**\n * @mixin Comment\n *\u002F\nfinal class CommentResource extends JsonResource\n{\n    \u002F**\n     * Transform the resource into an array.\n     *\n     * @return array\u003Cstring, mixed>\n     *\u002F\n    public function toArray(Request $request): array\n    {\n        return [\n            'id' => $this->id,\n            'content' => $this->content,\n            'author' => UserResource::make($this->whenLoaded('user')),\n        ];\n    }\n}\n```\n\nAnd a second resource for the author:\n\n```bash [terminal]\nphp artisan make:resource UserResource\n```\n\n```php [app\u002FHttp\u002FResources\u002FUserResource.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Resources;\n\nuse App\\Models\\User;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\n\u002F**\n * @mixin User\n *\u002F\nfinal class UserResource extends JsonResource\n{\n    \u002F**\n     * Transform the resource into an array.\n     *\n     * @return array\u003Cstring, mixed>\n     *\u002F\n    public function toArray(Request $request): array\n    {\n        return [\n            'name' => $this->name,\n            'username' => $this->username,\n            'avatar' => $this->avatar,\n        ];\n    }\n}\n```\n\nWhat are these resources?\n\nA resource is a transformation layer between our Eloquent models and the JSON responses sent to the client. It defines how a model is transformed into JSON.\n\nHere, we return a comment's `id`, `content`, and `author`. The nested author resource exposes only the user's `name`, `username`, and `avatar`. This lets us change the response shape without changing the controller and prevents accidental exposure of fields such as the user's email.\n\nNow, we can run our test and it should pass. But let's not be too hasty and add a test to verify that this method only returns the comments for the post:\n\n```php [tests\u002FFeature\u002FHttp\u002FApi\u002FPost\u002FComment\u002FIndexTest.php]\nit('returns comments for a post', function () {\n    Comment::factory()\n        ->count(2)\n        ->create();\n\n    $this->getJson(route('posts.comments', Post::factory()->create()))\n        ->assertJson(\n            fn (AssertableJson $json) => $json\n                ->has('data', 0)\n        );\n});\n```\n\nThis test creates two comments for one post, calls the route with another post, and expects an empty response.\n\nThe test fails because the controller is not filtering comments by post.\n\nTo fix this, we can update the `index` method:\n\n```php [app\u002FHttp\u002FApi\u002FPostCommentController.php]\nuse App\\Models\\Post;\n\nfinal class PostCommentController extends Controller\n{\n    public function index(Post $post): ResourceCollection\n    {\n        $comments = Comment::query()\n            ->whereBelongsTo($post)\n            ->with('user')\n            ->get();\n\n        return CommentResource::collection($comments);\n    }\n}\n```\n\nLaravel's route model binding gives us the `Post` instance directly. Because the route contains `{post}` and the method accepts a `Post`, Laravel finds the matching record and injects it. This keeps the controller concise.\n\nNow, we can run our tests and they should pass. 👌\n\nNow move on to the `store` method.\n\nYou know the drill, let's start by writing a test:\n\n```php [tests\u002FFeature\u002FHttp\u002FApi\u002FPost\u002FComment\u002FStoreTest.php]\n\u003C?php\n\nuse App\\Models\\Post;\n\nit('requires authentication', function () {\n    $post = Post::factory()->create();\n\n    $this->postJson(route('posts.comments.store', $post))\n        ->assertUnauthorized();\n});\n```\n\nThis test verifies that authentication is required. Add the route:\n\n```php [routes\u002Fapi.php]\nRoute::middleware('auth')->group(function () {\n    Route::post('\u002Fposts\u002F{post}\u002Fcomments', [PostCommentController::class, 'store'])\n        ->name('posts.comments.store');\n});\n```\n\nContinuing with another test:\n\n```php [tests\u002FFeature\u002FHttp\u002FApi\u002FPost\u002FComment\u002FStoreTest.php]\nuse App\\Models\\User;\n\n\u002F\u002F ...\n\nit('stores a comment', function () {\n    $user = User::factory()->create();\n    $post = Post::factory()->create();\n\n    $this->actingAs($user)\n        ->postJson(route('posts.comments.store', $post), [\n            'content' => 'This is a comment',\n        ]);\n\n    $this->assertDatabaseHas('comments', [\n        'post_id' => $post->id,\n        'user_id' => $user->id,\n        'content' => 'This is a comment',\n    ]);\n});\n```\n\nThis test verifies that the comment is stored with the correct `post_id`, `user_id`, and content. The controller sets the two foreign keys.\n\nNow, we can implement the `store` method:\n\n```php [app\u002FHttp\u002FApi\u002FPostCommentController.php]\nfinal class PostCommentController extends Controller\n{\n    public function store(Request $request, Post $post)\n    {\n        Comment::create([\n            'post_id' => $post->id,\n            'user_id' => $request->user()->id,\n            'content' => $request->input('content')\n        ]);\n    }\n}\n```\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nWe are writing only the minimum code needed to make the tests pass. That does not mean the implementation is complete. For example, the request still needs validation, which we will add with the next test.\n::\n\nAdd a test for request validation:\n\n```php [tests\u002FFeature\u002FHttp\u002FApi\u002FPost\u002FComment\u002FStoreTest.php]\nit('requires a valid data', function (array $badData, array|string $errors) {\n    $post = Post::factory()->create();\n\n    $response = $this->actingAs(User::factory()->create())\n        ->postJson(route('posts.comments.store', $post), $badData);\n\n    $response->assertJsonValidationErrors($errors);\n})->with([\n    [['content' => ''], ['content' => 'The content field is required.']],\n    [['content' => 1], ['content' => 'The content field must be a string.']],\n    [['content' => 'a'], ['content' => 'The content field must be at least 6 characters.']],\n    [['content' => 'a'.str_repeat('a', 2001)], ['content' => 'The content field must not be greater than 2000 characters.']],\n]);\n```\n\nPest runs this test four times with different data. A dataset lets us cover several invalid inputs without duplicating the test body.\n\nCreate a `StoreCommentRequest` class to hold these rules:\n\n```bash [terminal]\nphp artisan make:request StoreCommentRequest\n```\n\n```php [app\u002FHttp\u002FRequests\u002FStoreCommentRequest.php]\n\u003C?php\n\nnamespace App\\Http\\Requests;\n\nuse Illuminate\\Foundation\\Http\\FormRequest;\n\nclass StoreCommentRequest extends FormRequest\n{\n    \u002F**\n     * Get the validation rules that apply to the request.\n     *\n     * @return array\u003Cstring, \\Illuminate\\Contracts\\Validation\\ValidationRule|array\u003Cmixed>|string>\n     *\u002F\n    public function rules(): array\n    {\n        return [\n            'content' => ['required', 'string', 'max:2000', 'min:6'],\n        ];\n    }\n}\n```\n\nUpdate `store` to use the new request:\n\n```php [app\u002FHttp\u002FApi\u002FPostCommentController.php]\nuse App\\Http\\Requests\\StoreCommentRequest; \u002F\u002F [!code --]\nuse Illuminate\\Http\\Request; \u002F\u002F [!code --]\n\nfinal class PostCommentController extends Controller\n{\n    public function store(StoreCommentRequest $request, Post $post) \u002F\u002F [!code highlight]\n    {\n        \u002F\u002F ...\n    }\n}\n```\n\nLaravel now validates the request before the controller runs. ✨\n\nFinally, we can add a test to check that the returned data is correct:\n\n```php [tests\u002FFeature\u002FHttp\u002FApi\u002FPost\u002FComment\u002FStoreTest.php]\nit('returns the created comment', function () {\n    $user = User::factory()->create();\n    $post = Post::factory()->create();\n    $comment = Comment::factory()->make();\n\n    $response = $this->actingAs($user)\n        ->postJson(route('posts.comments.store', $post), [\n            'content' => $comment->content,\n        ]);\n\n    $comment = Comment::first();\n    $response\n        ->assertCreated()\n        ->assertJson(\n            fn (AssertableJson $json) => $json\n                ->has(\n                    'data',\n                    fn (AssertableJson $json) => $json\n                        ->where('id', $comment->id)\n                        ->where('content', $comment->content)\n                        ->has(\n                            'author',\n                            fn (AssertableJson $json) => $json\n                                ->where('name', $user->name)\n                                ->where('username', $user->username)\n                                ->where('avatar', $user->avatar)\n                        )\n                )\n        );\n});\n```\n\nThis test verifies the response data and checks that the status code is `201 Created` with `assertCreated`.\n\nNow, let's update the `store` method to return the created comment:\n\n```php [app\u002FHttp\u002FApi\u002FPostCommentController.php]\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\nfinal class PostCommentController extends Controller\n{\n    public function store(StoreCommentRequest $request, Post $post): JsonResource\n    {\n        $comment = Comment::create([ \u002F\u002F [!code highlight]\n            'post_id' => $post->id,\n            'user_id' => $request->user()->id,\n            'content' => $request->input('content')\n        ]);\n\n        $comment->load('user'); \u002F\u002F [!code ++]\n\n        return CommentResource::make($comment); \u002F\u002F [!code ++]\n    }\n}\n```\n\nAll tests should now pass.\n\nThese tests are representative of the tests you can write for other controllers.\n\n## Editing and deleting comments\n\nNow we can implement comment editing and deletion.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nI will move faster here because the workflow is familiar. The complete tests are included so you can still follow each requirement.\n::\n\nFor the edition, we need to create a new test file:\n\n```bash [terminal]\nmkdir -p tests\u002FHttp\u002FApi\u002FComment && touch tests\u002FHttp\u002FApi\u002FComment\u002FUpdateTest.php\n```\n\nThen, we can add the following test:\n\n```php [tests\u002FHttp\u002FApi\u002FComment\u002FUpdateTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\nuse App\\Models\\User;\nuse Illuminate\\Testing\\Fluent\\AssertableJson;\n\nit('requires authentication', function () {\n    $comment = Comment::factory()->create();\n\n    $this->putJson(route('comments.update', $comment))\n        ->assertUnauthorized();\n});\n\nit('requires the user to be the author of the comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->create();\n\n    $this->actingAs($user)\n        ->putJson(route('comments.update', $comment), [\n            'content' => 'Updated content',\n        ])\n        ->assertForbidden();\n});\n\nit('updates a comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()\n        ->for($user)\n        ->create();\n\n    $this->actingAs($user)\n        ->putJson(route('comments.update', $comment), [\n            'content' => 'Updated content',\n        ]);\n\n    $this->assertDatabaseHas('comments', [\n        'id' => $comment->id,\n        'content' => 'Updated content',\n    ]);\n});\n\nit('requires a valid data', function (array $badData, array|string $errors) {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->for($user)->create();\n\n    $this->actingAs($user)\n        ->putJson(route('comments.update', $comment), $badData)\n        ->assertJsonValidationErrors($errors);\n})->with([\n    [['content' => ''], ['content' => 'The content field is required.']],\n    [['content' => 1], ['content' => 'The content field must be a string.']],\n    [['content' => 'a'], ['content' => 'The content field must be at least 6 characters.']],\n    [['content' => 'a' . str_repeat('a', 2001)], ['content' => 'The content field must not be greater than 2000 characters.']],\n]);\n\nit('returns the comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->for($user)->create();\n\n    $this->actingAs($user)\n        ->putJson(route('comments.update', $comment), [\n            'content' => 'Updated content',\n        ])\n        ->assertOk()\n        ->assertJson(\n            fn(AssertableJson $json) => $json\n                ->has(\n                    'data',\n                    fn(AssertableJson $json) => $json\n                        ->where('id', $comment->id)\n                        ->where('content', 'Updated content')\n                        ->has(\n                            'author',\n                            fn(AssertableJson $json) => $json\n                                ->where('name', $user->name)\n                                ->where('username', $user->username)\n                                ->where('avatar', $user->avatar)\n                        )\n                )\n        );\n});\n```\n\nThen, we can add the route:\n\n```php [routes\u002Fapi.php]\n\u003C?php\n\nuse App\\Http\\Controllers\\Api\\CommentController; \u002F\u002F [!code ++]\n\nRoute::middleware('auth')->group(function () {\n    Route::put('\u002Fcomments\u002F{comment}', [CommentController::class, 'update']) \u002F\u002F [!code ++]\n        ->name('comments.update'); \u002F\u002F [!code ++]\n});\n```\n\nCreate the controller:\n\n```bash [terminal]\nphp artisan make:controller Api\u002FCommentController\n```\n\nImplement the `update` method:\n\n```php [app\u002FHttp\u002FApi\u002FCommentController.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Controllers\\Controller;\nuse App\\Http\\Requests\\UpdateCommentRequest;\nuse App\\Http\\Resources\\CommentResource;\nuse App\\Models\\Comment;\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\nfinal class CommentController extends Controller\n{\n    public function update(UpdateCommentRequest $request, Comment $comment): JsonResource\n    {\n        $comment->update($request->validated());\n        $comment->load('user');\n\n        return CommentResource::make($comment);\n    }\n}\n```\n\nThis method needs a dedicated form request:\n\n```bash [terminal]\nphp artisan make:request UpdateCommentRequest\n```\n\nThen, we can implement the request:\n\n```php [app\u002FHttp\u002FRequests\u002FUpdateCommentRequest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Requests;\n\nuse App\\Models\\Comment;\nuse Illuminate\\Foundation\\Http\\FormRequest;\n\n\u002F**\n * @property Comment $comment\n *\u002F\nfinal class UpdateCommentRequest extends FormRequest\n{\n    \u002F**\n     * Determine if the user is authorized to make this request.\n     *\u002F\n    public function authorize(): bool\n    {\n        return $this->user()->can('update', $this->comment);\n    }\n\n    \u002F**\n     * Get the validation rules that apply to the request.\n     *\n     * @return array\u003Cstring, \\Illuminate\\Contracts\\Validation\\ValidationRule|array\u003Cmixed>|string>\n     *\u002F\n    public function rules(): array\n    {\n        return [\n            'content' => ['required', 'string', 'max:2000', 'min:6'],\n        ];\n    }\n}\n```\n\nThe request's `authorize` method checks whether the current user may update the comment. It delegates that decision to a policy, which we need to create.\n\n```bash [terminal]\nphp artisan make:policy CommentPolicy\n```\n\nThen, we can implement the policy:\n\n```php [app\u002FPolicies\u002FCommentPolicy.php]\n\u003C?php\n\nnamespace App\\Policies;\n\nuse App\\Models\\Comment;\nuse App\\Models\\User;\n\nclass CommentPolicy\n{\n    \u002F**\n     * Determine whether the user can update the model.\n     *\u002F\n    public function update(User $user, Comment $comment): bool\n    {\n        return $user->id === $comment->user_id;\n    }\n}\n```\n\nThe update flow is now complete.\n\nFinish the article by adding comment deletion:\n\n```php [tests\u002FHttp\u002FApi\u002FComment\u002FDestroyTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\Comment;\nuse App\\Models\\User;\n\nit('requires authentification', function () {\n    $comment = Comment::factory()->create();\n\n    $this->deleteJson(route('comments.destroy', $comment))\n        ->assertUnauthorized();\n});\n\nit('requires the user to be the author of the comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->create();\n\n    $this->actingAs($user)\n        ->deleteJson(route('comments.destroy', $comment))\n        ->assertForbidden();\n});\n\nit('deletes a comment', function () {\n    $user = User::factory()->create();\n    $comment = Comment::factory()->for($user)->create();\n\n    $this->actingAs($user)\n        ->deleteJson(route('comments.destroy', $comment));\n\n    $this->assertDatabaseMissing('comments', [\n        'id' => $comment->id,\n    ]);\n});\n```\n\n```php [routes\u002Fapi.php]\n\u003C?php\n\n\u002F\u002F ...\n\nRoute::middleware('auth')->group(function () {\n    \u002F\u002F ...\n\n    Route::delete('\u002Fcomments\u002F{comment}', [CommentController::class, 'destroy'])\n        ->name('comments.destroy');\n});\n\n```\n\n```php [app\u002FHttp\u002FApi\u002FCommentController.php]\nuse Illuminate\\Http\\Response;\nuse Illuminate\\Support\\Facades\\Gate;\n\nfinal class CommentController extends Controller\n{\n    \u002F\u002F ...\n\n    public function destroy(Comment $comment): Response\n    {\n        Gate::authorize('delete', $comment);\n\n        $comment->delete();\n\n        return response()->noContent();\n    }\n}\n```\n\nThe `Gate` facade authorizes the deletion. Laravel resolves `CommentPolicy` from the model passed to `authorize`.\n\n```php [app\u002FPolicies\u002FCommentPolicy.php]\nfinal class CommentPolicy\n{\n    \u002F\u002F ...\n\n    \u002F**\n     * Determine whether the user can delete the model.\n     *\u002F\n    public function delete(User $user, Comment $comment): bool\n    {\n        return $user->id === $comment->user_id;\n    }\n}\n```\n\nThe comment system is ready, and the tests give us confidence that its main behaviors work without requiring a manual click-through.\n\n## What's next\n\nThe comment API is now in place. It supports listing, creating, updating, and deleting comments, and the tests describe the behavior and permissions that keep those operations safe.\n\nWorking test-first kept the implementation focused: each failure pointed to the next piece of behavior, and the completed tests now protect us from regressions.\n\nNext, we will connect the static frontend to the backend. We will generate post metadata during the VitePress build and use Laravel to synchronize the `posts` table automatically.\n",{"title":5,"description":4585},"empower-and-dynamize-our-vitepress-blog-with-a-laravel-api",{"loc":4589},"series\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbuilding-a-simple-comment-system-for-user-engagement","6eOLclUz0TtsdZt1yFwOup9ik3tenxet47sWQ5D2j-0",{"overview":4597,"chapters":4771},{"id":4598,"title":4599,"body":4600,"contentId":4755,"date":4756,"description":4757,"extension":4586,"github":4587,"meetTheInstructor":4758,"meta":4759,"navigation":449,"part":4587,"path":4760,"rawbody":4761,"robots":4587,"schemaOrg":4587,"seo":4762,"seriesSlug":4592,"sitemap":4763,"stem":4764,"subtitle":4765,"topics":4766,"__hash__":4770},"series\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api.md","Empower and Enhance Your VitePress Blog with a Laravel API",{"type":7,"value":4601,"toc":4752},[4602,4605,4608,4611,4615,4624,4627,4636,4639,4642,4723,4726,4729,4732,4742,4746],[10,4603,4604],{},"Hello! 👋",[10,4606,4607],{},"After building our VitePress blog, we are ready to make it more dynamic with a Laravel API.",[10,4609,4610],{},"In the previous series, we explored VitePress from the initial project setup to deployment on Cloudflare Pages. We built a functional, automated blog with SEO metadata, Open Graph images, and a GitHub projects page. The blog handled everything at build time, so publishing content was the only task left.",[4612,4613],"callout-read-more",{"id":4614},"43c95b33-041c-4108-ab98-0d21ef60ed7f",[10,4616,4617,4618,4623],{},"This series introduces back-end development by creating a ",[227,4619,4622],{"href":4620,"rel":4621},"https:\u002F\u002Flaravel.com",[231],"Laravel"," API that gives our blog a few interactive features.",[10,4625,4626],{},"Until now, our blog has been mostly static. Content was generated at build time, with a small amount of data loaded dynamically, and the resulting HTML files were distributed through a CDN. By adding a Laravel API, we will let readers interact with the blog through features such as post reactions and comments.",[10,4628,4629,4630,4635],{},"Although the focus is on the back end, we will also integrate the API into our VitePress blog. We will use Vue.js and ",[227,4631,4634],{"href":4632,"rel":4633},"https:\u002F\u002Fpinia-colada.esm.dev\u002F",[231],"Pinia Colada"," as our data-fetching framework. VitePress is a Vue.js application, so we can extend it with the components we need.",[10,4637,4638],{},"The examples are designed to be easy to follow. Unnecessary complexity and over-engineering are neither desirable nor necessary here. We will focus on simplicity, clarity, and efficiency.",[10,4640,4641],{},"Throughout the series, we will build a Laravel API and integrate it with our VitePress blog. We will cover:",[17,4643,4644,4651,4678,4689,4695,4705,4711,4717],{},[20,4645,4646,4650],{},[4647,4648,4649],"strong",{},"Setting up the Laravel project",": Create a new Laravel project and become familiar with its structure.",[20,4652,4653,4656,4657,2414,4662,2414,4667,2417,4672,4677],{},[4647,4654,4655],{},"Improving the development workflow",": Configure ",[227,4658,4661],{"href":4659,"rel":4660},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fpint",[231],"Pint",[227,4663,4666],{"href":4664,"rel":4665},"https:\u002F\u002Fgithub.com\u002Frectorphp\u002Frector",[231],"Rector",[227,4668,4671],{"href":4669,"rel":4670},"https:\u002F\u002Fgithub.com\u002Flarastan\u002Flarastan",[231],"Larastan",[227,4673,4676],{"href":4674,"rel":4675},"https:\u002F\u002Fpestphp.com\u002F",[231],"Pest"," for formatting, refactoring, static analysis, and testing.",[20,4679,4680,4683,4684,233],{},[4647,4681,4682],{},"Adding social authentication",": Let users sign in with GitHub through ",[227,4685,4688],{"href":4686,"rel":4687},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fsocialite",[231],"Laravel Socialite",[20,4690,4691,4694],{},[4647,4692,4693],{},"Connecting the applications",": Configure Sanctum, CORS, CSRF protection, and the first requests between the VitePress frontend and the Laravel API.",[20,4696,4697,4700,4701,4704],{},[4647,4698,4699],{},"Managing authentication state",": Use ",[227,4702,4634],{"href":4632,"rel":4703},[231]," to retrieve the current user and log out with an optimistic update.",[20,4706,4707,4710],{},[4647,4708,4709],{},"Building the comment API",": Create the models, relationships, endpoints, validation, authorization, and tests for comments.",[20,4712,4713,4716],{},[4647,4714,4715],{},"Keeping the backend in sync",": Generate post metadata from VitePress and synchronize it with the Laravel database.",[20,4718,4719,4722],{},[4647,4720,4721],{},"Building the comment interface",": Fetch, create, edit, and delete comments from the VitePress frontend.",[10,4724,4725],{},"By the end of the series, you will have a blog backed by a Laravel API. Readers will be able to sign in with GitHub and leave comments, and the architecture will be ready for additional interactive features.",[10,4727,4728],{},"Testing is part of the development process and will be included at each stage, so it does not need a dedicated article.",[10,4730,4731],{},"If you have questions, feedback, or suggestions, feel free to share them in the comments. Your input helps improve the series.",[36,4733,4734],{"color":38,"icon":39},[10,4735,4736,4737,4741],{},"This series assumes prior knowledge of TypeScript, Vue.js, and Laravel. If you are unfamiliar with any of these technologies, review the ",[227,4738,4740],{"href":4739},"\u002Fseries\u002Fcreate-a-blog-with-vitepress-and-vue-js-from-scratch","Create a Blog with VitePress and Vue.js from Scratch"," first.",[44,4743,4745],{"id":4744},"chapters","Chapters",[4747,4748],"series-chapters-list",{"className":4749},[4750,4751],"mx-auto","max-w-5xl",{"title":258,"searchDepth":289,"depth":289,"links":4753},[4754],{"id":4744,"depth":289,"text":4745},"676d45dd-eb18-42ec-803e-b9d6b7f04b42","2024-11-19","Transform your VitePress blog into a dynamic platform with a Laravel API. Leverage backend API capabilities to create advanced features.","I create this series because I love \u003Cstrong>VitePress\u003C\u002Fstrong> and \u003Cstrong>Laravel\u003C\u002Fstrong>. I truly believe that combining the two results in a simple yet \u003Cstrong>powerful solution\u003C\u002Fstrong> for creating a blog. I want to empower developers to enhance their VitePress blogs with a Laravel API to create advanced features.",{},"\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api","---\ncontentId: 676d45dd-eb18-42ec-803e-b9d6b7f04b42\ntitle: Empower and Enhance Your VitePress Blog with a Laravel API\nsubtitle: Transform your VitePress blog into a dynamic platform with an API\ndescription: Transform your VitePress blog into a dynamic platform with a Laravel API. Leverage backend API capabilities to create advanced features.\ndate: 2024-11-19\ntopics:\n  - laravel\n  - vitepress\n  - api\nmeetTheInstructor: I create this series because I love \u003Cstrong>VitePress\u003C\u002Fstrong> and \u003Cstrong>Laravel\u003C\u002Fstrong>. I truly believe that combining the two results in a simple yet \u003Cstrong>powerful solution\u003C\u002Fstrong> for creating a blog. I want to empower developers to enhance their VitePress blogs with a Laravel API to create advanced features.\nseriesSlug: empower-and-dynamize-our-vitepress-blog-with-a-laravel-api\n---\n\nHello! 👋\n\nAfter building our VitePress blog, we are ready to make it more dynamic with a Laravel API.\n\nIn the previous series, we explored VitePress from the initial project setup to deployment on Cloudflare Pages. We built a functional, automated blog with SEO metadata, Open Graph images, and a GitHub projects page. The blog handled everything at build time, so publishing content was the only task left.\n\n\u003CCalloutReadMore id=\"43c95b33-041c-4108-ab98-0d21ef60ed7f\" \u002F>\n\nThis series introduces back-end development by creating a [Laravel](https:\u002F\u002Flaravel.com) API that gives our blog a few interactive features.\n\nUntil now, our blog has been mostly static. Content was generated at build time, with a small amount of data loaded dynamically, and the resulting HTML files were distributed through a CDN. By adding a Laravel API, we will let readers interact with the blog through features such as post reactions and comments.\n\nAlthough the focus is on the back end, we will also integrate the API into our VitePress blog. We will use Vue.js and [Pinia Colada](https:\u002F\u002Fpinia-colada.esm.dev\u002F) as our data-fetching framework. VitePress is a Vue.js application, so we can extend it with the components we need.\n\nThe examples are designed to be easy to follow. Unnecessary complexity and over-engineering are neither desirable nor necessary here. We will focus on simplicity, clarity, and efficiency.\n\nThroughout the series, we will build a Laravel API and integrate it with our VitePress blog. We will cover:\n\n- **Setting up the Laravel project**: Create a new Laravel project and become familiar with its structure.\n- **Improving the development workflow**: Configure [Pint](https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fpint), [Rector](https:\u002F\u002Fgithub.com\u002Frectorphp\u002Frector), [Larastan](https:\u002F\u002Fgithub.com\u002Flarastan\u002Flarastan), and [Pest](https:\u002F\u002Fpestphp.com\u002F) for formatting, refactoring, static analysis, and testing.\n- **Adding social authentication**: Let users sign in with GitHub through [Laravel Socialite](https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fsocialite).\n- **Connecting the applications**: Configure Sanctum, CORS, CSRF protection, and the first requests between the VitePress frontend and the Laravel API.\n- **Managing authentication state**: Use [Pinia Colada](https:\u002F\u002Fpinia-colada.esm.dev\u002F) to retrieve the current user and log out with an optimistic update.\n- **Building the comment API**: Create the models, relationships, endpoints, validation, authorization, and tests for comments.\n- **Keeping the backend in sync**: Generate post metadata from VitePress and synchronize it with the Laravel database.\n- **Building the comment interface**: Fetch, create, edit, and delete comments from the VitePress frontend.\n\nBy the end of the series, you will have a blog backed by a Laravel API. Readers will be able to sign in with GitHub and leave comments, and the architecture will be ready for additional interactive features.\n\nTesting is part of the development process and will be included at each stage, so it does not need a dedicated article.\n\nIf you have questions, feedback, or suggestions, feel free to share them in the comments. Your input helps improve the series.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nThis series assumes prior knowledge of TypeScript, Vue.js, and Laravel. If you are unfamiliar with any of these technologies, review the [Create a Blog with VitePress and Vue.js from Scratch](\u002Fseries\u002Fcreate-a-blog-with-vitepress-and-vue-js-from-scratch) first.\n::\n\n## Chapters\n\n::series-chapters-list\n---\nclass: mx-auto max-w-5xl\n---\n::\n",{"title":4599,"description":4757},{"loc":4760},"series\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api","Transform your VitePress blog into a dynamic platform with an API",[4767,4768,4769],"laravel","vitepress","api","JLBtX9BKfN72BkhcYisEXraNGTvZSnT5YHM05A_uemk",[4772,4777,4782,4787,4788,4793,4798,4803],{"contentId":4773,"title":4774,"description":4775,"path":4776,"part":265,"github":4587,"topics":4587},"06469e25-715e-4a92-87b9-0db6db845a50","Setting Up Your Laravel Project Structure and Essentials","A comprehensive guide to setting up your Laravel project and understanding its structure for a better development experience.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fsetting-up-your-laravel-project-structure-and-essentials",{"contentId":4778,"title":4779,"description":4780,"path":4781,"part":289,"github":4587,"topics":4587},"d566d5f4-3c4a-44e5-89cb-b3c547673ffa","Pint, Rector, Larastan, and Pest: Essentials for Success","Explore the four indispensable tools for maintaining code quality and consistency in Laravel projects: Pint, Rector, Larastan, and Pest.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fpint-larastan-rector-and-pest-essential-for-success",{"contentId":4783,"title":4784,"description":4785,"path":4786,"part":317,"github":4587,"topics":4587},"3729f419-a8b6-486c-a845-ab5ba1a33172","Effortless Social Authentication with Laravel Socialite","Add GitHub authentication to Laravel with Socialite, OAuth callbacks, database synchronization, secure sessions, and test-first development.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Feffortless-social-authentication-with-laravel-socialite",{"contentId":4583,"title":5,"description":4585,"path":4589,"part":346,"github":4587,"topics":4587},{"contentId":4789,"title":4790,"description":4791,"path":4792,"part":372,"github":4587,"topics":4587},"53a607df-d10e-4423-966c-500d2885e6e0","Automating Your Backend to Stay in Sync Effortlessly","Generate frontend metadata with VitePress, synchronize posts with Laravel, and keep the backend database aligned automatically.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fautomating-your-backend-to-stay-in-sync-effortlessly",{"contentId":4794,"title":4795,"description":4796,"path":4797,"part":453,"github":4587,"topics":4587},"e6040e0a-4997-40d6-bde8-332cbca0f307","Bridging the Gap: Connecting Your Frontend and Backend","Connect a VitePress frontend to a Laravel API with Sanctum, CORS, CSRF protection, shared credentials, and a reusable API client.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbridging-the-gap-connecting-your-frontend-and-backend",{"contentId":4799,"title":4800,"description":4801,"path":4802,"part":459,"github":4587,"topics":4587},"d507f8af-7c76-4660-859e-23af11c0728e","Streamlining User Authentication from Frontend to Backend","Connect frontend authentication to Laravel with a current-user query, GitHub logout flow, Pinia Colada caching, and optimistic state updates.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fstreamlining-user-authentication-from-frontend-to-backend",{"contentId":4804,"title":4805,"description":4806,"path":4807,"part":465,"github":4587,"topics":4587},"1b2a6cc0-c10f-421a-9344-60cb1583a136","Simplifying Comment Querying and Editing with Pinia Colada","Build the VitePress comment interface with Pinia Colada queries, mutations, optimistic updates, reusable Vue components, and permissions.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fsimplifying-comment-querying-and-editing-with-pinia-colada",1795016693722]