Ad

Laravel With Arabic Slugs

- 1 answer

i'm using Laravel 6 to build a blog application and the language of this app is Arabic but there is a problem with slug ,it looks like that Laravel doesn't support Arabic.

any idea to fix this?

Controller

public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    return view('content.post',compact('post'));
}

Store Method

public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = Str::slug($request->slug, '-');
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}

Route

Route::get('post/{slug}', '[email protected]')->name('post.show');
Ad

Answer

You can use this function

public function slug($string, $separator = '-') {
    if (is_null($string)) {
        return "";
    }

    $string = trim($string);

    $string = mb_strtolower($string, "UTF-8");;

    $string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

    $string = preg_replace("/[\s-]+/", " ", $string);

    $string = preg_replace("/[\s_]/", $separator, $string);

    return $string;
}
public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $this->slug($request->slug);
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}

It will make slug for each language arabic or english. and it will work fine.

Ad
source: stackoverflow.com
Ad