Sitemap search engine friendly in Laravel

Stefanescu Mihai 2 years ago iNoob

Cu ceva timp in urma (acum cativa ani) motoarele de cautare (ex: Google) au recomandat sa facem submit sitemap-urilor astfel incat indexarea site-urilor sa fie mai simpla si rapida.

In clipa de fata exista pareri si pareri cum ca sitemap-ul nu mai este atat de important in prezent, dar eu sunt de parere ca nu poate strica sa dai submit unui sitemap.

Ce este un sitemap?

Daca nu cunosti termenul, Google a dat aceasta definitie:

A sitemap is a file where you can list the web pages of your site to tell Google and other search engines about the organization of your site content. Search engine web crawlers like Googlebot read this file to more intelligently crawl your site.

Ne mai dau si urmatoarele motive de a face submit unui sitemap:

  • Site-ul este foarte mare, iar crawlerii Google pot sari peste anumite pagini din site.

  • Site-ul are o arhiva foarte mare cu link-uri izolate sau pentru care nu exista link-uri atat de usor accesibile

  • Site-ul are mult continut media.

Poate ca site-ul tau nu se incadreaza in aceste criterii, dar tot nu ar strica sa faci submit unui sitemap.

Protocolul sitemap

Pe site-ul oficial se regasesc toate informatiile referitoare la structura unui fisier sitemap, dar totusi am sa va pun si aici un mic exemplu:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.invata-programare.ro/</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
</urlset> 

Din ce se poate observa sitemap-ul este un simplu xml ce contine tag-ul <url> pentru fiecare pagina din site-ul tau.

Un singur sitemap poate contine in jud de 50000 link-uri, dar daca aveti nevoie le puteti separa in mai multe fixiere, iar apoi sa le includeti intr-un fisier de index.

Acest fisier ar trebuii sa arate in acest mod:

<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <sitemap>
      <loc>http://www.invata-programare.ro/sitemap1.xml.gz</loc>
      <lastmod>2004-10-01T18:23:17+00:00</lastmod>
   </sitemap>
   <sitemap>
      <loc>http://www.invata-programare.ro/sitemap2.xml.gz</loc>
      <lastmod>2005-01-01</lastmod>
   </sitemap>
</sitemapindex>

In tag-ul <loc> punem locatia fisierului xml, intr-o maniera similara cu <url>

Construirea unui Controller pentru Sitemap

In acest articol voi considera ca voi crea sitemap pentru articole pe blog, categoriile blogului si articole video. Fiecar dintre acestea va avea proriul sitemap, iar mai apoi vor fi apelate in fisierul de index.

Pentru inceput hai sa facem un controller pentru sitemap:

php artisan make:controller SitemapController

Acum hai sa deschidem acest fisier si sa facem un fisier de index.

Crearea indexului

Hai sa scriem o metoda ce ne va genera XML-ul necesar:

public function index()
{
  $post = Post::active()->orderBy('updated_at', 'desc')->first();
  $video = Video::active()->orderBy('updated_at', 'desc')->first();

  return response()->view('sitemap.index', [
      'post' => $post,
      'video' => $video,
  ])->header('Content-Type', 'text/xml');
}

Atentie, in sitemap trebuie sa avem si timestamp-urile articolelor, astfel incat crawlerele sa stie daca au aparut modificari in continut.

Probabil nu sunteti obisnuiti cu acest tip de return, ci doar cu return-ul unui view in modul clasic. In acest mod returnez un view caruia ii setez headerul de text/xml. View-ul mei sitemap.index arata in acest mod:

<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <sitemap>
        <loc>https://invata-programare.ro/sitemap/posts</loc>
        <lastmod>{{ $post->publishes_at->tz('UTC')->toAtomString() }}</lastmod>
    </sitemap>
    <sitemap>
        <loc>https://invata-programare.ro/sitemap/categories</loc>
        <lastmod>{{ $post->publishes_at->tz('UTC')->toAtomString() }}</lastmod>
    </sitemap>
    <sitemap>
        <loc>https://invata-programare.ro/sitemap/podcasts</loc>
        <lastmod>{{ $podcast->publishes_at->tz('UTC')->toAtomString() }}</lastmod>
    </sitemap
