GithubHelp home page GithubHelp logo

eusonlito / laravel-meta Goto Github PK

View Code? Open in Web Editor NEW
195.0 9.0 82.0 322 KB

HTML Meta Tags management package available for for Laravel >= 5 (Including 10)

License: MIT License

PHP 3.97% JavaScript 66.41% CSS 29.62%
laravel meta tags php html

laravel-meta's Introduction

HTML Meta Tags management package available for Laravel >= 5 (Including 10)

Build Status Latest Stable Version Total Downloads License

With this package you can manage header Meta Tags from Laravel controllers.

If you want a Laravel <= 4.2 compatible version, please use v4.2 branch.

Installation

Begin by installing this package through Composer.

{
    "require": {
        "eusonlito/laravel-meta": "3.1.*"
    }
}

Laravel installation

// config/app.php

'providers' => [
    '...',
    Eusonlito\LaravelMeta\MetaServiceProvider::class
];

'aliases' => [
    '...',
    'Meta'    => Eusonlito\LaravelMeta\Facade::class,
];

Now you have a Meta facade available.

Publish the config file:

php artisan vendor:publish --provider="Eusonlito\LaravelMeta\MetaServiceProvider"

app/Http/Controllers/Controller.php

<?php namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

use Meta;

abstract class Controller extends BaseController
{
    use DispatchesCommands, ValidatesRequests;

    public function __construct()
    {
        # Default title
        Meta::title('This is default page title to complete section title');

        # Default robots
        Meta::set('robots', 'index,follow');

        # Default image
        Meta::set('image', asset('images/logo.png'));
    }
}

app/Http/Controllers/HomeController.php

<?php namespace App\Http\Controllers;

use Meta;

class HomeController extends Controller
{
    public function index()
    {
        # Section description
        Meta::set('title', 'You are at home');
        Meta::set('description', 'This is my home. Enjoy!');
        Meta::set('image', asset('images/home-logo.png'));

        return view('index');
    }

    public function detail()
    {
        # Section description
        Meta::set('title', 'This is a detail page');
        Meta::set('description', 'All about this detail page');

        # Remove previous images
        Meta::remove('image');

        # Add only this last image
        Meta::set('image', asset('images/detail-logo.png'));

        # Canonical URL
        Meta::set('canonical', 'http://example.com');

        return view('detail');
    }

    public function private()
    {
        # Section description
        Meta::set('title', 'Private Area');
        Meta::set('description', 'You shall not pass!');
        Meta::set('image', asset('images/locked-logo.png'));

        # Custom robots for this section
        Meta::set('robots', 'noindex,nofollow');

        return view('private');
    }
}

resources/views/html.php

<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />

        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="author" content="Lito - [email protected]" />

        <title>{!! Meta::get('title') !!}</title>

        {!! Meta::tag('robots') !!}

        {!! Meta::tag('site_name', 'My site') !!}
        {!! Meta::tag('url', Request::url()); !!}
        {!! Meta::tag('locale', 'en_EN') !!}

        {!! Meta::tag('title') !!}
        {!! Meta::tag('description') !!}

        {!! Meta::tag('canonical') !!}

        {{-- Print custom section images and a default image after that --}}
        {!! Meta::tag('image', asset('images/default-logo.png')) !!}
    </head>

    <body>
        ...
    </body>
</html>

Or you can use Blade directives:

<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />

        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="author" content="Lito - [email protected]" />

        <title>{!! Meta::get('title') !!}</title>

        @meta('robots')

        @meta('site_name', 'My site')
        @meta('url', Request::url())
        @meta('locale', 'en_EN')

        @meta('title')
        @meta('description')

        @meta('canonical')

        {{-- Print custom section images and a default image after that --}}
        @meta('image', asset('images/default-logo.png'))

        {{-- Or use @metas to get all tags at once --}}
        @metas
        
    </head>

    <body>
        ...
    </body>
</html>

MetaProduct / og:product

This will allow you to add product data to your meta data. See Open Graph product object

// resources/views/html.php

<head>
    ...
    {!! Meta::tag('type') !!} // this is needed for Meta Product to change the og:type to og:product
    {!! Meta::tag('product') !!}
</head>

Add your product data from your controller

<?php namespace App\Http\Controllers;

use Meta;

