generate dynamic sitemaps in a laravel project without using composer

前端 未结 4 1221
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 13:30

I want to generate Dynamic sitemap for my laravel project. I had already searched in so many sites for an answer. some of them describes it using composer. I di

相关标签:
4条回答
  • 2020-12-14 13:54

    Add this line to your routes.php

    Route::get('/sitemap', function()
    {
       return Response::view('sitemap')->header('Content-Type', 'application/xml');
    });
    

    Create new file app\Http\Middleware\sitemap.php

    <?php namespace App\Http\Middleware;
    
    use Closure;
    use Carbon\Carbon;
    use Illuminate\Contracts\Auth\Guard;
    
    class sitemap {
    
        /**
         * The Guard implementation.
         *
         * @var Guard
         */
        protected $auth;
    
        public function __construct(Guard $auth)
        {
            $this->auth = $auth;
        }
    
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request $request
         * @param  \Closure                 $next
         *
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            if ( !$request->is("sitemap") && $request->fullUrl() != '' && $this->auth->guest() )
            {
                $aSiteMap = \Cache::get('sitemap', []);
                $changefreq = 'always';
                if ( !empty( $aSiteMap[$request->fullUrl()]['added'] ) ) {
                    $aDateDiff = Carbon::createFromTimestamp( $aSiteMap[$request->fullUrl()]['added'] )->diff( Carbon::now() );
                    if ( $aDateDiff->y > 0 ) {
                        $changefreq = 'yearly';
                    } else if ( $aDateDiff->m > 0) {
                        $changefreq = 'monthly';
                    } else if ( $aDateDiff->d > 6 ) {
                        $changefreq = 'weekly';
                    } else if ( $aDateDiff->d > 0 && $aDateDiff->d < 7 ) {
                        $changefreq = 'daily';
                    } else if ( $aDateDiff->h > 0 ) {
                        $changefreq = 'hourly';
                    } else {
                        $changefreq = 'always';
                    }
                }
                $aSiteMap[$request->fullUrl()] = [
                    'added' => time(),
                    'lastmod' => Carbon::now()->toIso8601String(),
                    'priority' => 1 - substr_count($request->getPathInfo(), '/') / 10,
                    'changefreq' => $changefreq
                ];
                \Cache::put('sitemap', $aSiteMap, 2880);
            }
            return $next($request);
        }
    }
    

    And create new view file resources\views\sitemap.blade.php

    <?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
            xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
            xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
        @foreach( Cache::get('sitemap') as $url => $params )
        <url>
            <loc>{{$url}}</loc>
            <lastmod>{{$params['lastmod']}}</lastmod>
            <changefreq>{{$params['changefreq']}}</changefreq>
            <priority>{{$params['priority']}}</priority>
        </url>
        @endforeach
    </urlset>
    

    Add an entry to protected $middleware array in the file app\Http\Kernel.php

    'sitemap' => 'App\Http\Middleware\sitemap'
    
    0 讨论(0)
  • 2020-12-14 14:01

    routes in laravel for sitemap

    Route::get('/sitemap.xml', 'SitemapController@index');
    Route::get('/sitemap.xml/products', 'SitemapController@product');
    Route::get('/sitemap.xml/FAQ', 'SitemapController@FAQ');
    Route::get('/sitemap.xml/Inquiry', 'SitemapController@inquiry);
    

    Controller methods

      public function product()
    {
        $products= Product::latest()->get();
        return response ()->view ('sitemap.product', [
            'products' => $products,
        ])->header ('Content-Type', 'text/xml');
    }
    
    public function faqs()
    {
        $FAQ = FAQt::active()->orderBy('updated_at', 'desc')->get();
        return response()->view('sitemap.FAQ', [
            'FAQ' => $FAQ,
        ])->header('Content-Type', 'text/xml');
    }
    
    public function inquiry()
    {
        $FAQ = inquiry ::active()->orderBy('updated_at', 'desc')->get();
        return response()->view('sitemap.inquiry ', [
            'inquiry ' => $ inquiry,
        ])->header('Content-Type', 'text/xml');
    }
    

    Generate sitemap in laravel with example

    0 讨论(0)
  • 2020-12-14 14:13

    Suppose you want your website's sitemap.xml file to include links to all doctors and patients you have in the database, you can do so like this:

    in routes.php file..

    Route::get("sitemap.xml", array(
        "as"   => "sitemap",
        "uses" => "HomeController@sitemap", // or any other controller you want to use
    ));
    

    in HomeController.php file (if you decided to use HomeController)..

    public function sitemap()
    {
        $doctors = Doctor::remember(59) // chach this query for 59 minutes
            ->select(["id", "updated_at"]) 
            // you may want to add where clauses here according to your needs
            ->orderBy("id", "desc")
            ->take(50000) // each Sitemap file must have no more than 50,000 URLs and must be no larger than 10MB
            ->get();
    
        $patients = Patient::remember(59) // chach this query for 59 minutes
            ->select(["id", "updated_at"]) 
            // you may want to add where clauses here according to your needs
            ->orderBy("id", "desc")
            ->take(50000) // each Sitemap file must have no more than 50,000 URLs and must be no larger than 10MB
            ->get();
    
        $content = View::make('sitemap', ['doctors' => $doctors, 'patients' => $patients]);
        return Response::make($content)->header('Content-Type', 'text/xml;charset=utf-8');
    }
    

    in views/sitemap.blade.php file..

    <?php echo '<?xml version="1.0" encoding="UTF-8"?>' ?>
    
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach($doctors as $doctor)
        <url>
            <loc>{{ URL::route("doctors.show", [$doctor->id]) }}</loc>
            <lastmod>{{ gmdate(DateTime::W3C, strtotime($doctor->updated_at)) }}</lastmod>
            <changefreq>daily</changefreq>
            <priority>1.0</priority>
        </url>
    @endforeach
    
    @foreach($patients as $patient)
        <url>
            <loc>{{ URL::route("patients.show", [$patient->id]) }}</loc>
            <lastmod>{{ gmdate(DateTime::W3C, strtotime($patient->updated_at)) }}</lastmod>
            <changefreq>daily</changefreq>
            <priority>1.0</priority>
        </url>
    @endforeach
    </urlset>
    
    0 讨论(0)
  • 2020-12-14 14:16

    check https://github.com/RoumenDamianoff/laravel-sitemap

    A simple sitemap generator for Laravel 4.

    Route::get('sitemap', function(){
    
        // create new sitemap object
        $sitemap = App::make("sitemap");
    
        // set cache (key (string), duration in minutes (Carbon|Datetime|int), turn on/off (boolean))
        // by default cache is disabled
        $sitemap->setCache('laravel.sitemap', 3600);
    
        // check if there is cached sitemap and build new only if is not
        if (!$sitemap->isCached())
        {
             // add item to the sitemap (url, date, priority, freq)
             $sitemap->add(URL::to('/'), '2012-08-25T20:10:00+02:00', '1.0', 'daily');
             $sitemap->add(URL::to('page'), '2012-08-26T12:30:00+02:00', '0.9', 'monthly');
    
             // get all posts from db
             $posts = DB::table('posts')->orderBy('created_at', 'desc')->get();
    
             // add every post to the sitemap
             foreach ($posts as $post)
             {
                $sitemap->add($post->slug, $post->modified, $post->priority, $post->freq);
             }
        }
    
        // show your sitemap (options: 'xml' (default), 'html', 'txt', 'ror-rss', 'ror-rdf')
        return $sitemap->render('xml');
    
    });
    

    i have used it. works great!

    update #1

    to clear the confusion, let's take an example.

    let's say i have a blog table with id, title, blog

    i have the route as, Route::get('blog/{blog}',['as' => 'blog.show', 'uses' => 'Blog@show'];

    first i will fetch the content, by $blogs = DB::table('blog')->get();

    $blogs will contain the results.

    i will just loop,

    foreach($blogs as $i)
    {
         $sitemap->add(route('blog.show',[$i->title]), '2014-11-11', '1.0','daily');
    }
    

    all my blogs are added in the sitemap.

    0 讨论(0)
提交回复
热议问题