Create Shortcode in Laravel Same as Wordpress
Shortcode is a way of generating specific html or part of html inside contents in page. We are familiar with wordpress where there is a feature called shortcode. Using that shortcode users can easily bind specific html content. It can be gallery, adsense block or readalso links.
Here in this blog we will create a shortcode that will generate a custom link inside blog description
Let's create ShortCodeServiceProvider
namespace App\Providers;
use App\AppSetting;
use App\Service\Front\ShortcodeService;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class ShortCodeServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
}
}Register article content also key in provider
public function register()
{
$this->shortCodeService = new ShortcodeService();
$this->shortCodeService->register('article_content_read_also', function ($params) {
$slug = $params['slug'];
$PostTitle = str_replace('-', ' ', $slug);
$PostTitle = ucfirst($PostTitle);
$route = route('view-post', $slug);
return "<div class='read-also-post-link'>
<a href=" . $route . " target='_blank'><i class='fa fa-arrow-right'></i> " . $PostTitle . "</a>
</div>";
});
}Below code should be added inside boot()
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->app->singleton('shortcode', function () {
return $this->shortCodeService;
});
}Final ShortCodeServiceProvider will be Like Below
namespace App\Providers;
use App\Service\Front\ShortcodeService;
use Illuminate\Support\ServiceProvider;
class ShortCodeServiceProvider extends ServiceProvider
{
protected ShortcodeService $shortCodeService;
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->shortCodeService = new ShortcodeService();
$this->shortCodeService->register('article_content_read_also', function ($params) {
$slug = $params['slug'];
$PostTitle = str_replace('-', ' ', $slug);
$PostTitle = ucfirst($PostTitle);
$route = route('view-post', $slug);
return "<div class='read-also-post-link'>
<a href=" . $route . " target='_blank'><i class='fa fa-arrow-right'></i> " . $PostTitle . "</a>
</div>";
});
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->app->singleton('shortcode', function () {
return $this->shortCodeService;
});
}
}Add Shortcode in your texteditor(ckeditor, tinymce, summernote)

Now final output in browser will look like this