class ProductController extends Controller
{
    public function show()
    {
        # Add product meta
        Meta::set('product', [
            'price' => 100,
            'currency' => 'EUR',
        ]);
        
        # if multiple currencies just add more product metas
        Meta::set('product', [
            'price' => 100,
            'currency' => 'USD',
        ]);

        return view('index');
    }
}

Config

return [
    /*
    |--------------------------------------------------------------------------
    | Limit title meta tag length
    |--------------------------------------------------------------------------
    |
    | To best SEO implementation, limit tags.
    |
    */

    'title_limit' => 70,

    /*
    |--------------------------------------------------------------------------
    | Limit description meta tag length
    |--------------------------------------------------------------------------
    |
    | To best SEO implementation, limit tags.
    |
    */

    'description_limit' => 200,

    /*
    |--------------------------------------------------------------------------
    | Limit image meta tag quantity
    |--------------------------------------------------------------------------
    |
    | To best SEO implementation, limit tags.
    |
    */

    'image_limit' => 5,

    /*
    |--------------------------------------------------------------------------
    | Available Tag formats
    |--------------------------------------------------------------------------
    |
    | A list of tags formats to print with each definition
    |
    */

    'tags' => ['Tag', 'MetaName', 'MetaProperty', 'MetaProduct', 'TwitterCard'],
];

Using Meta outside Laravel

Controller

require __DIR__.'/vendor/autoload.php';

// Check default settings
$config = require __DIR__.'/src/config/config.php';

$Meta = new Eusonlito\LaravelMeta\Meta($config);

# Default title
$Meta->title('This is default page title to complete section title');

# Default robots
$Meta->set('robots', 'index,follow');

# Section description
$Meta->set('title', 'This is a detail page');
$Meta->set('description', 'All about this detail page');
$Meta->set('image', '/images/detail-logo.png');

# Canonical URL
$Meta->set('canonical', 'http://example.com');

Template

<title><?= $Meta->get('title'); ?></title>

<?= $Meta->tag('robots'); ?>

<?= $Meta->tag('site_name', 'My site'); ?>
<?= $Meta->tag('url', getenv('REQUEST_URI')); ?>
<?= $Meta->tag('locale', 'en_EN'); ?>

<?= $Meta->tag('title'); ?>
<?= $Meta->tag('description'); ?>

<?= $Meta->tag('canonical'); ?>

# Print custom section image and a default image after that
<?= $Meta->tag('image', '/images/default-logo.png'); ?>

Updates from 2.*

  • Meta::meta('title', 'Section Title') > Meta::set('title', 'Section Title')
  • Meta::meta('title') > Meta::get('title')
  • Meta::tagMetaName('title') > Meta::tag('title')
  • Meta::tagMetaProperty('title') > Meta::tag('title')

laravel-meta's People

Contributors

alexjoffroy avatar dalholm avatar eusonlito avatar hootlex avatar kkomelin avatar perents avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-meta's Issues

[Suggestion] Make facade detectable by Laravel Idea plugin for PhpStorm

Hello!

Currently this package does not let detect facade target with Laravel Idea Plugin, because it just returns an arbitrary string instead of FQCN.

Would you consider following?

use Illuminate\Support\Facades\Facade;

class Meta extends Facade
{
    protected static function getFacadeAccessor(): string
    {
        return \Eusonlito\LaravelMeta\Meta::class;
    }
}
        $this->app->singleton(Eusonlito\LaravelMeta\Meta::class, function () {
            return new Meta(config('meta'));
        });

end result is the same, cause this string is really not used for anything else than binding!

Is this supports Laravel 8?

Hi, I can't find any information about laravel version support, could you update to Laravel 8 and add dependencies to coposer.json?

Incompatible with ide-helper

The type hinting used in the Meta::__construct gets the package incompatible with barryvdh/laravel-ide-helper, which passes a null value to the constructor and throw an error.

php artisan ide-helper:generate