</sitemapindex>

In acest view am sa folosesc Carbon pentru a afisa data in UTC si in formatul corect.

Crearea sitemap-urilor

Urmatorul pas este crearea fiecarei pagini pentru sitemap-uri. Trebuie sa facem 3 metode noi si foarte similare in controller.


public function posts()
{
    $posts = Post::active()->where('category_id', '!=', 21)->get();
    return response()->view('sitemap.posts', [
        'posts' => $posts,
    ])->header('Content-Type', 'text/xml');
}

public function categories()
{
    $categories = Category::all();
    return response()->view('sitemap.categories', [
        'categories' => $categories,
    ])->header('Content-Type', 'text/xml');
}

public function videos()
{
    $videos = Video::active()->orderBy('updated_at', 'desc')->get();
    return response()->view('sitemap.videos', [
        'videos' => $videos,
    ])->header('Content-Type', 'text/xml');
}

O data ce am facut aceste metode trebuie sa facem si view-ul pentru fiecare. Iata mai jos un exemplu de view:

<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach ($posts as $post)
        <url>
            <loc>https://invata-programare.ro/{{ $post->uri }}</loc>
            <lastmod>{{ $post->publishes_at->tz('UTC')->toAtomString() }}</lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.6</priority>
        </url>
    @endforeach
</urlset>

O data ce am ajuns aici mai trebuie sa facem un singur lucru, rutele:

Route::get('/sitemap', 'SitemapController@index');
Route::get('/sitemap/posts', 'SitemapController@posts');
Route::get('/sitemap/categories', 'SitemapController@categories');
Route::get('/sitemap/videos', 'SitemapController@videos');

Concluzie

Din ce se poate observa, construirea unui sitemap in laravel este relativ simpla, mai ales daca ai un site cu o structura relativ simpla cum am eu in exemplul din articol.

Programator de ~8 ani, am lucrat la proiecte din mai multe industrstrii, de la eCommerce la telecomunicatii la automatizari. In acest timp am folosi diferite tehnologii, de la PHP, MySQL, PostgreSql, RabbitMq, Redis, Memcached si altele.


Get in touch
Pentru nelamuriri, dubii, comentarii si chestii de pe suflet ne putem auzi pe Discord, Reddit sau poti deschide o discutie noua pe forum

