[{"data":1,"prerenderedAt":2346},["ShallowReactive",2],{"series-\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fautomating-your-backend-to-stay-in-sync-effortlessly":3,"series-context-\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api":2132},{"id":4,"title":5,"body":6,"contentId":2120,"date":2121,"description":2122,"extension":872,"github":2123,"meetTheInstructor":2123,"meta":2124,"navigation":239,"part":236,"path":2125,"rawbody":2126,"robots":2123,"schemaOrg":2123,"seo":2127,"seriesSlug":2128,"sitemap":2129,"stem":2130,"subtitle":2123,"topics":2123,"__hash__":2131},"series\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fautomating-your-backend-to-stay-in-sync-effortlessly.md","Automating Your Backend to Stay in Sync Effortlessly",{"type":7,"value":8,"toc":2112},"minimark",[9,22,25,33,50,53,56,67,70,78,96,110,120,143,153,166,169,744,751,756,768,864,867,922,969,979,995,1008,1011,1088,1091,1095,1105,1113,1116,1135,1142,1153,1156,1398,1412,1434,1446,1483,1486,1489,1513,1516,1530,1541,1551,1565,1568,1573,1580,1594,1996,2007,2074,2077,2098,2102,2105,2108],[10,11,12,13,17,18,21],"p",{},"At the end of the previous article, we created a ",[14,15,16],"code",{},"posts"," table with a ",[14,19,20],{},"meta_id"," column. We have not used that column yet, so this article will connect it to the frontend.",[10,23,24],{},"VitePress generates a static website at build time, while comments are loaded dynamically for the post currently being viewed. To make that work, the frontend and backend need a stable way to identify the same post.",[10,26,27,28,32],{},"For example, the blog ",[29,30],"git-hub-link",{"repo":31},"barbapapazes\u002Fgarabit"," has two articles with these slugs:",[34,35,36,44],"ol",{},[37,38,39,40,43],"li",{},"Getting Started with Laravel (",[14,41,42],{},"getting-started-with-laravel",")",[37,45,46,47,43],{},"Getting Started with Vue 3 and Vite (",[14,48,49],{},"getting-started-with-vue-3-and-vite",[10,51,52],{},"We could use the slug as the identifier, but slugs sometimes change because of a typo, search-engine optimization, or a change in the content. Keeping an outdated slug only to preserve an identifier makes URLs less useful. We need a separate identifier that remains stable even when the slug changes.",[10,54,55],{},"The solution is to store a stable ID in each post's frontmatter. This ID identifies the post and does not change when its title, content, or slug changes.",[10,57,58,59,62,63,66],{},"The remaining question is how to send these IDs to the backend. Manual synchronization is error-prone and easy to automate, so the frontend will generate a ",[14,60,61],{},"meta.json"," file at build time. It will contain each post's ID and title. The backend will read that file and create or update the corresponding database records. The frontend can then fetch comments by using the ID in the post frontmatter, while the ",[14,64,65],{},"posts.id"," column remains an internal key used to link posts to comments.",[10,68,69],{},"The architecture is straightforward: VitePress writes the post metadata, and Laravel reads it to keep its records synchronized.",[71,72,74,75,77],"h2",{"id":73},"generating-the-metajson-file","Generating the ",[14,76,61],{}," file",[10,79,80,81,83,84,87,88,91,92,95],{},"For this part, open the ",[29,82],{"repo":31}," project. We will create a ",[14,85,86],{},"genMeta"," function that reads all Markdown files, extracts each ID and title from the frontmatter, and writes them to ",[14,89,90],{},"dist\u002Fmeta.json"," using VitePress's ",[14,93,94],{},"buildEnd"," hook. VitePress calls this hook after the rest of the build has finished, which makes it a good place to generate the file.",[10,97,98,99,102,103,106,107,109],{},"First, create a ",[14,100,101],{},"generators"," folder inside ",[14,104,105],{},".vitepress",". It will contain the functions called by the ",[14,108,94],{}," hook.",[111,112,115],"callout",{"color":113,"icon":114},"info","i-ph-info-duotone",[10,116,117,119],{},[14,118,101],{}," is only a naming choice. You can use any folder name you prefer.",[121,122,128],"pre",{"className":123,"code":124,"filename":125,"language":126,"meta":127,"style":127},"language-bash shiki shiki-themes github-light github-light github-dark","mkdir .vitepress\u002Fgenerators\n","terminal","bash","",[14,129,130],{"__ignoreMap":127},[131,132,135,139],"span",{"class":133,"line":134},"line",1,[131,136,138],{"class":137},"snPdu","mkdir",[131,140,142],{"class":141},"sIIMD"," .vitepress\u002Fgenerators\n",[10,144,145,146,149,150,152],{},"Create ",[14,147,148],{},"meta.ts"," in that folder. It will contain ",[14,151,86],{},".",[121,154,156],{"className":123,"code":155,"filename":125,"language":126,"meta":127,"style":127},"touch .vitepress\u002Fgenerators\u002Fmeta.ts\n",[14,157,158],{"__ignoreMap":127},[131,159,160,163],{"class":133,"line":134},[131,161,162],{"class":137},"touch",[131,164,165],{"class":141}," .vitepress\u002Fgenerators\u002Fmeta.ts\n",[10,167,168],{},"Finally, we can write our function:",[121,170,175],{"className":171,"code":172,"filename":173,"language":174,"meta":127,"style":127},"language-ts shiki shiki-themes github-light github-light github-dark","import type { ContentData, SiteConfig } from 'vitepress'\nimport { writeFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { createContentLoader } from 'vitepress'\n\nexport async function genMeta(config: SiteConfig) {\n  const posts = await createContentLoader('**\u002Fblog\u002F**\u002F*.md').load()\n\n  validatePosts(posts)\n\n  const meta = []\n\n  for (const item of posts) {\n    meta.push({\n      id: item.frontmatter.id,\n      title: item.frontmatter.title,\n    })\n  }\n\n  writeFileSync(path.join(config.outDir, 'meta.json'), JSON.stringify(meta.sort((a, b) => a.id - b.id), null, 2))\n}\n\nfunction validatePosts(items: ContentData[]) {\n  const ids = new Set\u003Cstring>()\n\n  for (const item of items) {\n    if (!item.frontmatter.id) {\n      throw new Error(`Id is missing: ${item.url}`)\n    }\n\n    if (ids.has(item.frontmatter.id)) {\n      throw new Error(`Id is not unique: ${item.frontmatter.id} (${item.url}) (${items.find(i => i.frontmatter.id === item.frontmatter.id)?.url})`)\n    }\n\n    ids.add(item.frontmatter.id)\n  }\n}\n",".vitepress\u002Fgenerators\u002Fmeta.ts","ts",[14,176,177,196,209,222,234,241,272,305,310,319,324,337,342,363,375,381,387,393,399,404,477,483,488,510,535,540,556,570,600,606,611,625,712,717,722,734,739],{"__ignoreMap":127},[131,178,179,183,186,190,193],{"class":133,"line":134},[131,180,182],{"class":181},"s8jYJ","import",[131,184,185],{"class":181}," type",[131,187,189],{"class":188},"sxrX7"," { ContentData, SiteConfig } ",[131,191,192],{"class":181},"from",[131,194,195],{"class":141}," 'vitepress'\n",[131,197,199,201,204,206],{"class":133,"line":198},2,[131,200,182],{"class":181},[131,202,203],{"class":188}," { writeFileSync } ",[131,205,192],{"class":181},[131,207,208],{"class":141}," 'node:fs'\n",[131,210,212,214,217,219],{"class":133,"line":211},3,[131,213,182],{"class":181},[131,215,216],{"class":188}," path ",[131,218,192],{"class":181},[131,220,221],{"class":141}," 'node:path'\n",[131,223,225,227,230,232],{"class":133,"line":224},4,[131,226,182],{"class":181},[131,228,229],{"class":188}," { createContentLoader } ",[131,231,192],{"class":181},[131,233,195],{"class":141},[131,235,237],{"class":133,"line":236},5,[131,238,240],{"emptyLinePlaceholder":239},true,"\n",[131,242,244,247,250,253,256,259,263,266,269],{"class":133,"line":243},6,[131,245,246],{"class":181},"export",[131,248,249],{"class":181}," async",[131,251,252],{"class":181}," function",[131,254,255],{"class":137}," genMeta",[131,257,258],{"class":188},"(",[131,260,262],{"class":261},"sP4rz","config",[131,264,265],{"class":181},":",[131,267,268],{"class":137}," SiteConfig",[131,270,271],{"class":188},") {\n",[131,273,275,278,282,285,288,291,293,296,299,302],{"class":133,"line":274},7,[131,276,277],{"class":181},"  const",[131,279,281],{"class":280},"sBjJW"," posts",[131,283,284],{"class":181}," =",[131,286,287],{"class":181}," await",[131,289,290],{"class":137}," createContentLoader",[131,292,258],{"class":188},[131,294,295],{"class":141},"'**\u002Fblog\u002F**\u002F*.md'",[131,297,298],{"class":188},").",[131,300,301],{"class":137},"load",[131,303,304],{"class":188},"()\n",[131,306,308],{"class":133,"line":307},8,[131,309,240],{"emptyLinePlaceholder":239},[131,311,313,316],{"class":133,"line":312},9,[131,314,315],{"class":137},"  validatePosts",[131,317,318],{"class":188},"(posts)\n",[131,320,322],{"class":133,"line":321},10,[131,323,240],{"emptyLinePlaceholder":239},[131,325,327,329,332,334],{"class":133,"line":326},11,[131,328,277],{"class":181},[131,330,331],{"class":280}," meta",[131,333,284],{"class":181},[131,335,336],{"class":188}," []\n",[131,338,340],{"class":133,"line":339},12,[131,341,240],{"emptyLinePlaceholder":239},[131,343,345,348,351,354,357,360],{"class":133,"line":344},13,[131,346,347],{"class":181},"  for",[131,349,350],{"class":188}," (",[131,352,353],{"class":181},"const",[131,355,356],{"class":280}," item",[131,358,359],{"class":181}," of",[131,361,362],{"class":188}," posts) {\n",[131,364,366,369,372],{"class":133,"line":365},14,[131,367,368],{"class":188},"    meta.",[131,370,371],{"class":137},"push",[131,373,374],{"class":188},"({\n",[131,376,378],{"class":133,"line":377},15,[131,379,380],{"class":188},"      id: item.frontmatter.id,\n",[131,382,384],{"class":133,"line":383},16,[131,385,386],{"class":188},"      title: item.frontmatter.title,\n",[131,388,390],{"class":133,"line":389},17,[131,391,392],{"class":188},"    })\n",[131,394,396],{"class":133,"line":395},18,[131,397,398],{"class":188},"  }\n",[131,400,402],{"class":133,"line":401},19,[131,403,240],{"emptyLinePlaceholder":239},[131,405,407,410,413,416,419,422,425,428,430,433,436,439,442,445,448,451,454,457,460,463,466,469,471,474],{"class":133,"line":406},20,[131,408,409],{"class":137},"  writeFileSync",[131,411,412],{"class":188},"(path.",[131,414,415],{"class":137},"join",[131,417,418],{"class":188},"(config.outDir, ",[131,420,421],{"class":141},"'meta.json'",[131,423,424],{"class":188},"), ",[131,426,427],{"class":280},"JSON",[131,429,152],{"class":188},[131,431,432],{"class":137},"stringify",[131,434,435],{"class":188},"(meta.",[131,437,438],{"class":137},"sort",[131,440,441],{"class":188},"((",[131,443,444],{"class":261},"a",[131,446,447],{"class":188},", ",[131,449,450],{"class":261},"b",[131,452,453],{"class":188},") ",[131,455,456],{"class":181},"=>",[131,458,459],{"class":188}," a.id ",[131,461,462],{"class":181},"-",[131,464,465],{"class":188}," b.id), ",[131,467,468],{"class":280},"null",[131,470,447],{"class":188},[131,472,473],{"class":280},"2",[131,475,476],{"class":188},"))\n",[131,478,480],{"class":133,"line":479},21,[131,481,482],{"class":188},"}\n",[131,484,486],{"class":133,"line":485},22,[131,487,240],{"emptyLinePlaceholder":239},[131,489,491,494,497,499,502,504,507],{"class":133,"line":490},23,[131,492,493],{"class":181},"function",[131,495,496],{"class":137}," validatePosts",[131,498,258],{"class":188},[131,500,501],{"class":261},"items",[131,503,265],{"class":181},[131,505,506],{"class":137}," ContentData",[131,508,509],{"class":188},"[]) {\n",[131,511,513,515,518,520,523,526,529,532],{"class":133,"line":512},24,[131,514,277],{"class":181},[131,516,517],{"class":280}," ids",[131,519,284],{"class":181},[131,521,522],{"class":181}," new",[131,524,525],{"class":137}," Set",[131,527,528],{"class":188},"\u003C",[131,530,531],{"class":280},"string",[131,533,534],{"class":188},">()\n",[131,536,538],{"class":133,"line":537},25,[131,539,240],{"emptyLinePlaceholder":239},[131,541,543,545,547,549,551,553],{"class":133,"line":542},26,[131,544,347],{"class":181},[131,546,350],{"class":188},[131,548,353],{"class":181},[131,550,356],{"class":280},[131,552,359],{"class":181},[131,554,555],{"class":188}," items) {\n",[131,557,559,562,564,567],{"class":133,"line":558},27,[131,560,561],{"class":181},"    if",[131,563,350],{"class":188},[131,565,566],{"class":181},"!",[131,568,569],{"class":188},"item.frontmatter.id) {\n",[131,571,573,576,578,581,583,586,589,591,594,597],{"class":133,"line":572},28,[131,574,575],{"class":181},"      throw",[131,577,522],{"class":181},[131,579,580],{"class":137}," Error",[131,582,258],{"class":188},[131,584,585],{"class":141},"`Id is missing: ${",[131,587,588],{"class":188},"item",[131,590,152],{"class":141},[131,592,593],{"class":188},"url",[131,595,596],{"class":141},"}`",[131,598,599],{"class":188},")\n",[131,601,603],{"class":133,"line":602},29,[131,604,605],{"class":188},"    }\n",[131,607,609],{"class":133,"line":608},30,[131,610,240],{"emptyLinePlaceholder":239},[131,612,614,616,619,622],{"class":133,"line":613},31,[131,615,561],{"class":181},[131,617,618],{"class":188}," (ids.",[131,620,621],{"class":137},"has",[131,623,624],{"class":188},"(item.frontmatter.id)) {\n",[131,626,628,630,632,634,636,639,641,643,646,648,651,654,656,658,660,663,665,667,670,672,675,678,681,683,685,687,689,692,694,696,698,700,702,705,707,710],{"class":133,"line":627},32,[131,629,575],{"class":181},[131,631,522],{"class":181},[131,633,580],{"class":137},[131,635,258],{"class":188},[131,637,638],{"class":141},"`Id is not unique: ${",[131,640,588],{"class":188},[131,642,152],{"class":141},[131,644,645],{"class":188},"frontmatter",[131,647,152],{"class":141},[131,649,650],{"class":188},"id",[131,652,653],{"class":141},"} (${",[131,655,588],{"class":188},[131,657,152],{"class":141},[131,659,593],{"class":188},[131,661,662],{"class":141},"}) (${",[131,664,501],{"class":188},[131,666,152],{"class":141},[131,668,669],{"class":137},"find",[131,671,258],{"class":141},[131,673,674],{"class":280},"i",[131,676,677],{"class":181}," =>",[131,679,680],{"class":188}," i",[131,682,152],{"class":141},[131,684,645],{"class":188},[131,686,152],{"class":141},[131,688,650],{"class":188},[131,690,691],{"class":181}," ===",[131,693,356],{"class":188},[131,695,152],{"class":141},[131,697,645],{"class":188},[131,699,152],{"class":141},[131,701,650],{"class":188},[131,703,704],{"class":141},")?.",[131,706,593],{"class":188},[131,708,709],{"class":141},"})`",[131,711,599],{"class":188},[131,713,715],{"class":133,"line":714},33,[131,716,605],{"class":188},[131,718,720],{"class":133,"line":719},34,[131,721,240],{"emptyLinePlaceholder":239},[131,723,725,728,731],{"class":133,"line":724},35,[131,726,727],{"class":188},"    ids.",[131,729,730],{"class":137},"add",[131,732,733],{"class":188},"(item.frontmatter.id)\n",[131,735,737],{"class":133,"line":736},36,[131,738,398],{"class":188},[131,740,742],{"class":133,"line":741},37,[131,743,482],{"class":188},[10,745,746,747,750],{},"The script has three steps. First, ",[14,748,749],{},"createContentLoader"," reads the Markdown files and parses their frontmatter. Next, we verify that every post has an ID and that IDs are unique. This matters because a post without an ID cannot participate in the comment system, while duplicate IDs would make two posts share comments. The validation throws an error and stops the build in either case.",[10,752,753,754,152],{},"We then create an array containing each post's ID and title and write it to ",[14,755,90],{},[10,757,758,759,761,762,764,765,265],{},"To run it, add ",[14,760,86],{}," to the ",[14,763,94],{}," hook in ",[14,766,767],{},".vitepress\u002Fconfig.ts",[121,769,771],{"className":171,"code":770,"filename":767,"language":174,"meta":127,"style":127},"import { defineConfig } from 'vitepress'\nimport { genMeta } from '.\u002Fgenerators\u002Fmeta'\n\nexport default defineConfig({\n  \u002F\u002F ...\n\n  buildEnd: async (config) => {\n    await genMeta(config)\n  },\n})\n",[14,772,773,784,796,800,812,818,822,844,854,859],{"__ignoreMap":127},[131,774,775,777,780,782],{"class":133,"line":134},[131,776,182],{"class":181},[131,778,779],{"class":188}," { defineConfig } ",[131,781,192],{"class":181},[131,783,195],{"class":141},[131,785,786,788,791,793],{"class":133,"line":198},[131,787,182],{"class":181},[131,789,790],{"class":188}," { genMeta } ",[131,792,192],{"class":181},[131,794,795],{"class":141}," '.\u002Fgenerators\u002Fmeta'\n",[131,797,798],{"class":133,"line":211},[131,799,240],{"emptyLinePlaceholder":239},[131,801,802,804,807,810],{"class":133,"line":224},[131,803,246],{"class":181},[131,805,806],{"class":181}," default",[131,808,809],{"class":137}," defineConfig",[131,811,374],{"class":188},[131,813,814],{"class":133,"line":236},[131,815,817],{"class":816},"sCsY4","  \u002F\u002F ...\n",[131,819,820],{"class":133,"line":243},[131,821,240],{"emptyLinePlaceholder":239},[131,823,824,827,830,833,835,837,839,841],{"class":133,"line":274},[131,825,826],{"class":137},"  buildEnd",[131,828,829],{"class":188},": ",[131,831,832],{"class":181},"async",[131,834,350],{"class":188},[131,836,262],{"class":261},[131,838,453],{"class":188},[131,840,456],{"class":181},[131,842,843],{"class":188}," {\n",[131,845,846,849,851],{"class":133,"line":307},[131,847,848],{"class":181},"    await",[131,850,255],{"class":137},[131,852,853],{"class":188},"(config)\n",[131,855,856],{"class":133,"line":312},[131,857,858],{"class":188},"  },\n",[131,860,861],{"class":133,"line":321},[131,862,863],{"class":188},"})\n",[10,865,866],{},"Finally, add a unique ID to each post:",[121,868,873],{"className":869,"code":870,"filename":871,"language":872,"meta":127,"style":127},"language-md shiki shiki-themes github-light github-light github-dark","---\nid: 1 [!code ++]\ntitle: Getting Started with Laravel\ndescription:\ndate: 2024-10-14\n---\n","src\u002Fblog\u002Fgetting-started-with-laravel.md","md",[14,874,875,880,890,900,908,918],{"__ignoreMap":127},[131,876,877],{"class":133,"line":134},[131,878,879],{"class":188},"---\n",[131,881,882,885,887],{"class":133,"line":198},[131,883,650],{"class":884},"sovSZ",[131,886,829],{"class":188},[131,888,889],{"class":141},"1 [!code ++]\n",[131,891,892,895,897],{"class":133,"line":211},[131,893,894],{"class":884},"title",[131,896,829],{"class":188},[131,898,899],{"class":141},"Getting Started with Laravel\n",[131,901,902,905],{"class":133,"line":224},[131,903,904],{"class":884},"description",[131,906,907],{"class":188},":\n",[131,909,910,913,915],{"class":133,"line":236},[131,911,912],{"class":884},"date",[131,914,829],{"class":188},[131,916,917],{"class":280},"2024-10-14\n",[131,919,920],{"class":133,"line":243},[131,921,879],{"class":188},[121,923,926],{"className":869,"code":924,"filename":925,"language":872,"meta":127,"style":127},"---\nid: 2\ntitle: Getting Started with Vue 3 and Vite\ndescription:\ndate: 2024-09-14\n---\n","src\u002Fblog\u002Fgetting-started-with-vue-3-and-vite.md",[14,927,928,932,941,950,956,965],{"__ignoreMap":127},[131,929,930],{"class":133,"line":134},[131,931,879],{"class":188},[131,933,934,936,938],{"class":133,"line":198},[131,935,650],{"class":884},[131,937,829],{"class":188},[131,939,940],{"class":280},"2\n",[131,942,943,945,947],{"class":133,"line":211},[131,944,894],{"class":884},[131,946,829],{"class":188},[131,948,949],{"class":141},"Getting Started with Vue 3 and Vite\n",[131,951,952,954],{"class":133,"line":224},[131,953,904],{"class":884},[131,955,907],{"class":188},[131,957,958,960,962],{"class":133,"line":236},[131,959,912],{"class":884},[131,961,829],{"class":188},[131,963,964],{"class":280},"2024-09-14\n",[131,966,967],{"class":133,"line":243},[131,968,879],{"class":188},[10,970,971,972,974,975,978],{},"When we build the frontend, VitePress will create ",[14,973,61],{}," in ",[14,976,977],{},"dist",". It will contain each post's ID and title. Check it with:",[121,980,982],{"className":123,"code":981,"filename":125,"language":126,"meta":127,"style":127},"npm run build\n",[14,983,984],{"__ignoreMap":127},[131,985,986,989,992],{"class":133,"line":134},[131,987,988],{"class":137},"npm",[131,990,991],{"class":141}," run",[131,993,994],{"class":141}," build\n",[121,996,998],{"className":123,"code":997,"filename":125,"language":126,"meta":127,"style":127},"cat .vitepress\u002Fdist\u002Fmeta.json\n",[14,999,1000],{"__ignoreMap":127},[131,1001,1002,1005],{"class":133,"line":134},[131,1003,1004],{"class":137},"cat",[131,1006,1007],{"class":141}," .vitepress\u002Fdist\u002Fmeta.json\n",[10,1009,1010],{},"The output should look similar to this:",[121,1012,1017],{"className":1013,"code":1014,"filename":1015,"language":1016,"meta":127,"style":127},"language-json shiki shiki-themes github-light github-light github-dark","[\n  {\n    \"id\": 1,\n    \"title\": \"Getting Started with Laravel\"\n  },\n  {\n    \"id\": 2,\n    \"title\": \"Getting Started with Vue 3 and Vite\"\n  }\n]\n",".vitepress\u002Fdist\u002Fmeta.json","json",[14,1018,1019,1024,1029,1042,1052,1056,1060,1070,1079,1083],{"__ignoreMap":127},[131,1020,1021],{"class":133,"line":134},[131,1022,1023],{"class":188},"[\n",[131,1025,1026],{"class":133,"line":198},[131,1027,1028],{"class":188},"  {\n",[131,1030,1031,1034,1036,1039],{"class":133,"line":211},[131,1032,1033],{"class":280},"    \"id\"",[131,1035,829],{"class":188},[131,1037,1038],{"class":280},"1",[131,1040,1041],{"class":188},",\n",[131,1043,1044,1047,1049],{"class":133,"line":224},[131,1045,1046],{"class":280},"    \"title\"",[131,1048,829],{"class":188},[131,1050,1051],{"class":141},"\"Getting Started with Laravel\"\n",[131,1053,1054],{"class":133,"line":236},[131,1055,858],{"class":188},[131,1057,1058],{"class":133,"line":243},[131,1059,1028],{"class":188},[131,1061,1062,1064,1066,1068],{"class":133,"line":274},[131,1063,1033],{"class":280},[131,1065,829],{"class":188},[131,1067,473],{"class":280},[131,1069,1041],{"class":188},[131,1071,1072,1074,1076],{"class":133,"line":307},[131,1073,1046],{"class":280},[131,1075,829],{"class":188},[131,1077,1078],{"class":141},"\"Getting Started with Vue 3 and Vite\"\n",[131,1080,1081],{"class":133,"line":312},[131,1082,398],{"class":188},[131,1084,1085],{"class":133,"line":321},[131,1086,1087],{"class":188},"]\n",[10,1089,1090],{},"If you see this file, the frontend half of the synchronization is complete.",[71,1092,1094],{"id":1093},"retrieving-the-posts-from-the-backend","Retrieving the posts from the backend",[10,1096,1097,1098,1101,1102,1104],{},"Next, the backend needs to read this file and synchronize the database. We will create an ",[14,1099,1100],{},"app:posts-sync"," command that fetches and parses ",[14,1103,61],{},", then inserts or updates each post.",[111,1106,1107],{"color":113,"icon":114},[10,1108,1109,1110,1112],{},"The ",[14,1111,894],{}," column is not used by the frontend or the API, but it makes database records easier to identify and can be useful in an admin panel.",[10,1114,1115],{},"Create the command with Artisan:",[121,1117,1119],{"className":123,"code":1118,"filename":125,"language":126,"meta":127,"style":127},"php artisan make:command PostsSync\n",[14,1120,1121],{"__ignoreMap":127},[131,1122,1123,1126,1129,1132],{"class":133,"line":134},[131,1124,1125],{"class":137},"php",[131,1127,1128],{"class":141}," artisan",[131,1130,1131],{"class":141}," make:command",[131,1133,1134],{"class":141}," PostsSync\n",[10,1136,1137,1138,1141],{},"The command will be created in ",[14,1139,1140],{},"app\u002FConsole\u002FCommands",". Its job is simple:",[34,1143,1144,1150],{},[37,1145,1146,1147,1149],{},"Fetch the ",[14,1148,61],{}," file from the frontend",[37,1151,1152],{},"Insert (or update) each post in the database",[10,1154,1155],{},"Here is the implementation:",[121,1157,1161],{"className":1158,"code":1159,"filename":1160,"language":1125,"meta":127,"style":127},"language-php shiki shiki-themes github-light github-light github-dark","\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Console\\Commands;\n\nuse App\\Models\\Post;\nuse Illuminate\\Console\\Command;\nuse Illuminate\\Support\\Facades\\Config;\nuse Illuminate\\Support\\Facades\\Http;\n\nfinal class PostsSync extends Command\n{\n    \u002F**\n     * The name and signature of the console command.\n     *\n     * @var string\n     *\u002F\n    protected $signature = 'app:posts-sync';\n\n    \u002F**\n     * The console command description.\n     *\n     * @var string\n     *\u002F\n    protected $description = 'Synchronize backend posts with the frontend through the `meta.json` file.';\n\n    \u002F**\n     * Execute the console command.\n     *\u002F\n    public function handle(): void\n    {\n        \u002F**\n         * @var array\u003Carray\u003Cstring, int|string>>\n         *\u002F\n        $response = Http::get(Config::get('app.frontend_url').'\u002Fmeta.json')\n            ->json();\n\n        $meta = collect($response)->map(\n            fn (array $post): array => [\n                'meta_id' => $post['id'],\n                'title' => $post['title'],\n            ]\n        )->toArray();\n\n        Post::upsert($meta, uniqueBy: ['meta_id'], update: ['title']);\n    }\n}\n","app\u002FConsole\u002FCommands\u002FPostsSync.php",[14,1162,1163,1168,1172,1177,1181,1186,1190,1195,1200,1205,1210,1214,1219,1224,1229,1234,1239,1244,1249,1254,1258,1262,1267,1271,1275,1279,1284,1288,1292,1297,1301,1306,1311,1316,1321,1326,1331,1336,1341,1347,1353,1359,1365,1371,1377,1382,1388,1393],{"__ignoreMap":127},[131,1164,1165],{"class":133,"line":134},[131,1166,1167],{},"\u003C?php\n",[131,1169,1170],{"class":133,"line":198},[131,1171,240],{"emptyLinePlaceholder":239},[131,1173,1174],{"class":133,"line":211},[131,1175,1176],{},"declare(strict_types=1);\n",[131,1178,1179],{"class":133,"line":224},[131,1180,240],{"emptyLinePlaceholder":239},[131,1182,1183],{"class":133,"line":236},[131,1184,1185],{},"namespace App\\Console\\Commands;\n",[131,1187,1188],{"class":133,"line":243},[131,1189,240],{"emptyLinePlaceholder":239},[131,1191,1192],{"class":133,"line":274},[131,1193,1194],{},"use App\\Models\\Post;\n",[131,1196,1197],{"class":133,"line":307},[131,1198,1199],{},"use Illuminate\\Console\\Command;\n",[131,1201,1202],{"class":133,"line":312},[131,1203,1204],{},"use Illuminate\\Support\\Facades\\Config;\n",[131,1206,1207],{"class":133,"line":321},[131,1208,1209],{},"use Illuminate\\Support\\Facades\\Http;\n",[131,1211,1212],{"class":133,"line":326},[131,1213,240],{"emptyLinePlaceholder":239},[131,1215,1216],{"class":133,"line":339},[131,1217,1218],{},"final class PostsSync extends Command\n",[131,1220,1221],{"class":133,"line":344},[131,1222,1223],{},"{\n",[131,1225,1226],{"class":133,"line":365},[131,1227,1228],{},"    \u002F**\n",[131,1230,1231],{"class":133,"line":377},[131,1232,1233],{},"     * The name and signature of the console command.\n",[131,1235,1236],{"class":133,"line":383},[131,1237,1238],{},"     *\n",[131,1240,1241],{"class":133,"line":389},[131,1242,1243],{},"     * @var string\n",[131,1245,1246],{"class":133,"line":395},[131,1247,1248],{},"     *\u002F\n",[131,1250,1251],{"class":133,"line":401},[131,1252,1253],{},"    protected $signature = 'app:posts-sync';\n",[131,1255,1256],{"class":133,"line":406},[131,1257,240],{"emptyLinePlaceholder":239},[131,1259,1260],{"class":133,"line":479},[131,1261,1228],{},[131,1263,1264],{"class":133,"line":485},[131,1265,1266],{},"     * The console command description.\n",[131,1268,1269],{"class":133,"line":490},[131,1270,1238],{},[131,1272,1273],{"class":133,"line":512},[131,1274,1243],{},[131,1276,1277],{"class":133,"line":537},[131,1278,1248],{},[131,1280,1281],{"class":133,"line":542},[131,1282,1283],{},"    protected $description = 'Synchronize backend posts with the frontend through the `meta.json` file.';\n",[131,1285,1286],{"class":133,"line":558},[131,1287,240],{"emptyLinePlaceholder":239},[131,1289,1290],{"class":133,"line":572},[131,1291,1228],{},[131,1293,1294],{"class":133,"line":602},[131,1295,1296],{},"     * Execute the console command.\n",[131,1298,1299],{"class":133,"line":608},[131,1300,1248],{},[131,1302,1303],{"class":133,"line":613},[131,1304,1305],{},"    public function handle(): void\n",[131,1307,1308],{"class":133,"line":627},[131,1309,1310],{},"    {\n",[131,1312,1313],{"class":133,"line":714},[131,1314,1315],{},"        \u002F**\n",[131,1317,1318],{"class":133,"line":719},[131,1319,1320],{},"         * @var array\u003Carray\u003Cstring, int|string>>\n",[131,1322,1323],{"class":133,"line":724},[131,1324,1325],{},"         *\u002F\n",[131,1327,1328],{"class":133,"line":736},[131,1329,1330],{},"        $response = Http::get(Config::get('app.frontend_url').'\u002Fmeta.json')\n",[131,1332,1333],{"class":133,"line":741},[131,1334,1335],{},"            ->json();\n",[131,1337,1339],{"class":133,"line":1338},38,[131,1340,240],{"emptyLinePlaceholder":239},[131,1342,1344],{"class":133,"line":1343},39,[131,1345,1346],{},"        $meta = collect($response)->map(\n",[131,1348,1350],{"class":133,"line":1349},40,[131,1351,1352],{},"            fn (array $post): array => [\n",[131,1354,1356],{"class":133,"line":1355},41,[131,1357,1358],{},"                'meta_id' => $post['id'],\n",[131,1360,1362],{"class":133,"line":1361},42,[131,1363,1364],{},"                'title' => $post['title'],\n",[131,1366,1368],{"class":133,"line":1367},43,[131,1369,1370],{},"            ]\n",[131,1372,1374],{"class":133,"line":1373},44,[131,1375,1376],{},"        )->toArray();\n",[131,1378,1380],{"class":133,"line":1379},45,[131,1381,240],{"emptyLinePlaceholder":239},[131,1383,1385],{"class":133,"line":1384},46,[131,1386,1387],{},"        Post::upsert($meta, uniqueBy: ['meta_id'], update: ['title']);\n",[131,1389,1391],{"class":133,"line":1390},47,[131,1392,605],{},[131,1394,1396],{"class":133,"line":1395},48,[131,1397,482],{},[10,1399,1109,1400,1408,1409,1411],{},[444,1401,1405],{"href":1402,"rel":1403},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Feloquent#upserts",[1404],"nofollow",[14,1406,1407],{},"upsert"," method handles both cases. It inserts records that do not exist, using the unique ",[14,1410,20],{}," key, and updates the title of an existing record.",[10,1413,1414,1415,1418,1419,1422,1423,1426,1427,1430,1431,152],{},"The command must work in both local and production environments. Locally, the frontend may be served from ",[14,1416,1417],{},"localhost:5173"," or ",[14,1420,1421],{},"localhost:4173"," during a preview. In production, it is served from a public URL. We solve that difference with the ",[14,1424,1425],{},"APP_FRONTEND_URL"," environment variable, exposed through the ",[14,1428,1429],{},"frontend_url"," key in ",[14,1432,1433],{},"config\u002Fapp.php",[121,1435,1440],{"className":1436,"code":1437,"filename":1438,"language":1439,"meta":127,"style":127},"language-ini shiki shiki-themes github-light github-light github-dark","APP_FRONTEND_URL=http:\u002F\u002Flocalhost:4173\n",".env.example","ini",[14,1441,1442],{"__ignoreMap":127},[131,1443,1444],{"class":133,"line":134},[131,1445,1437],{},[121,1447,1449],{"className":1158,"code":1448,"filename":1433,"language":1125,"meta":127,"style":127},"return [\n    \u002F\u002F ...\n\n    'frontend_url' => env('APP_FRONTEND_URL', 'http:\u002F\u002Flocalhost:4173'),\n\n    \u002F\u002F ...\n];\n",[14,1450,1451,1456,1461,1465,1470,1474,1478],{"__ignoreMap":127},[131,1452,1453],{"class":133,"line":134},[131,1454,1455],{},"return [\n",[131,1457,1458],{"class":133,"line":198},[131,1459,1460],{},"    \u002F\u002F ...\n",[131,1462,1463],{"class":133,"line":211},[131,1464,240],{"emptyLinePlaceholder":239},[131,1466,1467],{"class":133,"line":224},[131,1468,1469],{},"    'frontend_url' => env('APP_FRONTEND_URL', 'http:\u002F\u002Flocalhost:4173'),\n",[131,1471,1472],{"class":133,"line":236},[131,1473,240],{"emptyLinePlaceholder":239},[131,1475,1476],{"class":133,"line":243},[131,1477,1460],{},[131,1479,1480],{"class":133,"line":274},[131,1481,1482],{},"];\n",[10,1484,1485],{},"The code is then identical in both environments; only the environment variable changes.",[10,1487,1488],{},"During development, start the frontend preview server:",[121,1490,1492],{"className":123,"code":1491,"filename":125,"language":126,"meta":127,"style":127},"npm run build && npm run preview\n",[14,1493,1494],{"__ignoreMap":127},[131,1495,1496,1498,1500,1503,1506,1508,1510],{"class":133,"line":134},[131,1497,988],{"class":137},[131,1499,991],{"class":141},[131,1501,1502],{"class":141}," build",[131,1504,1505],{"class":188}," && ",[131,1507,988],{"class":137},[131,1509,991],{"class":141},[131,1511,1512],{"class":141}," preview\n",[10,1514,1515],{},"Then run the synchronization command:",[121,1517,1519],{"className":123,"code":1518,"filename":125,"language":126,"meta":127,"style":127},"php artisan app:posts-sync\n",[14,1520,1521],{"__ignoreMap":127},[131,1522,1523,1525,1527],{"class":133,"line":134},[131,1524,1125],{"class":137},[131,1526,1128],{"class":141},[131,1528,1529],{"class":141}," app:posts-sync\n",[111,1531,1532],{"color":113,"icon":114},[10,1533,1534,1535,974,1537,1540],{},"Set the correct ",[14,1536,1425],{},[14,1538,1539],{},".env"," before running the command.",[10,1542,1543,1544,1547,1548,1550],{},"If you see ",[14,1545,1546],{},"SQLSTATE[HY000]: General error: 1 no such table: posts",", the ",[14,1549,16],{}," table has not been created yet. Run:",[121,1552,1554],{"className":123,"code":1553,"filename":125,"language":126,"meta":127,"style":127},"php artisan migrate\n",[14,1555,1556],{"__ignoreMap":127},[131,1557,1558,1560,1562],{"class":133,"line":134},[131,1559,1125],{"class":137},[131,1561,1128],{"class":141},[131,1563,1564],{"class":141}," migrate\n",[10,1566,1567],{},"You can now run the synchronization command repeatedly without creating duplicate records.",[1569,1570,1572],"h3",{"id":1571},"testing-the-command","Testing the command",[10,1574,1575,1576,1579],{},"The command is part of our application and we have to test it. To do this, we will mock the ",[14,1577,1578],{},"Http"," facade. This way, we can test the command without relying on the network. This is one of the rare cases where mocking is useful.",[10,1581,1582,1583,1590,1591,1593],{},"To mock the HTTP client, use ",[444,1584,1587],{"href":1585,"rel":1586},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fhttp-client#testing",[1404],[14,1588,1589],{},"Http::fake",". It lets the test provide a predictable ",[14,1592,61],{}," response without relying on the network.",[121,1595,1598],{"className":1158,"code":1596,"filename":1597,"language":1125,"meta":127,"style":127},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse Illuminate\\Support\\Facades\\Config;\nuse Illuminate\\Support\\Facades\\Http;\n\nit('fetches posts meta', function () {\n    Http::fake([\n        Config::get('app.frontend_url').'\u002Fmeta.json' => Http::response([\n            [\n                'id' => 1,\n                'title' => 'Post 1',\n            ],\n            [\n                'id' => 2,\n                'title' => 'Post 2',\n            ],\n        ], 200),\n    ]);\n\n    $this->artisan('app:posts-sync')\n        ->assertExitCode(0);\n\n    Http::assertSentCount(1);\n\n    $this->assertDatabaseCount('posts', 2);\n    $this->assertDatabaseHas('posts', [\n        'meta_id' => 1,\n        'title' => 'Post 1',\n    ]);\n});\n\nit('does not insert duplicates', function () {\n    Http::fake([\n        Config::get('app.frontend_url').'\u002Fmeta.json' => Http::response([\n            [\n                'id' => 1,\n                'title' => 'Post 1',\n            ],\n            [\n                'id' => 1,\n                'title' => 'Post 1',\n            ],\n        ], 200),\n    ]);\n\n    $this->artisan('app:posts-sync')\n        ->assertExitCode(0);\n\n    Http::assertSentCount(1);\n\n    $this->assertDatabaseCount('posts', 1);\n    $this->assertDatabaseHas('posts', [\n        'meta_id' => 1,\n        'title' => 'Post 1',\n    ]);\n});\n\nit('updates the data based on the id', function () {\n    Http::fake([\n        Config::get('app.frontend_url').'\u002Fmeta.json' => Http::response([\n            [\n                'id' => 1,\n                'title' => 'Post 1',\n            ],\n            [\n                'id' => 1,\n                'title' => 'Post 1 Updated',\n            ],\n        ], 200),\n    ]);\n\n    $this->artisan('app:posts-sync')\n        ->assertExitCode(0);\n\n    Http::assertSentCount(1);\n\n    $this->assertDatabaseCount('posts', 1);\n    $this->assertDatabaseHas('posts', [\n        'meta_id' => 1,\n        'title' => 'Post 1 Updated',\n    ]);\n});\n","tests\u002FConsole\u002FPostsSyncTest.php",[14,1599,1600,1604,1608,1612,1616,1620,1624,1628,1633,1638,1643,1648,1653,1658,1663,1667,1672,1677,1681,1686,1691,1695,1700,1705,1709,1714,1718,1723,1728,1733,1738,1742,1747,1751,1756,1760,1764,1768,1772,1776,1780,1784,1788,1792,1796,1800,1804,1808,1812,1817,1822,1827,1832,1838,1843,1848,1853,1858,1863,1868,1874,1879,1884,1889,1894,1899,1904,1909,1914,1920,1925,1930,1935,1940,1945,1950,1955,1960,1965,1970,1975,1980,1986,1991],{"__ignoreMap":127},[131,1601,1602],{"class":133,"line":134},[131,1603,1167],{},[131,1605,1606],{"class":133,"line":198},[131,1607,240],{"emptyLinePlaceholder":239},[131,1609,1610],{"class":133,"line":211},[131,1611,1176],{},[131,1613,1614],{"class":133,"line":224},[131,1615,240],{"emptyLinePlaceholder":239},[131,1617,1618],{"class":133,"line":236},[131,1619,1204],{},[131,1621,1622],{"class":133,"line":243},[131,1623,1209],{},[131,1625,1626],{"class":133,"line":274},[131,1627,240],{"emptyLinePlaceholder":239},[131,1629,1630],{"class":133,"line":307},[131,1631,1632],{},"it('fetches posts meta', function () {\n",[131,1634,1635],{"class":133,"line":312},[131,1636,1637],{},"    Http::fake([\n",[131,1639,1640],{"class":133,"line":321},[131,1641,1642],{},"        Config::get('app.frontend_url').'\u002Fmeta.json' => Http::response([\n",[131,1644,1645],{"class":133,"line":326},[131,1646,1647],{},"            [\n",[131,1649,1650],{"class":133,"line":339},[131,1651,1652],{},"                'id' => 1,\n",[131,1654,1655],{"class":133,"line":344},[131,1656,1657],{},"                'title' => 'Post 1',\n",[131,1659,1660],{"class":133,"line":365},[131,1661,1662],{},"            ],\n",[131,1664,1665],{"class":133,"line":377},[131,1666,1647],{},[131,1668,1669],{"class":133,"line":383},[131,1670,1671],{},"                'id' => 2,\n",[131,1673,1674],{"class":133,"line":389},[131,1675,1676],{},"                'title' => 'Post 2',\n",[131,1678,1679],{"class":133,"line":395},[131,1680,1662],{},[131,1682,1683],{"class":133,"line":401},[131,1684,1685],{},"        ], 200),\n",[131,1687,1688],{"class":133,"line":406},[131,1689,1690],{},"    ]);\n",[131,1692,1693],{"class":133,"line":479},[131,1694,240],{"emptyLinePlaceholder":239},[131,1696,1697],{"class":133,"line":485},[131,1698,1699],{},"    $this->artisan('app:posts-sync')\n",[131,1701,1702],{"class":133,"line":490},[131,1703,1704],{},"        ->assertExitCode(0);\n",[131,1706,1707],{"class":133,"line":512},[131,1708,240],{"emptyLinePlaceholder":239},[131,1710,1711],{"class":133,"line":537},[131,1712,1713],{},"    Http::assertSentCount(1);\n",[131,1715,1716],{"class":133,"line":542},[131,1717,240],{"emptyLinePlaceholder":239},[131,1719,1720],{"class":133,"line":558},[131,1721,1722],{},"    $this->assertDatabaseCount('posts', 2);\n",[131,1724,1725],{"class":133,"line":572},[131,1726,1727],{},"    $this->assertDatabaseHas('posts', [\n",[131,1729,1730],{"class":133,"line":602},[131,1731,1732],{},"        'meta_id' => 1,\n",[131,1734,1735],{"class":133,"line":608},[131,1736,1737],{},"        'title' => 'Post 1',\n",[131,1739,1740],{"class":133,"line":613},[131,1741,1690],{},[131,1743,1744],{"class":133,"line":627},[131,1745,1746],{},"});\n",[131,1748,1749],{"class":133,"line":714},[131,1750,240],{"emptyLinePlaceholder":239},[131,1752,1753],{"class":133,"line":719},[131,1754,1755],{},"it('does not insert duplicates', function () {\n",[131,1757,1758],{"class":133,"line":724},[131,1759,1637],{},[131,1761,1762],{"class":133,"line":736},[131,1763,1642],{},[131,1765,1766],{"class":133,"line":741},[131,1767,1647],{},[131,1769,1770],{"class":133,"line":1338},[131,1771,1652],{},[131,1773,1774],{"class":133,"line":1343},[131,1775,1657],{},[131,1777,1778],{"class":133,"line":1349},[131,1779,1662],{},[131,1781,1782],{"class":133,"line":1355},[131,1783,1647],{},[131,1785,1786],{"class":133,"line":1361},[131,1787,1652],{},[131,1789,1790],{"class":133,"line":1367},[131,1791,1657],{},[131,1793,1794],{"class":133,"line":1373},[131,1795,1662],{},[131,1797,1798],{"class":133,"line":1379},[131,1799,1685],{},[131,1801,1802],{"class":133,"line":1384},[131,1803,1690],{},[131,1805,1806],{"class":133,"line":1390},[131,1807,240],{"emptyLinePlaceholder":239},[131,1809,1810],{"class":133,"line":1395},[131,1811,1699],{},[131,1813,1815],{"class":133,"line":1814},49,[131,1816,1704],{},[131,1818,1820],{"class":133,"line":1819},50,[131,1821,240],{"emptyLinePlaceholder":239},[131,1823,1825],{"class":133,"line":1824},51,[131,1826,1713],{},[131,1828,1830],{"class":133,"line":1829},52,[131,1831,240],{"emptyLinePlaceholder":239},[131,1833,1835],{"class":133,"line":1834},53,[131,1836,1837],{},"    $this->assertDatabaseCount('posts', 1);\n",[131,1839,1841],{"class":133,"line":1840},54,[131,1842,1727],{},[131,1844,1846],{"class":133,"line":1845},55,[131,1847,1732],{},[131,1849,1851],{"class":133,"line":1850},56,[131,1852,1737],{},[131,1854,1856],{"class":133,"line":1855},57,[131,1857,1690],{},[131,1859,1861],{"class":133,"line":1860},58,[131,1862,1746],{},[131,1864,1866],{"class":133,"line":1865},59,[131,1867,240],{"emptyLinePlaceholder":239},[131,1869,1871],{"class":133,"line":1870},60,[131,1872,1873],{},"it('updates the data based on the id', function () {\n",[131,1875,1877],{"class":133,"line":1876},61,[131,1878,1637],{},[131,1880,1882],{"class":133,"line":1881},62,[131,1883,1642],{},[131,1885,1887],{"class":133,"line":1886},63,[131,1888,1647],{},[131,1890,1892],{"class":133,"line":1891},64,[131,1893,1652],{},[131,1895,1897],{"class":133,"line":1896},65,[131,1898,1657],{},[131,1900,1902],{"class":133,"line":1901},66,[131,1903,1662],{},[131,1905,1907],{"class":133,"line":1906},67,[131,1908,1647],{},[131,1910,1912],{"class":133,"line":1911},68,[131,1913,1652],{},[131,1915,1917],{"class":133,"line":1916},69,[131,1918,1919],{},"                'title' => 'Post 1 Updated',\n",[131,1921,1923],{"class":133,"line":1922},70,[131,1924,1662],{},[131,1926,1928],{"class":133,"line":1927},71,[131,1929,1685],{},[131,1931,1933],{"class":133,"line":1932},72,[131,1934,1690],{},[131,1936,1938],{"class":133,"line":1937},73,[131,1939,240],{"emptyLinePlaceholder":239},[131,1941,1943],{"class":133,"line":1942},74,[131,1944,1699],{},[131,1946,1948],{"class":133,"line":1947},75,[131,1949,1704],{},[131,1951,1953],{"class":133,"line":1952},76,[131,1954,240],{"emptyLinePlaceholder":239},[131,1956,1958],{"class":133,"line":1957},77,[131,1959,1713],{},[131,1961,1963],{"class":133,"line":1962},78,[131,1964,240],{"emptyLinePlaceholder":239},[131,1966,1968],{"class":133,"line":1967},79,[131,1969,1837],{},[131,1971,1973],{"class":133,"line":1972},80,[131,1974,1727],{},[131,1976,1978],{"class":133,"line":1977},81,[131,1979,1732],{},[131,1981,1983],{"class":133,"line":1982},82,[131,1984,1985],{},"        'title' => 'Post 1 Updated',\n",[131,1987,1989],{"class":133,"line":1988},83,[131,1990,1690],{},[131,1992,1994],{"class":133,"line":1993},84,[131,1995,1746],{},[10,1997,1998,1999,2002,2003,2006],{},"The command tests live in a new ",[14,2000,2001],{},"Console"," folder. Add that folder to ",[14,2004,2005],{},"phpunit.xml"," so PHPUnit discovers them:",[121,2008,2012],{"className":2009,"code":2010,"filename":2005,"language":2011,"meta":127,"style":127},"language-xml shiki shiki-themes github-light github-light github-dark","\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\u003Cphpunit xmlns:xsi=\"http:\u002F\u002Fwww.w3.org\u002F2001\u002FXMLSchema-instance\"\n         xsi:noNamespaceSchemaLocation=\"vendor\u002Fphpunit\u002Fphpunit\u002Fphpunit.xsd\"\n         bootstrap=\"vendor\u002Fautoload.php\"\n         colors=\"true\"\n>\n    \u003Ctestsuites>\n        \u003Ctestsuite name=\"Console\"> \u003C!-- [!code ++] -->\n            \u003Cdirectory>tests\u002FConsole\u003C\u002Fdirectory> \u003C!-- [!code ++] -->\n        \u003C\u002Ftestsuite> \u003C!-- [!code ++] -->\n    \u003C\u002Ftestsuites>\n\u003C\u002Fphpunit>\n","xml",[14,2013,2014,2019,2024,2029,2034,2039,2044,2049,2054,2059,2064,2069],{"__ignoreMap":127},[131,2015,2016],{"class":133,"line":134},[131,2017,2018],{},"\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",[131,2020,2021],{"class":133,"line":198},[131,2022,2023],{},"\u003Cphpunit xmlns:xsi=\"http:\u002F\u002Fwww.w3.org\u002F2001\u002FXMLSchema-instance\"\n",[131,2025,2026],{"class":133,"line":211},[131,2027,2028],{},"         xsi:noNamespaceSchemaLocation=\"vendor\u002Fphpunit\u002Fphpunit\u002Fphpunit.xsd\"\n",[131,2030,2031],{"class":133,"line":224},[131,2032,2033],{},"         bootstrap=\"vendor\u002Fautoload.php\"\n",[131,2035,2036],{"class":133,"line":236},[131,2037,2038],{},"         colors=\"true\"\n",[131,2040,2041],{"class":133,"line":243},[131,2042,2043],{},">\n",[131,2045,2046],{"class":133,"line":274},[131,2047,2048],{},"    \u003Ctestsuites>\n",[131,2050,2051],{"class":133,"line":307},[131,2052,2053],{},"        \u003Ctestsuite name=\"Console\"> \u003C!-- [!code ++] -->\n",[131,2055,2056],{"class":133,"line":312},[131,2057,2058],{},"            \u003Cdirectory>tests\u002FConsole\u003C\u002Fdirectory> \u003C!-- [!code ++] -->\n",[131,2060,2061],{"class":133,"line":321},[131,2062,2063],{},"        \u003C\u002Ftestsuite> \u003C!-- [!code ++] -->\n",[131,2065,2066],{"class":133,"line":326},[131,2067,2068],{},"    \u003C\u002Ftestsuites>\n",[131,2070,2071],{"class":133,"line":339},[131,2072,2073],{},"\u003C\u002Fphpunit>\n",[10,2075,2076],{},"Because these tests access the database, update Pest so it refreshes the database before each test:",[121,2078,2081],{"className":1158,"code":2079,"filename":2080,"language":1125,"meta":127,"style":127},"pest()->extend(Tests\\TestCase::class)\n    ->use(Illuminate\\Foundation\\Testing\\RefreshDatabase::class)\n    ->in('Console', 'Http', 'Unit'); \u002F\u002F [!code highlighter]\n","tests\u002FPest.php",[14,2082,2083,2088,2093],{"__ignoreMap":127},[131,2084,2085],{"class":133,"line":134},[131,2086,2087],{},"pest()->extend(Tests\\TestCase::class)\n",[131,2089,2090],{"class":133,"line":198},[131,2091,2092],{},"    ->use(Illuminate\\Foundation\\Testing\\RefreshDatabase::class)\n",[131,2094,2095],{"class":133,"line":211},[131,2096,2097],{},"    ->in('Console', 'Http', 'Unit'); \u002F\u002F [!code highlighter]\n",[71,2099,2101],{"id":2100},"final-words","Final words",[10,2103,2104],{},"The frontend and backend now share a stable identifier for every post. VitePress generates the metadata, and Laravel can synchronize its records without manual database updates.",[10,2106,2107],{},"That gives us the bridge we need for the interactive features. Next, we will configure Sanctum, CORS, and CSRF protection, then send the first requests from VitePress to Laravel.",[2109,2110,2111],"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 .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 .s8jYJ, html code.shiki .s8jYJ{--shiki-light:#D73A49;--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sxrX7, html code.shiki .sxrX7{--shiki-light:#24292E;--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sP4rz, html code.shiki .sP4rz{--shiki-light:#E36209;--shiki-default:#E36209;--shiki-dark:#FFAB70}html pre.shiki code .sBjJW, html code.shiki .sBjJW{--shiki-light:#005CC5;--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .sovSZ, html code.shiki .sovSZ{--shiki-light:#22863A;--shiki-default:#22863A;--shiki-dark:#85E89D}",{"title":127,"searchDepth":198,"depth":198,"links":2113},[2114,2116,2119],{"id":73,"depth":198,"text":2115},"Generating the meta.json file",{"id":1093,"depth":198,"text":1094,"children":2117},[2118],{"id":1571,"depth":211,"text":1572},{"id":2100,"depth":198,"text":2101},"53a607df-d10e-4423-966c-500d2885e6e0","2025-02-25","Generate frontend metadata with VitePress, synchronize posts with Laravel, and keep the backend database aligned automatically.",null,{},"\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fautomating-your-backend-to-stay-in-sync-effortlessly","---\ncontentId: 53a607df-d10e-4423-966c-500d2885e6e0\npart: 5\ntitle: Automating Your Backend to Stay in Sync Effortlessly\ndescription: Generate frontend metadata with VitePress, synchronize posts with Laravel, and keep the backend database aligned automatically.\ndate: 2025-02-25\nseriesSlug: empower-and-dynamize-our-vitepress-blog-with-a-laravel-api\n---\n\nAt the end of the previous article, we created a `posts` table with a `meta_id` column. We have not used that column yet, so this article will connect it to the frontend.\n\nVitePress generates a static website at build time, while comments are loaded dynamically for the post currently being viewed. To make that work, the frontend and backend need a stable way to identify the same post.\n\nFor example, the blog \u003CGitHubLink repo=\"barbapapazes\u002Fgarabit\" \u002F> has two articles with these slugs:\n\n1. Getting Started with Laravel (`getting-started-with-laravel`)\n2. Getting Started with Vue 3 and Vite (`getting-started-with-vue-3-and-vite`)\n\nWe could use the slug as the identifier, but slugs sometimes change because of a typo, search-engine optimization, or a change in the content. Keeping an outdated slug only to preserve an identifier makes URLs less useful. We need a separate identifier that remains stable even when the slug changes.\n\nThe solution is to store a stable ID in each post's frontmatter. This ID identifies the post and does not change when its title, content, or slug changes.\n\nThe remaining question is how to send these IDs to the backend. Manual synchronization is error-prone and easy to automate, so the frontend will generate a `meta.json` file at build time. It will contain each post's ID and title. The backend will read that file and create or update the corresponding database records. The frontend can then fetch comments by using the ID in the post frontmatter, while the `posts.id` column remains an internal key used to link posts to comments.\n\nThe architecture is straightforward: VitePress writes the post metadata, and Laravel reads it to keep its records synchronized.\n\n## Generating the `meta.json` file\n\nFor this part, open the \u003CGitHubLink repo=\"barbapapazes\u002Fgarabit\" \u002F> project. We will create a `genMeta` function that reads all Markdown files, extracts each ID and title from the frontmatter, and writes them to `dist\u002Fmeta.json` using VitePress's `buildEnd` hook. VitePress calls this hook after the rest of the build has finished, which makes it a good place to generate the file.\n\nFirst, create a `generators` folder inside `.vitepress`. It will contain the functions called by the `buildEnd` hook.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\n`generators` is only a naming choice. You can use any folder name you prefer.\n::\n\n```bash [terminal]\nmkdir .vitepress\u002Fgenerators\n```\n\nCreate `meta.ts` in that folder. It will contain `genMeta`.\n\n```bash [terminal]\ntouch .vitepress\u002Fgenerators\u002Fmeta.ts\n```\n\nFinally, we can write our function:\n\n```ts [.vitepress\u002Fgenerators\u002Fmeta.ts]\nimport type { ContentData, SiteConfig } from 'vitepress'\nimport { writeFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { createContentLoader } from 'vitepress'\n\nexport async function genMeta(config: SiteConfig) {\n  const posts = await createContentLoader('**\u002Fblog\u002F**\u002F*.md').load()\n\n  validatePosts(posts)\n\n  const meta = []\n\n  for (const item of posts) {\n    meta.push({\n      id: item.frontmatter.id,\n      title: item.frontmatter.title,\n    })\n  }\n\n  writeFileSync(path.join(config.outDir, 'meta.json'), JSON.stringify(meta.sort((a, b) => a.id - b.id), null, 2))\n}\n\nfunction validatePosts(items: ContentData[]) {\n  const ids = new Set\u003Cstring>()\n\n  for (const item of items) {\n    if (!item.frontmatter.id) {\n      throw new Error(`Id is missing: ${item.url}`)\n    }\n\n    if (ids.has(item.frontmatter.id)) {\n      throw new Error(`Id is not unique: ${item.frontmatter.id} (${item.url}) (${items.find(i => i.frontmatter.id === item.frontmatter.id)?.url})`)\n    }\n\n    ids.add(item.frontmatter.id)\n  }\n}\n```\n\nThe script has three steps. First, `createContentLoader` reads the Markdown files and parses their frontmatter. Next, we verify that every post has an ID and that IDs are unique. This matters because a post without an ID cannot participate in the comment system, while duplicate IDs would make two posts share comments. The validation throws an error and stops the build in either case.\n\nWe then create an array containing each post's ID and title and write it to `dist\u002Fmeta.json`.\n\nTo run it, add `genMeta` to the `buildEnd` hook in `.vitepress\u002Fconfig.ts`:\n\n```ts [.vitepress\u002Fconfig.ts]\nimport { defineConfig } from 'vitepress'\nimport { genMeta } from '.\u002Fgenerators\u002Fmeta'\n\nexport default defineConfig({\n  \u002F\u002F ...\n\n  buildEnd: async (config) => {\n    await genMeta(config)\n  },\n})\n```\n\nFinally, add a unique ID to each post:\n\n```md [src\u002Fblog\u002Fgetting-started-with-laravel.md]\n---\nid: 1 [!code ++]\ntitle: Getting Started with Laravel\ndescription:\ndate: 2024-10-14\n---\n```\n\n```md [src\u002Fblog\u002Fgetting-started-with-vue-3-and-vite.md]\n---\nid: 2\ntitle: Getting Started with Vue 3 and Vite\ndescription:\ndate: 2024-09-14\n---\n```\n\nWhen we build the frontend, VitePress will create `meta.json` in `dist`. It will contain each post's ID and title. Check it with:\n\n```bash [terminal]\nnpm run build\n```\n\n```bash [terminal]\ncat .vitepress\u002Fdist\u002Fmeta.json\n```\n\nThe output should look similar to this:\n\n```json [.vitepress\u002Fdist\u002Fmeta.json]\n[\n  {\n    \"id\": 1,\n    \"title\": \"Getting Started with Laravel\"\n  },\n  {\n    \"id\": 2,\n    \"title\": \"Getting Started with Vue 3 and Vite\"\n  }\n]\n```\n\nIf you see this file, the frontend half of the synchronization is complete.\n\n## Retrieving the posts from the backend\n\nNext, the backend needs to read this file and synchronize the database. We will create an `app:posts-sync` command that fetches and parses `meta.json`, then inserts or updates each post.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nThe `title` column is not used by the frontend or the API, but it makes database records easier to identify and can be useful in an admin panel.\n::\n\nCreate the command with Artisan:\n\n```bash [terminal]\nphp artisan make:command PostsSync\n```\n\nThe command will be created in `app\u002FConsole\u002FCommands`. Its job is simple:\n\n1. Fetch the `meta.json` file from the frontend\n2. Insert (or update) each post in the database\n\nHere is the implementation:\n\n```php [app\u002FConsole\u002FCommands\u002FPostsSync.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Console\\Commands;\n\nuse App\\Models\\Post;\nuse Illuminate\\Console\\Command;\nuse Illuminate\\Support\\Facades\\Config;\nuse Illuminate\\Support\\Facades\\Http;\n\nfinal class PostsSync extends Command\n{\n    \u002F**\n     * The name and signature of the console command.\n     *\n     * @var string\n     *\u002F\n    protected $signature = 'app:posts-sync';\n\n    \u002F**\n     * The console command description.\n     *\n     * @var string\n     *\u002F\n    protected $description = 'Synchronize backend posts with the frontend through the `meta.json` file.';\n\n    \u002F**\n     * Execute the console command.\n     *\u002F\n    public function handle(): void\n    {\n        \u002F**\n         * @var array\u003Carray\u003Cstring, int|string>>\n         *\u002F\n        $response = Http::get(Config::get('app.frontend_url').'\u002Fmeta.json')\n            ->json();\n\n        $meta = collect($response)->map(\n            fn (array $post): array => [\n                'meta_id' => $post['id'],\n                'title' => $post['title'],\n            ]\n        )->toArray();\n\n        Post::upsert($meta, uniqueBy: ['meta_id'], update: ['title']);\n    }\n}\n```\n\nThe [`upsert`](https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Feloquent#upserts) method handles both cases. It inserts records that do not exist, using the unique `meta_id` key, and updates the title of an existing record.\n\nThe command must work in both local and production environments. Locally, the frontend may be served from `localhost:5173` or `localhost:4173` during a preview. In production, it is served from a public URL. We solve that difference with the `APP_FRONTEND_URL` environment variable, exposed through the `frontend_url` key in `config\u002Fapp.php`.\n\n```ini [.env.example]\nAPP_FRONTEND_URL=http:\u002F\u002Flocalhost:4173\n```\n\n```php [config\u002Fapp.php]\nreturn [\n    \u002F\u002F ...\n\n    'frontend_url' => env('APP_FRONTEND_URL', 'http:\u002F\u002Flocalhost:4173'),\n\n    \u002F\u002F ...\n];\n```\n\nThe code is then identical in both environments; only the environment variable changes.\n\nDuring development, start the frontend preview server:\n\n```bash [terminal]\nnpm run build && npm run preview\n```\n\nThen run the synchronization command:\n\n```bash [terminal]\nphp artisan app:posts-sync\n```\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nSet the correct `APP_FRONTEND_URL` in `.env` before running the command.\n::\n\nIf you see `SQLSTATE[HY000]: General error: 1 no such table: posts`, the `posts` table has not been created yet. Run:\n\n```bash [terminal]\nphp artisan migrate\n```\n\nYou can now run the synchronization command repeatedly without creating duplicate records.\n### Testing the command\n\nThe command is part of our application and we have to test it. To do this, we will mock the `Http` facade. This way, we can test the command without relying on the network. This is one of the rare cases where mocking is useful.\n\nTo mock the HTTP client, use [`Http::fake`](https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fhttp-client#testing). It lets the test provide a predictable `meta.json` response without relying on the network.\n\n```php [tests\u002FConsole\u002FPostsSyncTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse Illuminate\\Support\\Facades\\Config;\nuse Illuminate\\Support\\Facades\\Http;\n\nit('fetches posts meta', function () {\n    Http::fake([\n        Config::get('app.frontend_url').'\u002Fmeta.json' => Http::response([\n            [\n                'id' => 1,\n                'title' => 'Post 1',\n            ],\n            [\n                'id' => 2,\n                'title' => 'Post 2',\n            ],\n        ], 200),\n    ]);\n\n    $this->artisan('app:posts-sync')\n        ->assertExitCode(0);\n\n    Http::assertSentCount(1);\n\n    $this->assertDatabaseCount('posts', 2);\n    $this->assertDatabaseHas('posts', [\n        'meta_id' => 1,\n        'title' => 'Post 1',\n    ]);\n});\n\nit('does not insert duplicates', function () {\n    Http::fake([\n        Config::get('app.frontend_url').'\u002Fmeta.json' => Http::response([\n            [\n                'id' => 1,\n                'title' => 'Post 1',\n            ],\n            [\n                'id' => 1,\n                'title' => 'Post 1',\n            ],\n        ], 200),\n    ]);\n\n    $this->artisan('app:posts-sync')\n        ->assertExitCode(0);\n\n    Http::assertSentCount(1);\n\n    $this->assertDatabaseCount('posts', 1);\n    $this->assertDatabaseHas('posts', [\n        'meta_id' => 1,\n        'title' => 'Post 1',\n    ]);\n});\n\nit('updates the data based on the id', function () {\n    Http::fake([\n        Config::get('app.frontend_url').'\u002Fmeta.json' => Http::response([\n            [\n                'id' => 1,\n                'title' => 'Post 1',\n            ],\n            [\n                'id' => 1,\n                'title' => 'Post 1 Updated',\n            ],\n        ], 200),\n    ]);\n\n    $this->artisan('app:posts-sync')\n        ->assertExitCode(0);\n\n    Http::assertSentCount(1);\n\n    $this->assertDatabaseCount('posts', 1);\n    $this->assertDatabaseHas('posts', [\n        'meta_id' => 1,\n        'title' => 'Post 1 Updated',\n    ]);\n});\n```\n\nThe command tests live in a new `Console` folder. Add that folder to `phpunit.xml` so PHPUnit discovers them:\n\n```xml [phpunit.xml]\n\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\u003Cphpunit xmlns:xsi=\"http:\u002F\u002Fwww.w3.org\u002F2001\u002FXMLSchema-instance\"\n         xsi:noNamespaceSchemaLocation=\"vendor\u002Fphpunit\u002Fphpunit\u002Fphpunit.xsd\"\n         bootstrap=\"vendor\u002Fautoload.php\"\n         colors=\"true\"\n>\n    \u003Ctestsuites>\n        \u003Ctestsuite name=\"Console\"> \u003C!-- [!code ++] -->\n            \u003Cdirectory>tests\u002FConsole\u003C\u002Fdirectory> \u003C!-- [!code ++] -->\n        \u003C\u002Ftestsuite> \u003C!-- [!code ++] -->\n    \u003C\u002Ftestsuites>\n\u003C\u002Fphpunit>\n```\n\nBecause these tests access the database, update Pest so it refreshes the database before each test:\n\n```php [tests\u002FPest.php]\npest()->extend(Tests\\TestCase::class)\n    ->use(Illuminate\\Foundation\\Testing\\RefreshDatabase::class)\n    ->in('Console', 'Http', 'Unit'); \u002F\u002F [!code highlighter]\n```\n\n## Final words\n\nThe frontend and backend now share a stable identifier for every post. VitePress generates the metadata, and Laravel can synchronize its records without manual database updates.\n\nThat gives us the bridge we need for the interactive features. Next, we will configure Sanctum, CORS, and CSRF protection, then send the first requests from VitePress to Laravel.\n",{"title":5,"description":2122},"empower-and-dynamize-our-vitepress-blog-with-a-laravel-api",{"loc":2125},"series\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fautomating-your-backend-to-stay-in-sync-effortlessly","kGM-ai7a7InwUnfQSyFSVc0J0x1NFiPmJcbHvQ9YzGA",{"overview":2133,"chapters":2309},{"id":2134,"title":2135,"body":2136,"contentId":2293,"date":2294,"description":2295,"extension":872,"github":2123,"meetTheInstructor":2296,"meta":2297,"navigation":239,"part":2123,"path":2298,"rawbody":2299,"robots":2123,"schemaOrg":2123,"seo":2300,"seriesSlug":2128,"sitemap":2301,"stem":2302,"subtitle":2303,"topics":2304,"__hash__":2308},"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":2137,"toc":2290},[2138,2141,2144,2147,2151,2160,2163,2172,2175,2178,2261,2264,2267,2270,2280,2284],[10,2139,2140],{},"Hello! 👋",[10,2142,2143],{},"After building our VitePress blog, we are ready to make it more dynamic with a Laravel API.",[10,2145,2146],{},"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.",[2148,2149],"callout-read-more",{"id":2150},"43c95b33-041c-4108-ab98-0d21ef60ed7f",[10,2152,2153,2154,2159],{},"This series introduces back-end development by creating a ",[444,2155,2158],{"href":2156,"rel":2157},"https:\u002F\u002Flaravel.com",[1404],"Laravel"," API that gives our blog a few interactive features.",[10,2161,2162],{},"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,2164,2165,2166,2171],{},"Although the focus is on the back end, we will also integrate the API into our VitePress blog. We will use Vue.js and ",[444,2167,2170],{"href":2168,"rel":2169},"https:\u002F\u002Fpinia-colada.esm.dev\u002F",[1404],"Pinia Colada"," as our data-fetching framework. VitePress is a Vue.js application, so we can extend it with the components we need.",[10,2173,2174],{},"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,2176,2177],{},"Throughout the series, we will build a Laravel API and integrate it with our VitePress blog. We will cover:",[2179,2180,2181,2188,2216,2227,2233,2243,2249,2255],"ul",{},[37,2182,2183,2187],{},[2184,2185,2186],"strong",{},"Setting up the Laravel project",": Create a new Laravel project and become familiar with its structure.",[37,2189,2190,2193,2194,447,2199,447,2204,2209,2210,2215],{},[2184,2191,2192],{},"Improving the development workflow",": Configure ",[444,2195,2198],{"href":2196,"rel":2197},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fpint",[1404],"Pint",[444,2200,2203],{"href":2201,"rel":2202},"https:\u002F\u002Fgithub.com\u002Frectorphp\u002Frector",[1404],"Rector",[444,2205,2208],{"href":2206,"rel":2207},"https:\u002F\u002Fgithub.com\u002Flarastan\u002Flarastan",[1404],"Larastan",", and ",[444,2211,2214],{"href":2212,"rel":2213},"https:\u002F\u002Fpestphp.com\u002F",[1404],"Pest"," for formatting, refactoring, static analysis, and testing.",[37,2217,2218,2221,2222,152],{},[2184,2219,2220],{},"Adding social authentication",": Let users sign in with GitHub through ",[444,2223,2226],{"href":2224,"rel":2225},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fsocialite",[1404],"Laravel Socialite",[37,2228,2229,2232],{},[2184,2230,2231],{},"Connecting the applications",": Configure Sanctum, CORS, CSRF protection, and the first requests between the VitePress frontend and the Laravel API.",[37,2234,2235,2238,2239,2242],{},[2184,2236,2237],{},"Managing authentication state",": Use ",[444,2240,2170],{"href":2168,"rel":2241},[1404]," to retrieve the current user and log out with an optimistic update.",[37,2244,2245,2248],{},[2184,2246,2247],{},"Building the comment API",": Create the models, relationships, endpoints, validation, authorization, and tests for comments.",[37,2250,2251,2254],{},[2184,2252,2253],{},"Keeping the backend in sync",": Generate post metadata from VitePress and synchronize it with the Laravel database.",[37,2256,2257,2260],{},[2184,2258,2259],{},"Building the comment interface",": Fetch, create, edit, and delete comments from the VitePress frontend.",[10,2262,2263],{},"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,2265,2266],{},"Testing is part of the development process and will be included at each stage, so it does not need a dedicated article.",[10,2268,2269],{},"If you have questions, feedback, or suggestions, feel free to share them in the comments. Your input helps improve the series.",[111,2271,2272],{"color":113,"icon":114},[10,2273,2274,2275,2279],{},"This series assumes prior knowledge of TypeScript, Vue.js, and Laravel. If you are unfamiliar with any of these technologies, review the ",[444,2276,2278],{"href":2277},"\u002Fseries\u002Fcreate-a-blog-with-vitepress-and-vue-js-from-scratch","Create a Blog with VitePress and Vue.js from Scratch"," first.",[71,2281,2283],{"id":2282},"chapters","Chapters",[2285,2286],"series-chapters-list",{"className":2287},[2288,2289],"mx-auto","max-w-5xl",{"title":127,"searchDepth":198,"depth":198,"links":2291},[2292],{"id":2282,"depth":198,"text":2283},"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":2135,"description":2295},{"loc":2298},"series\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api","Transform your VitePress blog into a dynamic platform with an API",[2305,2306,2307],"laravel","vitepress","api","JLBtX9BKfN72BkhcYisEXraNGTvZSnT5YHM05A_uemk",[2310,2315,2320,2325,2330,2331,2336,2341],{"contentId":2311,"title":2312,"description":2313,"path":2314,"part":134,"github":2123,"topics":2123},"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":2316,"title":2317,"description":2318,"path":2319,"part":198,"github":2123,"topics":2123},"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":2321,"title":2322,"description":2323,"path":2324,"part":211,"github":2123,"topics":2123},"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":2326,"title":2327,"description":2328,"path":2329,"part":224,"github":2123,"topics":2123},"b07ec3b5-ca56-4d14-ae2f-8c0702218293","Building a Simple Comment System for User Engagement","Build a Laravel comment API with models, migrations, resources, policies, form requests, controllers, routes, and comprehensive tests.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbuilding-a-simple-comment-system-for-user-engagement",{"contentId":2120,"title":5,"description":2122,"path":2125,"part":236,"github":2123,"topics":2123},{"contentId":2332,"title":2333,"description":2334,"path":2335,"part":243,"github":2123,"topics":2123},"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":2337,"title":2338,"description":2339,"path":2340,"part":274,"github":2123,"topics":2123},"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":2342,"title":2343,"description":2344,"path":2345,"part":307,"github":2123,"topics":2123},"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",1795016693764]