Download the PHP package shammaa/laravel-seo without Composer
On this page you can find all versions of the php package shammaa/laravel-seo. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download shammaa/laravel-seo
More information about shammaa/laravel-seo
Files in shammaa/laravel-seo
Package laravel-seo
Short Description Professional SEO package for Laravel with support for OpenGraph, Twitter Cards, LinkedIn, and Schema.org structured data
License MIT
Informations about the package laravel-seo
Laravel SEO Package
Professional SEO package for Laravel with comprehensive support for OpenGraph, Twitter Cards, LinkedIn, Schema.org structured data, multilingual SEO, performance optimization, analytics integration, and much more.
Table of Contents
- Features
- Installation
- Configuration
- Quick Start
- Usage Guide
- Model Integration
- Complete Guide - Full Controller & Model Examples
- Advanced Features
- Configuration Reference
- API Reference
- Examples
- Troubleshooting
- Best Practices
- Requirements
- License
Features
Core SEO Features
- ✅ Meta Tags - Title, Description, Keywords, Robots, Canonical
- ✅ OpenGraph Tags - Complete Facebook sharing support
- ✅ Twitter Cards - Summary and large image cards with reading time
- ✅ LinkedIn Cards - OpenGraph compatible
- ✅ Article Tags - Automatic article:tag generation from model relationships
Schema.org Structured Data (JSON-LD) - 22+ Types
Core Schemas:
- ✅ NewsArticle - For blog posts and articles with author, publisher, dates
- ✅ Product - For e-commerce products with price, offers, ratings, shipping
- ✅ Offer - Enhanced with shipping details and return policy
- ✅ AggregateRating - For product ratings from multiple reviews
- ✅ Brand - For product brands
- ✅ WebPage - For all page types
- ✅ BreadcrumbList - Automatic breadcrumb navigation
- ✅ VideoObject - Enhanced with duration, contentUrl, interaction statistics
- ✅ WebSite - For homepage with search action
- ✅ Organization - Complete organization schema
- ✅ CollectionPage - For category pages
- ✅ FAQPage - For articles with frequently asked questions
- ✅ HowTo - For tutorial and instructional articles
- ✅ Review - For product and service reviews with ratings
- ✅ Event - For event announcements and coverage
New Advanced Schemas:
- ✅ Course - For educational courses with provider, instances, ratings
- ✅ Recipe - For recipes with ingredients, instructions, nutrition info
- ✅ JobPosting - For job listings with salary, location, requirements
- ✅ LocalBusiness - For local businesses with address, geo, hours
- ✅ SoftwareApplication - For apps with ratings, OS, pricing
- ✅ Book - For books with ISBN, author, publisher
- ✅ Movie - For movies with cast, director, ratings
- ✅ Podcast - For podcasts with episodes, author, publisher
Advanced Features
- ✅ Multilingual Support - Hreflang tags for multiple languages
- ✅ Reading Time - Automatic calculation and display in Twitter Cards and Schema
- ✅ AMP Support - Automatic AMP link generation
- ✅ RSS/Atom Feeds - Feed link support
- ✅ Pagination - Prev/Next link support
- ✅ Performance Optimization - DNS Prefetch, Preconnect, Preload, Prefetch, Prerender, Modulepreload
- ✅ Mobile Optimization - Theme color, Apple mobile web app, manifest
- ✅ Security Headers - CSP, Referrer Policy, X-Frame-Options
- ✅ Analytics Integration - Google Analytics 4, GTM, Yandex Metrica, Facebook Pixel
- ✅ Image Optimization - Lazy loading configuration support
- ✅ Geo-targeting - Geographic meta tags for location-based SEO
- ✅ Social Media - Pinterest Rich Pins, WhatsApp, Telegram optimization
- ✅ Commands -
seo:test-schemaandseo:health-checkfor validation
Developer Experience
- ✅ Easy Facade API - Simple, fluent interface
- ✅ Fully Configurable - Comprehensive config file
- ✅ Automatic Detection - Smart model attribute detection
- ✅ Model Trait - Automatic SEO data extraction from models
- ✅ Extensible - Easy to add custom schemas
Installation
Install via Composer
That's it! The package will be installed automatically.
Publish Configuration
This creates config/seo.php where you can configure all SEO settings.
Step 4: Configure Basic Settings
Edit config/seo.php and set your site information:
Dynamic Site Data from Database (Recommended)
Instead of hardcoding site information in the config file, you can load it dynamically from your database. This is useful when:
- You have a CMS with editable site settings
- You need to change site name/description without deploying
- You want to include social media links dynamically
Step 1: Register the resolver in your Service Provider:
Step 2: The resolver data automatically:
- ✅ Overrides config values
- ✅ Populates
og:site_name,publisher,author - ✅ Adds
sameAslinks to Organization and NewsArticle schemas - ✅ Is cached for performance (configurable TTL)
Clearing cache after settings update:
Quick Start
Basic Usage
In your controller:
In your Blade layout (resources/views/layouts/app.blade.php):
That's it! The package automatically generates all SEO tags.
Usage Guide
Page Types
Home Page
Post/Article Page
Category Page
Product Page (E-commerce)
Product Schema automatically includes:
- Product name, description, images
- SKU, MPN, GTIN
- Brand information
- Price and offers
- Availability status
- Aggregate ratings (from reviews)
- Product properties (color, size, material, etc.)
Search Page
Tag Page
Author Page
Archive Page
Static Page
Custom Page Type
Author Handling
The package automatically detects the author from your model relationships. It checks for relationships named: writer, author, user, or creator.
If the relationship is found, it will generate a rich Person schema with the author's name, image, and URL, instead of the generic Organization schema.
Manually Setting Author (withAuthor)
If you need to manually specify the author, or override the author's URL/Image without verifying model methods, you can use withAuthor() with extra arguments:
Advanced Schema Usage
Video Schema
For pages containing a main video:
Automatic Detection:
If your model has a video_url attribute or accessor, the package automatically adds the Video Schema.
FAQ Schema
For articles with frequently asked questions:
From Database (with HasSEO trait):
HowTo Schema
For tutorial and instructional articles:
Simple Steps:
Detailed Steps:
From Database (with HasSEO trait):
Review Schema
For product and service reviews:
From Database (with HasSEO trait):
Event Schema
For event announcements and coverage:
From Database (with HasSEO trait):
Breadcrumb Usage
The breadcrumb is automatically generated for post and category page types.
Method 1: Using the shared variable (Automatic)
After calling SEO::set(), breadcrumb items are automatically shared with the view:
Method 2: Using the Facade method
Method 3: Using the included view component
The breadcrumb view includes Schema.org microdata for SEO.
Chaining Multiple Schemas
You can chain multiple schema types for a single page:
New Advanced Schemas - Complete Guide
Course Schema
Perfect for educational websites, online courses, and training platforms:
Recipe Schema
Ideal for food blogs, recipe websites, and cooking platforms:
JobPosting Schema
Perfect for job boards and recruitment websites:
LocalBusiness Schema
Great for local businesses, restaurants, shops, and service providers:
SoftwareApplication Schema
Perfect for app stores, software marketplaces, and SaaS platforms:
Book Schema
Ideal for bookstores, libraries, and publishing websites:
Movie Schema
Perfect for movie databases, streaming platforms, and entertainment sites:
Podcast Schema
Great for podcast platforms and audio content websites:
Enhanced Video Schema
Improved VideoObject with additional features:
Geo-targeting
Add geographic targeting meta tags for location-based SEO:
This automatically generates:
geo.regionmeta taggeo.placenamemeta taggeo.positionmeta tagICBMmeta tag
Social Media Optimization
Pinterest Rich Pins
WhatsApp & Telegram
Both WhatsApp and Telegram use OpenGraph tags, so they work automatically. The package optimizes images for better previews.
Performance Optimization (Enhanced)
Prefetch, Prerender, and Modulepreload
Commands
Test Schema
Test your JSON-LD schemas:
This command:
- Fetches the page HTML
- Extracts all JSON-LD schemas
- Validates JSON structure
- Displays schema types and status
Health Check
Check your SEO configuration:
This command checks:
- ✅ Site configuration (name, description, URL)
- ✅ Social media settings (Twitter, Facebook)
- ✅ Analytics setup (GA4, GTM)
- ✅ Multilingual configuration
- ✅ Organization schema
- ✅ Provides a health score (0-100%)
Complete Guide
For complete examples of Controller and Model integration for all page types, see:
- COMPLETE_GUIDE.md - Comprehensive guide with explanations
- EXAMPLES_TEST.md - Ready-to-use code examples you can copy and paste
These guides include:
- ✅ Full Model examples for all page types
- ✅ Full Controller examples
- ✅ Migration examples
- ✅ Route examples
- ✅ View examples
- ✅ What gets generated automatically
- ✅ Advanced examples
- ✅ View integration
- ✅ Best practices
- ✅ Troubleshooting
- ✅ Testing checklist
Model Integration
The package provides a professional HasSEO trait that automatically detects and extracts SEO data from your models.
Quick Setup
Step 1: Add Trait to Model
Step 2: Use in Controller
The library automatically:
- ✅ Loads required relationships (eager loading)
- ✅ Detects FAQs from relationship or JSON column
- ✅ Detects HowTo steps from relationship or JSON column
- ✅ Detects Review data from relationship or attributes
- ✅ Detects Event data from relationship or attributes
- ✅ Extracts all SEO data (title, description, image, etc.)
Customizing Field Mappings
Each model can define its own field names:
Example: Different Model Structure
Customizing Relationship Loading
You can customize which relationships are loaded:
Overriding Methods
You can override methods for custom logic:
Model Requirements
The package automatically detects model attributes. Here's what it looks for:
Post Model
- Title:
title,name - Description:
content,text,description - Image:
photo,image,thumbnail - Dates:
created_at,published_at,updated_at,modified_at - Relationships:
writer,categories,tags,faqs,steps,review,event - Optional:
slug,video_url
Category Model
- Name:
name,title - Description:
description(optional) - Image:
photo,image,thumbnail(optional) - Relationships:
parent(optional, for breadcrumbs) - Method:
route()(optional, for breadcrumb URLs)
Product Model (E-commerce)
- Name:
name,title,product_name - Description:
description,product_description - Image:
image,photo,product_image - Price:
price,sale_price,current_price - Currency:
currency,price_currency(default: USD) - Availability:
availability,in_stock,stock_quantity - SKU:
sku(optional) - MPN:
mpn(optional) - GTIN:
gtin(optional) - Condition:
condition(optional) - Relationships:
brand,category,reviews - Properties:
color,size,material,weight,height,width,depth(optional)
Tag Model
- Name:
name,title - Method:
route()(optional, for breadcrumb URLs)
Author Model
- Name:
name,username,title - Method:
route()(optional, for breadcrumb URLs)
Archive (String or Object)
- String: Date string like
"2024-01"or"January 2024" - Object: Model with
name,title, ordateattribute
Page Model (Static Pages)
- Name:
title,name - Relationships:
parent(optional, for breadcrumbs) - Method:
route()(optional, for breadcrumb URLs)
Advanced Features
Multilingual & Hreflang Support
Enable multilingual SEO with hreflang tags:
Custom URL Generator (via Static Method - Recommended):
⚠️ Important: Do NOT set url_generator to a closure in your config file if you plan to use php artisan config:cache. Closures cannot be serialized and will cause the cache command to fail.
Instead, register a global custom URL generator in your Service Provider:
Why use the static method?
- ✅ Works with
php artisan config:cache - ✅ Can be registered in Service Provider
- ✅ Takes priority over config
url_generator - ✅ More flexible and maintainable
Legacy Config Method (Not Recommended):
If you're not using config:cache, you can still use the config method (for backward compatibility):
Reading Time
Reading time is automatically calculated and displayed:
Translation Format:
- Use
:minutesplaceholder for the number of minutes - The library automatically replaces
:minuteswith the calculated value - If a translation for the current locale is not found, it falls back to English
Customization:
Reading time is automatically:
- Added to Twitter Cards as
twitter:label1andtwitter:data1 - Added to NewsArticle Schema as
timeRequired(ISO 8601 format: PT5M)
Using ReadingTimeCalculator directly:
AMP (Accelerated Mobile Pages) Support
⚠️ Important: Do NOT set url_generator to a closure in your config file if you plan to use php artisan config:cache. Closures cannot be serialized and will cause the cache command to fail.
Recommended approach: Register the URL generator in your Service Provider:
Config file (optional, for simple cases):
When enabled, automatically adds <link rel="amphtml"> tag for post pages.
RSS/Atom Feeds
Adds <link rel="alternate" type="application/rss+xml"> tag.
Pagination Support
To ensure perfect SEO for paginated pages (Canonical, Prev/Next, Robots), simply pass your Paginator instance to the library using withPagination():
The package provides comprehensive pagination SEO support:
Canonical URL Behavior
| Page | URL | Canonical |
|---|---|---|
| First page | /articles |
/articles |
| Page 2 | /articles?page=2 |
/articles?page=2 (Self-referencing) |
| Page 2 (config to first) | /articles?page=2 |
/articles |
Robots Directive
| Setting | Page 1 | Page 2+ |
|---|---|---|
noindex_pagination: false |
index, follow |
index, follow |
noindex_pagination: true |
index, follow |
noindex, follow |
Recommendation: Use canonical_to_first: false (default) to ensure paginated content is indexed. Only enable canonical_to_first: true if you have identical content across pages (which is rare for archives).
Prev/Next Links
Automatically adds <link rel="prev"> and <link rel="next"> tags if your model has previous and next relationships:
Model Example:
Performance Optimization
Improve page load speed with resource hints:
Mobile Optimization
Security Headers
Analytics Integration
Support for multiple analytics platforms:
All analytics scripts are automatically injected when configured.
Image Rendering Configuration
Configure image loading behavior:
Dynamic Site Configuration (Database)
For projects that store site settings in a database, use the Dynamic Site Resolver to fetch settings automatically.
Step 1: Add the Interface to Your Model (Optional but Recommended)
Step 2: Register in AppServiceProvider
That's it! Now your SEO settings come from the database.
Benefits:
- ✅ Simple: Just return an array with
name,description,logo - ✅ Cached: Results are automatically cached (24 hours by default)
- ✅ Fallback: Missing keys fall back to
config/seo.phpvalues
Configuration Reference
Site Information
Image Route
If you're using an image processing package (like laravel-smart-glide):
Social Media
Organization Schema
Fallback Texts
Customize default texts:
Environment Variables
You can configure SEO via environment variables:
Basic Settings
Social Media
Multilingual
Reading Time
AMP
RSS
Performance
Mobile
Security
Analytics
Organization
API Reference
Facade Methods
SEO::for(string $pageType, $model = null)
Set page type and model.
SEO::home()
Set page type to home.
SEO::post($model)
Set page type to post with model.
SEO::category($model)
Set page type to category with model.
SEO::search(array $params)
Set page type to search with query parameters.
SEO::set()
Generate and set all SEO tags. Must be called after setting page type.
SEO::render()
Render all SEO tags as HTML string. Automatically calls set() if not called.
SEO::breadcrumb()
Get breadcrumb items as array.
SEO::addFAQ(array $faqs)
Add FAQ schema. Returns self for chaining.
Parameters:
$faqs- Array of FAQ items, each withquestionandanswerkeys
SEO::addHowTo(string $name, array $steps, ?string $description = null, ?string $image = null)
Add HowTo schema. Returns self for chaining.
Parameters:
$name- Name of the HowTo$steps- Array of steps (strings or arrays withname,text,image,url)$description- Optional description$image- Optional image URL
SEO::addReview(string $itemName, float $ratingValue, float $bestRating = 5.0, ?string $reviewBody = null, ?string $authorName = null, ?string $datePublished = null)
Add Review schema. Returns self for chaining.
Parameters:
$itemName- Name of the item being reviewed$ratingValue- Rating value (e.g., 4.5)$bestRating- Best possible rating (default: 5.0)$reviewBody- Optional review text$authorName- Optional reviewer name$datePublished- Optional publication date (ISO 8601 format)
SEO::addEvent(string $name, string $startDate, ?string $endDate = null, ?string $description = null, ?string $locationName = null, ?string $locationAddress = null, ?string $image = null, ?string $organizerName = null, ?string $organizerUrl = null)
Add Event schema. Returns self for chaining.
Parameters:
$name- Event name$startDate- Start date (ISO 8601 format)$endDate- Optional end date (ISO 8601 format)$description- Optional description$locationName- Optional location name$locationAddress- Optional location address$image- Optional image URL$organizerName- Optional organizer name$organizerUrl- Optional organizer URL
SEO::product($model)
Set page type to product with model.
SEO::addProduct($model)
Add Product schema. Returns self for chaining. Automatically called when using SEO::product()->set().
Parameters:
$model- Product model with price, brand, category, etc.
SEO::addAggregateRating(float $ratingValue, int $ratingCount, float $bestRating = 5.0, float $worstRating = 1.0)
Add AggregateRating schema. Returns self for chaining.
Parameters:
$ratingValue- Average rating value (e.g., 4.5)$ratingCount- Number of ratings/reviews$bestRating- Best possible rating (default: 5.0)$worstRating- Worst possible rating (default: 1.0)
SEO::addBrand(string $name, ?string $logo = null, ?string $url = null)
Add Brand schema. Returns self for chaining.
Parameters:
$name- Brand name$logo- Optional brand logo URL$url- Optional brand website URL
HasSEO Trait Methods
getSEOFieldMap(): array
Define field mappings for your model. Override in your model.
getSEORelationships(): array
Define relationship names for your model. Override in your model.
getSEORelationshipsToLoad(): array
Define which relationships to eager load. Override in your model.
getSEOTitle(): ?string
Get SEO title from model.
getSEODescription(): ?string
Get SEO description from model.
getSEOImage(): ?string
Get SEO image from model.
getSEOKeywords(): array
Get SEO keywords from model (from tags and categories).
getSEOAuthor(): ?string
Get SEO author name from model.
getSEOPublishedAt(): ?string
Get published date in ISO 8601 format.
getSEOModifiedAt(): ?string
Get modified date in ISO 8601 format.
getSEOFAQs(): array
Get FAQs for FAQ schema. Override for custom logic.
getSEOHowToSteps(): array
Get HowTo steps. Override for custom logic.
getSEOReview(): ?array
Get Review data. Override for custom logic.
getSEOEvent(): ?array
Get Event data. Override for custom logic.
hasSEOFAQs(): bool
Check if model has FAQs.
hasSEOHowToSteps(): bool
Check if model has HowTo steps.
hasSEOReview(): bool
Check if model has Review data.
hasSEOEvent(): bool
Check if model has Event data.
Examples
Complete Example: Post with All Features
Example: Using HasSEO Trait
Example: Extracting Data from Database
Differences: Blog vs E-commerce
Blog/Article Website
Focus: Content, articles, news Schemas: NewsArticle, WebPage, BreadcrumbList Key Features:
- Article metadata (author, publisher, dates)
- Reading time
- Categories and tags
- FAQ, HowTo, Review, Event schemas
Example:
E-commerce Website
Focus: Products, sales, shopping Schemas: Product, Offer, AggregateRating, Brand Key Features:
- Product metadata (SKU, MPN, GTIN)
- Price and offers
- Availability status
- Aggregate ratings from reviews
- Brand information
- Product properties (color, size, material)
Example:
Hybrid Website (Both)
You can use both on the same website:
Troubleshooting
Tags Not Appearing
-
Check if
set()is called: -
Check if
render()is called in view: - Check config file:
Model Data Not Detected
-
Check field mappings:
- Check relationships:
Breadcrumb Not Showing
-
Check if breadcrumb is shared:
- Check model relationships:
- Post should have
categoriesrelationship - Category should have
parentrelationship androute()method
- Post should have
Reading Time Not Showing
-
Check if enabled:
- Check if model has content:
Schemas Not Auto-Detected
-
Check if HasSEO trait is used:
-
Check relationships:
- Check if relationships are loaded:
Config Cache Error (LogicException)
Error:
Cause:
This error occurs when you try to run php artisan config:cache after setting url_generator to a closure/function in your config file. Closures cannot be serialized.
Solution:
Use the static method MultilingualBuilder::urlGeneratorUsing() instead of setting a closure in the config file:
If you already cached config:
Best Practices
1. Use HasSEO Trait
Always use the HasSEO trait for automatic data extraction:
2. Define Field Mappings
Always define field mappings in your models:
3. Use Eager Loading
The library automatically eager loads relationships, but you can optimize:
4. Cache Site Data
Site data is cached by default (24 hours). Adjust if needed:
5. Use Environment Variables
Store sensitive data in .env:
6. Test Your Schemas
Use Google's Rich Results Test:
7. Validate JSON-LD
Use JSON-LD Playground:
8. Monitor Performance
Use performance optimization features:
How It Works
Automatic Detection
The package automatically detects model attributes:
- Title: Checks
title,nameattributes - Description: Checks
content,text,descriptionattributes - Image: Checks
photo,image,thumbnailattributes - Dates: Checks
created_at,published_at,updated_at,modified_at - Author: Checks
writerrelationship or uses site name - Categories: Checks
categoriesrelationship for breadcrumbs - Tags: Checks
tagsrelationship for article:tag meta tags - Video: Checks
video_urlfor VideoObject schema
Schema Generation Flow
- Page Type Detection: Determines page type (home, post, category, search)
- Data Extraction: Extracts data from model or config
- Meta Tags: Generates standard meta tags
- OpenGraph: Generates Facebook OpenGraph tags
- Twitter Cards: Generates Twitter Card tags with reading time
- Schemas: Generates appropriate JSON-LD schemas
- Additional Features: Adds multilingual, performance, analytics tags
Caching
Site data is cached for 24 hours by default (configurable via SEO_CACHE_TTL). This improves performance by avoiding repeated database queries.
View Sharing
The package automatically shares data with views:
$customSchemas- All JSON-LD schemas$breadcrumbs- Breadcrumb items (for post/category pages)$performanceTags- Performance optimization tags$analyticsTags- Analytics scripts$ampUrl- AMP URL (if enabled)$paginationLinks- Prev/Next links (if available)
Requirements
- PHP 8.1+
- Laravel 9.0+, 10.0+, 11.0+, or 12.0+
License
MIT
Author
Shadi Shammaa
Support
For issues, questions, or contributions, please visit the GitHub repository.
All versions of laravel-seo with dependencies
illuminate/support Version ^9.0|^10.0|^11.0|^12.0
illuminate/http Version ^9.0|^10.0|^11.0|^12.0
illuminate/view Version ^9.0|^10.0|^11.0|^12.0
illuminate/cache Version ^9.0|^10.0|^11.0|^12.0