понедельник, 4 сентября 2017 г.

Laravel. Блог. Удалим связи при удалении поста

Реализуем при удалении поста удаление всех связей в категориями и тегами.


Сделаем сохранение поста с временной меткой.
Идем в модель \app\Model\user\post.php

public function tags() {
return $this->belongsToMany('App\Model\user\tag', 'post_tags')->withTimestamps(); // post_tags - имя таблицы
}

public function categories() {
return $this->belongsToMany('App\Model\user\category', 'category_posts')->withTimestamps();
}
}

Добавим при редактировании постов вывод выбранных тэгов и категорий.
app\Http\Controllers\Admin\PostController.php

public function edit($id)
{
$post = post::with('tags', 'categories')->where('id', $id)->first();
$tags = tag::all();
$categories = category::all();
return view('admin.post.edit', compact('post', 'tags', 'categories'));
}

Идем в шаблон \resources\views\admin\post\edit.blade.php
и выведем теги и категории.
<div class="form-group" style="margin-top: 18px">
<label>Select Tags</label>
<select class="form-control select2" multiple="multiple" data-placeholder="Select a State"
style="width: 100%;" name="tags[]">
@foreach($tags as $tag)
<option value="{{ $tag->id }}"
@foreach ($post->tags as $postTag)
@if ($postTag->id == $tag->id)
selected
@endif
@endforeach
>{{ $tag->name}}</option>
@endforeach
</select>
</div>
<div class="form-group" style="margin-top: 18px">
<label>Select Category</label>
<select class="form-control select2" multiple="multiple" data-placeholder="Select a State"
style="width: 100%;" name="categories[]">
@foreach($categories as $category)
<option value="{{ $category->id }}"
@foreach ($post->categories as $postCategory)
@if ($postCategory->id == $category->id)
selected
@endif
@endforeach
>{{ $category->name}}</option>
@endforeach
</select>
</div>

Изменим миграцию для БД.
Идем в \database\migrations\2017_08_27_131008_create_category_posts_table.php
Нам не нужен инкремент. Поэтому убираем строку: $table->increments('id');
public function up()
{
Schema::create('category_posts', function (Blueprint $table) {
$table->integer('post_id')->unsigned()->index();
$table->integer('category_id')->unsigned()->index();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
}

Обновим БД: php artisan migrate:refresh

Изменим миграцию для БД.
Идем в \database\migrations\2017_08_27_131510_create_post_tags_table.php
public function up()
{
Schema::create('post_tags', function (Blueprint $table) {
$table->integer('post_id')->unsigned()->index();
$table->integer('tag_id')->unsigned()->index();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
}

Обновим БД: php artisan migrate:refresh

Идем в \database\migrations\2017_08_27_124709_create_posts_table.php
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->string('subtitle', 100);
$table->string('slug', 100);
$table->text('body');
$table->boolean('status')->nullable();
$table->integer('posted_by')->nullable();
$table->string('image')->nullable();
$table->integer('like')->nullable();
$table->integer('dislike')->nullable();
$table->timestamps();
});
}

Обновим БД: php artisan migrate:refresh

Добавим текстовой редактор к форме.
Откроем Row files\admin\pages\forms\editors.html
Скопируем:
<script src="../../bower_components/ckeditor/ckeditor.js"></script>

Скопируем скрипт:
$(function () {
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace('editor1')
//bootstrap WYSIHTML5 - text editor
$('.textarea').wysihtml5()
})

И вставим в \resources\views\admin\layouts\footer.blade.php
<script src="{{ asset('admin/bower_components/ckeditor/ckeditor.js') }}"></script>

В шаблоне создания поста и редактирования поста присвоим textarea id="editor1"
Удалим класс у textarea и value.
Будет так:
<textarea name="body" style="width: 100%; height: 500px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;" id="editor1"></textarea>

Перенесем текстовой редактор только в шаблоны post.blade.php и edit.blade.php из папки resources\views\admin\post

<script src="{{ asset('admin/bower_components/ckeditor/ckeditor.js') }}"></script>
<script>
$(function () {
CKEDITOR.replace('editor1')
$('.textarea').wysihtml5()
});
</script>

Код для edit.blade.php

@extends('admin.layouts.app')

@section('headSection')
<link rel="stylesheet" href="{{ asset('admin/bower_components/select2/dist/css/select2.min.css') }}" />
@endsection
@section('main-content')
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Text Editors
<small>Advanced form element</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li><a href="#">Forms</a></li>
<li class="active">Editors</li>
</ol>
</section>

<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Titles</h3>
</div>
@include('includes.messages')
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{ route('post.update', $post->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<div class="box-body">
<div class="col-lg-6">
<div class="form-group">
<label for="title">Post title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title" value="{{ $post->title }}">
</div>
<div class="form-group">
<label for="subtitle">Post Sub Title</label>
<input type="text" class="form-control" id="subtitle" name="subtitle" placeholder="Sub Title" value="{{ $post->subtitle }}">
</div>
<div class="form-group">
<label for="slug">Post Slug</label>
<input type="text" class="form-control" id="slug" name="slug" placeholder="Post Slug" value="{{ $post->slug }}">
</div>
</div>
<div class="col-lg-6">
<br />
<div class="form-group">
<div class="pull-right">
<label for="image">File input</label>
<input type="file" name="image" id="image">
</div>
<div class="checkbox pull-left">
<label>
<input type="checkbox" name="status" value="1" @if ($post->status == 1) {{'checked'}} @endif> Publish
</label>
</div>
</div>
<br />
<div class="form-group" style="margin-top: 18px">
<label>Select Tags</label>
<select class="form-control select2" multiple="multiple" data-placeholder="Select a State"
style="width: 100%;" name="tags[]">
@foreach($tags as $tag)
<option value="{{ $tag->id }}"
@foreach ($post->tags as $postTag)
@if ($postTag->id == $tag->id)
selected
@endif
@endforeach
>{{ $tag->name}}</option>
@endforeach
</select>
</div>
<div class="form-group" style="margin-top: 18px">
<label>Select Category</label>
<select class="form-control select2" multiple="multiple" data-placeholder="Select a State"
style="width: 100%;" name="categories[]">
@foreach($categories as $category)
<option value="{{ $category->id }}"
@foreach ($post->categories as $postCategory)
@if ($postCategory->id == $category->id)
selected
@endif
@endforeach
>{{ $category->name}}</option>
@endforeach
</select>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Write Post Body
<small>Simple and fast</small>
</h3>
</div>
<!-- /.box-header -->
<div class="box-body pad">
<textarea name="body" style="width: 100%; height: 500px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;" id="editor1">{{ $post->body }}</textarea>
</div>

<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<a type="button" href="{{ route('post.index') }}" class="btn btn-warning">Back</a>
</div>
</form>
</div>
<!-- /.box -->
</div>
<!-- /.col-->
</div>
<!-- ./row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
@endsection

@section('footerSection')
<script src="{{ asset('admin/bower_components/select2/dist/js/select2.full.min.js') }}"></script>
<script>
$(document).ready(function() {
$('.select2').select2();
});
</script>
<script src="{{ asset('admin/bower_components/ckeditor/ckeditor.js') }}"></script>
<script>
$(function () {
CKEDITOR.replace('editor1')
$('.textarea').wysihtml5()
});
</script>

@endsection

Комментариев нет:

Отправить комментарий

Materialize-css. Футер

Сделаем футер и прижмем к низу страницы. Документация: https://materializecss.com/footer.html