Cijeiz # 1 month ago buy cheap tricor <a href="https://fenoficor.com/">fenofibrate 160mg generic</a> order fenofibrate online cheap
Vhzhiv # 1 month ago buy cheap generic zaditor <a href="https://tofobose.com/">buy generic imipramine 75mg</a> buy tofranil 25mg generic
Elouaz # 1 month ago buy generic minoxytop for sale <a href="https://edxgetonline.shop/">cheap erectile dysfunction pills</a> best ed pills non prescription uk
Izpmws # 1 month ago buy precose <a href="https://tofobose.shop/">acarbose 50mg over the counter</a> buy fulvicin pills for sale
Skjyil # 4 weeks ago cheap aspirin <a href="https://imitonin.com/">buy imiquimod without prescription</a> imiquimod for sale
Veola # 3 weeks ago Good day! Would you mind if I share your blog with my myspace group? There's a lot of people that I think would really enjoy your content. Please let me know. Thank you
Wvcoyh # 3 weeks ago duphaston order online <a href="https://janozin.shop/">forxiga 10 mg over the counter</a> cost jardiance 10mg
Efpcnc # 3 weeks ago fludrocortisone tablet <a href="https://pravinef.shop/">buy florinef paypal</a> how to buy loperamide
Szpcsc # 3 weeks ago monograph 600 mg generic <a href="https://colotazol.com/">order colospa 135 mg generic</a> pletal 100mg uk
Xjaxvj # 3 weeks ago prasugrel 10mg ca <a href="https://thoramine.shop/">where to buy dramamine without a prescription</a> detrol cheap
Jmmozj # 2 weeks ago ferrous sulfate 100 mg pill <a href="https://fertonel.com/">buy ferrous sulfate 100 mg online</a> buy sotalol pills for sale
Rblajk # 2 weeks ago pyridostigmine for sale online <a href="https://mestien.shop/">cheap feldene 20mg</a> order maxalt
Ppaabf # 2 weeks ago vasotec brand <a href="https://betaotec.shop/">purchase vasotec online cheap</a> where can i buy lactulose
moltenmama # 1 week ago <a href="https://www.seloroh.com/miami-dolphins-bucket-hat-90s-handt">miami dolphins bucket hat 90s</a><a href="https://www.seloroh.com/new-york-mets-50th-anniversary-hat-tricks-handt">new york mets 50th anniversary hat tricks</a><a href="https://www.seloroh.com/minnesota-twins-winter-hat-list-handt">minnesota twins winter hat list</a><a href="https://www.seloroh.com/texas-rangers-2015-playoff-hat-pin-handt">texas rangers 2015 playoff hat pin</a> <a href="https://www.dizienleri.com/small-marlon-shoulder-bag-bagq">small marlon shoulder bag</a> <a href="https://www.snapitf.com/nike-air-force-1-gs-hyper-pink-cement-shoesw">nike air force 1 gs hyper pink cement</a><a href="https://www.snapitf.com/nike-free-mercurial-superfly-blue-shoesw">nike free mercurial superfly blue</a><a href="https://www.snapitf.com/jordan-retro-4-blue-and-hvit-shoesw">jordan retro 4 blue and hvit</a><a href="https://www.snapitf.com/adidas-superstar-hvid-lazada-shoesw">adidas superstar hvid lazada</a> <a href="https://www.yu-travel.net/luis-boutin-heels-louboutinit">luis boutin heels</a> <a href="https://www.dsis-conf.net/vn0a4bvatj1-shippingcz">vn0a4bvatj1</a> <a href="https://www.taedits.com/plus-size-beach-wedding-dresses-dresso">plus size beach wedding dresses</a><a href="https://www.taedits.com/tan-evening-gowns-dresso">tan evening gowns</a><a href="https://www.taedits.com/ladies-dressing-gowns-peacocks-dresso">ladies dressing gowns peacocks</a><a href="https://www.taedits.com/burgundy-nike-dress-dresso">burgundy nike dress</a> [url=http://www.moltenmama.net/]moltenmama[/url]
Psnzez # 1 week ago buy cheap zovirax <a href="https://aexeloda.shop/">rivastigmine sale</a> buy exelon without a prescription
aankoop van enjuvia in Europa # 1 week ago Yesterday, while I was at work, my sister stole my apple ipad and tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!
Hoajbw # 1 week ago betahistine usa <a href="https://haloatan.com/">haldol brand</a> buy benemid generic
Dglycz # 1 week ago order generic micardis <a href="https://molnenil.com/">buy generic plaquenil over the counter</a> molnunat 200mg tablet
Uzkpwn # 6 days ago buy cenforce sale <a href="https://enapocen.shop/">naprosyn 500mg pills</a> buy chloroquine 250mg
commande de ethambutol 400 mg en Belgique # 2 days ago Hello there! Quick question that's totally off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my iphone 4. I'm trying to find a template or plugin that might be able to fix this issue. If you have any suggestions, please share. Thank you!
Club-ul este dedicat membrilor si ofera access la mai multe zone ale website-ului.
Login Register

๐Ÿ”– Bookmarks โž•
โœจ Pentru a sustine aceasta comunitate am sa te rog sa te autentifici sau sa te inregistrezi!

๐ŸŒช๏ธ Discord โž•
Back to top
Folosim cookie-uri pentru a oferi functionalitatile critice ale aplicatiei Invata-Programare. Folosim cookie-uri si pentru a analiza traficul, pentru care e nevoie de consimtamantul dvs. explicit.