How to generate Unique slug?
Model
File name : index.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
# verify and return custom slug string
public function slugify($text)
{
# remove ? mark from string
$slug = preg_replace('/\?/u', ' ', trim($text));
$slug = preg_replace('/\s+/u', '-', trim($slug));
# slug repeat check
$latest = $this->whereRaw("slug REGEXP '^{$slug}(-[0-9]+)?$'")
->latest('id')
->value('slug');
if($latest){
$pieces = explode('-', $latest);
$number = intval(end($pieces));
$slug .= '-' . ($number + 1);
}
return $slug;
}
}
Controller
File name : index.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Post;
class PostController extends Controller
{
public function store(Request $request)
{
$post = new Post();
//..............................
* my name is mahi => my-name-is-mahi
*/
$post->slug = $post->slugify($request->title); // unique slug generator
//..............................
$post->save();
}
}
How to generate slug in laravel?
first add the Str class to your Controller:
use Illuminate\Support\Str;
Then use the Str::slug method and pass in your title:
$slug = Str::slug('Your Awesome Blog Title', '-');
$slug = Str::slug($request->title, '-');
After that, you can store this in your database and later on retrieve your posts by slug rather than ID for example:
$post = Post::where('slug', $slug)->firstOrFail();
File name : index.php
<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Menu;
use DB;
use Illuminate\Support\Str;
class MenuController extends Controller
{
public function store(Request $request)
{
$request->validate([
'title' => 'required',
]);
$input = $request->all();
$input['parent_id'] = empty($input['parent_id']) ? 0 : $input['parent_id'];
// $slug = Str::slug($request->title, '-');
$input['slug'] = Str::slug($input['title'], '-');
Menu::create($input);
return back()->with('success', 'Menu added successfully.');
}
}
How to use Next & previous Button
File name : model.php
class TrendePost extends Model
{
public function next()
{
return $this->where(‘id’, ‘>’, $this->id)->orderBy(‘id’,’asc’)->first();
}
public function previous()
{
return $this->where(‘id’, ‘<’, $this->id)->orderBy(‘id’,’desc’)->first();
}
}
File name : controller.php
class TrendePostController extends Controller
{
public function show($slug, TrendePost $post)
{
$post = $post->where('slug',$slug)->first();
$next = $post->next();
$prev = $post->previous();
// write here you return blade login...
}
)
File name : blade view.php
$next = $post->next();
$prev = $post->previous();
Previous
Next