Friday, 25 December 2020

How to create shortcode in laravel

1. Create a middleware name PostShortCodeMiddleware

2. Add this middleware in the kernal file.

3. Create a shortcode.php and shorcodeurl.php in view folder.

4. Place the shortcode in any view file. I have placed it in home.blade.php
 {user_list}
{user_email}

<?php
namespace App\Http\Middleware;

use Closure;
use App\Post;
use DB;
use Illuminate\Http\Response;
class PostShortCodeMiddleware
{   
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if(!method_exists($response, 'content')):
            return $response;
        endif;
           
    if(method_exists($response, 'content')){       
        $posts =  DB::table('users')->select()->get();       
        $postslug =  DB::table('users')->select('email')->get();       
        $content = str_replace(array('{user_list}', '{user_email}'), array(view('posts.shortcode',['posts' => $posts]),  view('posts.shortcodeurl',['posts' => $postslug])), $response->content());
        $response->setContent($content);
        return $response;
    }       
  }
}

Add in the Middleware
protected $middleware = [
.......
        \App\Http\Middleware\PostShortCodeMiddleware::class,       
......       
          ];

shortcode.php

<table class="table table-bordered data-table">
  <thead>
    <tr>
      <th width="50px">ID</th>
      <th>Name</th>
      <th>Email</th>     
      <th>Created</th>
      <th>Updated</th>            
    </tr>
  </thead>
  <tbody>  
  <?php foreach ($posts as $post)  {?>
  <tr>
    <td><?php echo $post->id; ?></td>
    <td><?php echo $post->name; ?></td>
    <td><?php echo $post->email; ?></td>
    <td><?php echo $post->created_at; ?></td>        
    <td><?php echo $post->updated_at; ?></td>        
  </tr>
  <?php } ?>
  </tbody>  
</table>

shortcodeurl.php

<table class="table table-bordered data-table">
  <thead>
    <tr>
      <th>User Email</th>
    </tr>
  </thead>
  <tbody>  
  <?php foreach ($posts as $post)  {?>
  <tr>
    <td><?php echo $post->email; ?></td>    
  </tr>
  <?php } ?>
  </tbody>  
</table>

2 comments:

  1. Nice Article!! I Really Appreciate your Content. This Article is about Rollback Migration Laravel. Here I have given How to Create a Rollback Migration in Laravel?

    Rollback Migration Laravel

    ReplyDelete

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...