Как поставить slug в laravel 5.5 без применения сторонних решений?

Обсуждение серверного программирования.

Модераторы: Duncon, Yurich

Ответить
Владимир.Абрамович
Сообщения: 0
Зарегистрирован: 04 мар 2018, 09:49

04 мар 2018, 09:53

Подскажите как в данном контроллере сделать так, чтобы slug автоматически добавлялся в базу, а не выскакивала ошибка:

Код: Выделить всё

SQLSTATE[HY000]: General error: 1364 Field 'slug' doesn't have a default value (SQL: insert into `posts` (`title`, `date`, `description`, `content`, `user_id`, `updated_at`, `created_at`) values (Статья 4444, 2018-03-04, <p>Супер статья которая не опубликуется</p>, <p>Полюбому не опубликуется</p>, 10, 2018-03-03 21:36:45, 2018-03-03 21:36:45))
Хочу отметить, что отсидел за гуглом 4 часа, понаходил кучу разной информации, но нигде нет конкретики. Просто тупо

Код: Выделить всё

$title = str_slug('Laravel 5 Framework', '-');
 
Грубо говоря, все сводится к данной строке или к еще более старым непонятным вариантм. Но куда её вставить чтобы она работала в моем конкретном случае? Как бы я ни пытался какие комбинации и хитрости делать, ничего не выходит.

Необходимо, чтобы title преобразовывался в slug и к нему прибавлялся id статьи.
По принципу примерно такому:

Код: Выделить всё

  if (empty(Post::find(DB::table('posts')->max('id'))))
                $last_id = 0;
            else
                $last_id = Post::find(DB::table('posts')->max('id'))->id;
 
            $last_id++;
'slug' => str_slug($title['title']) . "-" . $last_id, 
Вот собственно код контроллера статей:

Код: Выделить всё

<?php
 
namespace App\Http\Controllers\Admin;
 
use App\Post;
use App\Chainword;
use App\Category;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
 
class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
 
 
    public function index()
    {
        $posts = Post::all();
        return view('admin.posts.index', ['posts'=>$posts]);
    }
 
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = Category: :p luck('title', 'id')->all();
        $chainwords = Chainword: :p luck('title', 'id')->all();
 
        return view('admin.posts.create', compact(
            'categories',
            'chainwords'
        ));
 
    }
 
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
 
    {
      $this->validate($request, [
            'title' =>'required',
            'content' => 'required',
            'date' => 'required',
            'image' => 'nullable|image'
        ]);
 
 
        $post = Post::add($request->all());
        $post->uploadImage($request->file('image'));
        $post->setCategory($request->get('category_id'));
        $post->setChainwords($request->get('chainwords'));
        $post->toggleStatus($request->get('status'));
        $post->toggleFeatured($request->get('is_featured'));
 
        return redirect()->route('posts.index');
    }
 
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::find($id);
        $categories = Category: :p luck('title', 'id')->all();
        $chainwords = Chainword: :p luck('title', 'id')->all();
        $selectedChainwords = $post->chainwords->pluck('id')->all();
 
        return view('admin.posts.edit', compact(
            'categories',
            'chainwords',
            'post',
            'selectedChainwords'
        ));
    }
 
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' =>'required',
            'content' => 'required',
            'date' => 'required',
            'image' => 'nullable|image'
        ]);
 
        $post = Post::find($id);
        $post->edit($request->all());
        $post->uploadImage($request->file('image'));
        $post->setCategory($request->get('category_id'));
        $post->setChainwords($request->get('chainwords'));
        $post->toggleStatus($request->get('status'));
        $post->toggleFeatured($request->get('is_featured'));
 
        return redirect()->route('posts.index');
    }
 
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Post::find($id)->remove();
        return redirect()->route('posts.index');
    }
 
 
} 
Ответить