Laravel Create a global function or helper that can be used throughout the entire project.
This is how to create laravel global function or laravel helper that can be used throughout the entire project.
First, create a helper.php file if you don't have one already. location app/Http/helpers.php<?php // app/Http/helpers.php if (!function_exists('generateKeywords')) { /** * Generate keywords from a given title. * * @param string $title * @return string */ function generateKeywords($title) { // Convert title to lowercase $title = strtolower($title); // Remove non-alphanumeric characters except spaces $title = preg_replace('/[^a-zA-Z0-9\s]/', '', $title); // Replace spaces with commas return str_replace(' ', ',', $title); } }
Ensure that the helper file is loaded by adding it to the composer.json file under the autoload section:"autoload": { "files": [ "app/Http/helpers.php" ] }
Runcomposer dump-autoload
to make sure the new helper file is loaded.
to use it in .blade file<meta name="keywords" content="{{ generateKeywords($blog->title) }}">
Last update on Jul 07, 2024
Tags: laravel
Back to PostsComments
No comments yet.