[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: Argument 1 passed to Eusonlito\LaravelMeta\Meta::__construct()
must be of the type array, null given, called in D:\Progetti\studioelps.com
\StudioElps\vendor\eusonlito\laravel-meta\src\Eusonlito\LaravelMeta\MetaSer
viceProvider.php on line 35

Bug with characters

Hi,
Something strange with some utf-8 characters (I'm french) :
In fact, with "é" no problem but with "à", I've got "�"...
Any idea ?
Thanks!

Meta::set('image', 'xxxx') not working

Meta::set is not working for image.

  • PHP 7.4.0
  • Laravel 7
>>> Meta::set('image', 'http://localhost:8000/media/1-17.png')
=> ""
>>> Meta::get('image')
=> []

Just a question about the app/Http/Controllers/Controller.php

in the document

app/Http/Controllers/Controller.php

<?php namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Meta;

abstract class Controller extends BaseController
{
    use DispatchesCommands, ValidatesRequests;

    public function __construct()
    {
        # Default title
        Meta::title('This is default page title to complete section title');

        # Default robots
        Meta::set('robots', 'index,follow');
    }
} 

should I replace my current Controller.php with this I am using laravel 5.2

and when I used this DispatchesCommands
Got

Trait 'Illuminate\Foundation\Bus\DispatchesCommands' not found

here is my complete Controller.php file and what I try

<?php
namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;

use Illuminate\Foundation\Bus\DispatchesCommands;
use Meta;

class Controller extends BaseController
{
    use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;

    use DispatchesCommands, ValidatesRequests;

    public function __construct()
    {
        # Default title
        Meta::title('This is default page title to complete section title');

        # Default robots
        Meta::set('robots', 'index,follow');
    }
}

Option to set image_base for absolute image URLs

I am using laravel mix for my images which generates a relative path to the image via mix().

I'm finding myself repetitively prepending env('APP_URL') in my meta::set('image','...') so my images are absolutely pathed.

Could we have a option in config.php for 'image_base' => env('APP_URL') to permit this functionality?

Thank you =)

Dependency injection mixed with Facade usage

I'm facing a problem when I inject the \Eusonlito\LaravelMeta\Meta instance in my controller and then trying to get the tags in my view (with the Facade).

Here's a basic example:

Route::get('/', function (\Eusonlito\LaravelMeta\Meta $meta) {
    $meta->set('title', 'Hello world');

    dd(Meta::get('title'));
});

As I expect this bit of code to dump 'Hello world', it actually dumps 'null'. It seems that the instance returned by the Meta Facade is not the same as the one retrieved by the injection mecanism.

When looking at the MetaServiceProvider, I first thought it requires to define an alias like this:

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Meta::class, function () {
            return new Meta(config('meta'));
        });

        $this->app->alias(Meta::class, 'meta');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [Meta::class, 'meta'];
    }

But still not working.

Anyone else facing this issue ?

How to prevent a second title tag from being rendered

Hello! Thank you for this library. I just have a bit of issue. I'm already handling the <title> tag myself so it would be great if this library didn't set it separately if I use:

Meta::title('Some title');

All I want is the meta title tag:

<meta name="title" content="Some title" />
<meta property="og:title" content="Some title" />
<meta name="twitter:title" content="Some title" />

Currently it's also rendering the title tag:

<title>Some title</title>

tagString() generates two tags

Hello!

In Meta.php tagString()s behaviour is rather irrational: it generates 1 property tag when called from tagMetaProperty() but two tags, 1 property and 1 name, when called from tagMetaName().

It's both confusing and inflexible – what if user ONLY wants to add a meta name tag? Moreover, why is tagMetaName() called so if it inserts both name and property?

You should either rename the function or remove lines 235-236 ;-)

Preventing unwanted duplicate tags

When trying to add twitter cards:

{!! Meta::tag('card') !!}

I am seeing the following rendered:

<meta name="card" content="Summary" />
<meta name="twitter:card" content="Summary" />

...when all I want is:

<meta name="twitter:card" content="Summary" />

I see some granularity was added in 2.0 but I don't see a way to call Meta::tagTwitterCard or similar.

Thank you.

No way to remove images?

Here's my use case -

LinkedIn only seems to grab the first og:image
I set a default "catch all" image in Controller.php
I set more specific images in controllers that extend Controller.php
I output images with {!! Meta::tag('image') !!}

Is there any way to -

Unset a previously set image? Or override an image? Or reverse the order of the images?

You're missing a critical step

Looks like you might be missing a piece in your readme when dealing with setting default values in Controller.php -

Your HomeController.php needs a

public function __construct()
    {
        parent::__construct();
    }

Otherwise your defaults don't get called

Can't set title, desciption with utf-8

hello, i am using utf-8 text to set value for title, description but i can't set value,
when i try set value to title, title can't display in browser

Meta::set('title', 'Tổng Hợp Tài Liệu Tiếng Nhật');
the result: can't display title.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.