Skip to content

Instantly share code, notes, and snippets.

@platinize
Last active March 23, 2018 10:15
Show Gist options
  • Save platinize/0294ed715cb5aebf62dedbb18cfa6bc8 to your computer and use it in GitHub Desktop.
Save platinize/0294ed715cb5aebf62dedbb18cfa6bc8 to your computer and use it in GitHub Desktop.
Laravel_3_4
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNewsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('news', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 100);
$table->string('author', 60)->nullable();
$table->string('content', 12000)->nullable();
$table->string('img', 200)->nullable();
$table->dateTime('publiс_date')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('news');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ChangeNewsTitleColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('news', function (Blueprint $table) {
$table->string('title', 200)->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('news', function (Blueprint $table) {
$table->string('title', 100)->change();
});
}
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link href="../css/news/news.css" rel="stylesheet">
</head>
<h1>Админка</h1>
<p><a href="{{route('home')}}" class="home">На главную</a>
<table cellspacing="0" border="1" cellpadding="10" class="adminTable">
<tr>
<td colspan="{{$countColums}}" class="tableTitle"><span>Все новости</span></td>
<td colspan="2" class="tableTitle"><a href="{{route('addNews')}}">Добавить новость</a></td>
</tr>
<tr class="tableHead">
@foreach($colums as $entry)
@foreach($entry as $val)
<td>{{$val}}</td>
@endforeach
@endforeach
<td class="func">Редактировать</td>
<td class="func">Удалить</td>
</tr>
@foreach($full as $keyAll=>$entry)
<tr>
@foreach($entry as $key=>$val)
@if($key =='img' && $val != '' )
<td title="{{$val}}" style="padding:0"><img src='../../{{$val}}'></td>
@else
<td title="{{$val}}">{{$all{$keyAll}->$key}}</td>
@endif
@endforeach
<td><a href="{{route('updateNews', $entry->id)}}">Редактировать</a></td>
<td><a href="{{route('deleteNews', $entry->id)}}">Удалить</a></td>
</tr>
@endforeach
</table>
<div class="secondPag">{{$all->links()}}</div>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
@if(isset($news))<link href="../../../css/news/news.css" rel="stylesheet">@else<link href="../../css/news/news.css" rel="stylesheet">@endif
</head>
@if(isset($news))
<h1>Редактрирование новости "{{$news->title}}"(id{{$news->id}})</h1>
@else
<h1>Создание новости</h1>
@endif
<div class="newsForm">
<p><a href="{{route('admin')}}">Вернуться</a></p>
<form method="post" enctype="multipart/form-data">
<div><input type="hidden" name="id" value="@isset($news){{$news->id}}@endisset"></div>
<div>
<p>Название новсти</p>
<textarea rows="3" name="title" required>@isset($news){{$news->title}}@endisset</textarea>
</div>
<div>
<p>Автор</p>
<textarea rows="2" name="author" required>@isset($news){{$news->author}}@endisset</textarea>
</div>
<div>
<p>Содержание</p>
<textarea rows="20" spellcheck="true" name="content" required >@isset($news){{$news->content}}@endisset</textarea>
</div>
<div>
<p>Фото</p>
<p>@isset($news) @if($news->img != '') <img src="../../../../{{$news->img}}"> @endif @endisset</p>
<p><input type="file" name="img"></p>
</div>
{{ csrf_field() }}
<input type="submit" value="@if(isset($news)) Сохранить @else Добавить @endif">
</form>
</div>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
@isset($all) <link href= "../css/news/news.css" rel="stylesheet" > @else <link href= "css/news/news.css" rel="stylesheet" >@endisset
</head>
@isset($all)<h1>Все новости</h1><div><p><a href="{{route('home')}}" class="home">На главную</a></p>{{$last->links()}}
@else<h1>Главная</h1><div><p><a href="{{route('all')}}" class="home">Все новости</a><a href="{{route('admin')}}" class="home">Админка</a></p>@endisset
@foreach($last as $entry)
<div class="newsBlock">
<p class="newsTitle"><a href="{{route('moreInfo', $entry->id)}}">{{$entry->title}}</a></p>
<span>
@if($entry->img != '')<a href="{{route('moreInfo', $entry->id)}}"><img src="@isset($all)../@endisset../{{$entry->img}}"></a> @endif
{{$entry->content}}
</span>
<p class="info"><span class="auhor">Автор: {{$entry->author}}</span><span class="publicDate">{{$entry->publiс_date}}</span></p>
</div>
@endforeach
@isset($all)<div class="secondPag">{{$last->links()}}</div>@endisset
</div>
<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
class ModelBaseFunction
{
/**
* выборка всех записей
* @return Array
*/
public function getAll($tableName){
$all = DB::table($tableName)
->get();
return $all;
}
/**
* выборка последнх записей
* @count количество записей
* @return Array
*/
public function getLast($tableName, $count){
$all = DB::table($tableName)
->orderBy('id', 'desc')
->limit($count)
->get();
return $all;
}
/**
* выборка последнх записей
* @count количество записей на странице
* @return Array
*/
public function getLastPag($tableName, $count){
$all = DB::table($tableName)
->orderBy('id', 'desc')
->paginate($count);
return $all;
}
/**
* выбрать одну запись по id
* @return Array
*/
public function getOne($id, $tableName){
$one = DB::table($tableName)
->where('id', '=', $id)
->first();
return $one;
}
/**
* показать количество записей
* @return int
*/
public function getCount($tableName){
return DB::table($tableName)->count();
}
/**
* показать назване колонок таблицы
* @return Array
*/
public function getColName($tableName){
return DB::table('INFORMATION_SCHEMA.COLUMNS')
->select('COLUMN_NAME')
->where('TABLE_NAME', '=', $tableName)
->get();
}
/**
* Показать количество столбцов в таблице
* @param $tableName имя таблицы
* @return int
*/
public function getColumnCount($tableName){
return DB::table('INFORMATION_SCHEMA.COLUMNS')
->select('COLUMN_NAME')
->where('TABLE_NAME', '=', $tableName)
->count();
}
/**
* вставка новой записи
* @param $arr массив значений для вставки
* @param $tableName имя таблицы
* @return bool
*/
public function insert($arr, $tableName) {
return DB::table($tableName)->insert($arr);
}
/**
* update записи по $id
* @param $id id записи
* @param $tableName имя таблицы
* @param $data массив новых значений
*/
public function update($id, $tableName, $data) {
DB::table($tableName)
->where('id', $id)
->update($data);
}
/**
* удаление записи по id
* @param $id номер записи
* @param $tableName имя таблицы
*/
public function delete($id, $tableName) {
DB::table($tableName)
->where('id', $id)
->delete();
}
}
h1 {text-align: center;}
.newsBlock {display:flex;flex-direction: column;width: 60%; margin: 10px; background: #fafafa; padding: 10px}
.newsBlock p {display: flex;padding: 0 10px;justify-content: space-between;}
.newsBlock p.info span {display: block;}
a img {max-width: 300px; float:left; margin: 15px 20px 15px 0}
.newsTitle a {font-size:20px;font-weight: 600;color:#245269}
a {text-decoration:none;}
a.home {margin:40px;display:block;color:#2b542c;font-size:25px;}
a.home:hover{color: #c7254e}
.info {font-size: 14px;color:#5e5e5e}
table {background: #8eb4cb;border:solid 2px #fff;margin: 10px auto}
.func {font-size: 16px}
.tableTitle {text-align: center;padding:0;height: 40px}
.tableTitle span {font-weight:600;font-size:22px;color:#fff}
table a {color: #aa4a24;font-weight:600;font-size:14px;display:block;width: 100%;height:100%;padding:0px 0}
.tableTitle a {font-size:17px;display:block;width: 100%;height:100%;padding:10px 0}
a:hover {color: #1f648b}
.tableHead {color:#c7254e;font-size:18px;}
.adminTable td {padding:5px;height: 50px}
td img {max-width: 60px;}
.pagination {margin-right: 200px; display:block; float:right}
.secondPag {margin: 0px auto;width: 100%;padding: 5px; display:flex;}
.secondPag .pagination {margin: 0px auto; float:none;}
.newsForm textarea { width: 70%;resize: none}
.newsForm a {text-decoration: none; color: #aa4a24;font-weight:600;font-size:14px;display:block;}
.newsForm a:hover {color: #1f648b}
.newsForm {margin: 5px auto;text-align: center}
.newsForm input[type='submit'] {margin: 10px;width: 150px;height:50px;font-size:22px}
.newsForm input[type='file'] {display: inline-block}
.newsForm p img {max-width: 400px}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\NewsFunction;
class NewsController extends Controller
{
/**
* показать страницу с последними 5 новостями
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function show(){
$nf = new NewsFunction();
$arr = $nf->lastAdded(5);
$arr = $nf->pruning($arr, ['content'=>700]);
return view('news.index', ['last'=>$arr]);
}
/**
* показать страницу со всеми новостями начиная с последне добавленной
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showAll(){
$nf = new NewsFunction();
$arr = $nf->descAllPag(5);
$arr = $nf->pruning($arr, ['content'=>700]);
return view('news.index', ['last'=>$arr, 'all'=>'']);
}
/**
* показать страницу администрирования
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function admin(){
$nf = new NewsFunction();
return view('news.admin', ['all'=>$nf->pruning($nf->descAllPag(5),
['title'=>10,'author'=>10,'content'=>20,'img'=>5]
),
'colums'=>$nf->colums(), 'full'=>$nf->descAllPag(5),
'countColums'=>$nf->columsCount()
]);
}
/**
* удалить запись с $id и перенаправить на админку
* @param $id номер записи
* @return bool|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function delete($id){
if (!is_numeric($id)) return false;
$nf = new NewsFunction();
$nf->deleteNews($id);
return redirect('news/admin');
}
/**
* вывести форму для редкатировния записи
* @param $id номер записи
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function formUpdate($id) {
$nf = new NewsFunction();
$oneNews = $nf->one($id);
return view('news.form', ['news' => $oneNews]);
}
/**
* обновление записи значениями из формы
* @param Request $request массив значений из формы для обновления
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function update(Request $request){
$this->validate($request, [
'id' => 'required|numeric',
'title' => 'required|max:300',
'author' => 'required|max:100',
'content' => 'required|max:10000',
]);
$news = $request->all();
if (isset($request->img)){
$img = $request->img->store('images');
$img = 'storage/app/'.$img;
$news['img'] = $img;
}
$nf = new NewsFunction();
unset($news['_token'],$news['id']);
$nf->updateNews($request->id, $news);
return redirect('news/admin');
}
/**
* добавление новости значениями из формы
* @param Request $request значения из формы
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function addNews(Request $request){
$this->validate($request, [
'title' => 'required|max:300',
'author' => 'required|max:100',
'content' => 'required|max:10000',
]);
$news = $request->all();
if (isset($request->img)){
$img = $request->img->store('images');
$img = 'storage/app/'.$img;
$news['img'] = $img;
}
$nf = new NewsFunction();
unset($news['_token'],$news['id']);
$news['publiс_date'] = date('Y-m-d H:i:s', time());
$nf->add($news);
return redirect('news/admin');
}
/**
* вывести форму для добавления новсоти
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function formAddNews(){
return view('news.form');
}
/**
* перенаправить на страницу полной новости с выбранным id
* @param $id номер новости
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function moreInfo($id){
if (!is_numeric($id)) return view('news.index');
$nf = new NewsFunction();
$news = $nf->one($id);
return view('news.oneNews', ['news'=>$news]);
}
}
<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
use App\Models\ModelBaseFunction;
class NewsFunction extends ModelBaseFunction
{
protected $tableName = 'news';
/**
* выборка всех новостей из таблицы $name_table
* @return Array
*/
public function allGet(){
return $this->getAll($this->tableName);
}
/**
* выборка всех новостей из таблицы $name_table начиная с последней добавленной
* @count количество новостей
* @return Array
*/
public function lastAdded($count){
return $this->getLast($this->tableName, $count);
}
/**
* выборка всех новостей из таблицы $name_table начиная с последней добавленной
* @count количество новостей на странице
* @return Array
*/
public function descAllPag($count){
return $this->getLastPag($this->tableName, $count);
}
/**
* выбрать одну запись по id из таблицы $name_table
* @return Array
*/
public function one($id = 1){
return $this->getOne($id, $this->tableName);
}
/**
* показать количество записей в таблице $name_table
* @return int
*/
public function count(){
return $this->getCount($this->tableName);
}
/**
* показать имена колонок в таблице $name_table
* @return array
*/
public function colums(){
return $this->getColName($this->tableName);
}
/**
* показать количество колонок в таблице $name_table
* @return array
*/
public function columsCount(){
return $this->getColumnCount($this->tableName);
}
/**
* обрезка строк элементов массива
* @param $array массив значений для обрезки
* @param $colums массив с ключём равным имени колонки для обрезки и значнием максимально допустимой длинны
* @return array
*/
public function pruning($array, $colums){
foreach ($array as $val) {
foreach ($colums as $colName=>$length) {
if (mb_strlen($val->$colName) > $length){
$val->$colName = mb_substr($val->$colName, 0, $length).'...';
}
}
}
return $array;
}
/**
* удаление новости по $id
* @param $id номер новости
*/
public function deleteNews($id){
return $this->delete($id, $this->tableName);
}
/**
* добавление новости
* @param $data массив значений для добовления
* @return bool
*/
public function add($data){
return $this->insert($data, $this->tableName);
}
/**
* редактирование новости по id
* @param $id номер новости
* @param $data массив с новыми значениями для обновления
*/
public function updateNews($id, $data){
return $this->update($id, $this->tableName, $data);
}
}
<?php
use Illuminate\Database\Seeder;
class NewsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$data = [];
$time = 0;
$content = [
'Задача организации, в особенности же начало повседневной работы по формированию позиции способствует подготовки и реализации системы обучения кадров, соответствует насущным потребностям. Разнообразный и богатый опыт консультация с широким активом обеспечивает широкому кругу (специалистов) участие в формировании модели развития.',
'Таким образом постоянный количественный рост и сфера нашей активности требуют определения и уточнения направлений прогрессивного развития.',
'Повседневная практика показывает, что рамки и место обучения кадров обеспечивает широкому кругу (специалистов) участие в формировании направлений прогрессивного развития. Равным образом консультация с широким активом в значительной степени обуславливает создание дальнейших направлений развития. Разнообразный и богатый опыт дальнейшее развитие различных форм деятельности требуют определения и уточнения направлений прогрессивного развития.',
'Товарищи! рамки и место обучения кадров позволяет выполнять важные задания по разработке позиций, занимаемых участниками в отношении поставленных задач. Значимость этих проблем настолько очевидна, что сложившаяся структура организации играет важную роль в формировании позиций, занимаемых участниками в отношении поставленных задач.',
'Значимость этих проблем настолько очевидна, что постоянный количественный рост и сфера нашей активности способствует подготовки и реализации дальнейших направлений развития. Повседневная практика показывает, что сложившаяся структура организации позволяет выполнять важные задания по разработке системы обучения кадров, соответствует насущным потребностям.',
'Идейные соображения высшего порядка, а также сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Не следует, однако забывать, что дальнейшее развитие различных форм деятельности обеспечивает широкому кругу (специалистов) участие в формировании систем массового участия.'
];
function content($arr){
$quantity = rand(5,12);
$exitContent = '';
for ($i=0;$i<=$quantity;$i++){
$exitContent .= $arr[array_rand($arr, 1)].PHP_EOL;
}
return $exitContent;
}
for($i=0; $i<50; $i++) {
$time += 5000;
$data[] = [
'title' => title_case(str_random(rand(20,60))),
'author' =>ucfirst(str_random(rand(5,10))).' '.ucfirst(str_random(rand(5,12))),
'content' =>content($content),
'img' => 'storage/app/images/TAFdbpVfIXPXNUEFoPOi4y1GQIP8d05gsXrHTmXC.jpeg',
'publiс_date' => date('Y-m-d H:i:s', time()+$time)
];
}
DB::table('news')->insert($data);
}
}
<head>
<style>
body {}
h1 {text-align: center;}
.newsBlock {display:flex;flex-direction:column;width:60%;margin:10px;background:#fafafa;padding:10px;float:left}
.newsBlock p {display: flex;padding: 0 10px;justify-content: space-between;}
.newsBlock p.info span {display: block;}
img {max-width: 800px;width:100%; float:left; margin: 15px auto; display:block}
.newsTitle a {font-size:20px;font-weight: 600;color:#245269}
a {text-decoration:none;}
a.home {margin:40px;display:block;color:#2b542c;font-size:25px;}
a.home:hover{color: #c7254e}
.info {font-size: 14px;color:#5e5e5e}
</style>
</head>
<h1>{{$news->title}}</h1>
<div class="newsBlock">
@if($news->img != '')<img src="../../{{$news->img}}"> @endif
{{$news->content}}
<p class="info"><span class="auhor">Автор: {{$news->author}}</span><span class="publicDate">{{$news->publiс_date}}</span></p>
</div>
<a href="{{route('home')}}" class="home">На главную</a></p>
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('news', function () {
return view('news.index');
});
Route::any('news', 'NewsController@show')->name('home');
Route::get('news/all', 'NewsController@showAll')->name('all');
Route::any('news/admin', 'NewsController@admin')->name('admin');
Route::any('news/admin/update/{id}', 'NewsController@formUpdate')->name('updateNews');
Route::any('news/admin/delete/{id}', 'NewsController@delete')->name('deleteNews');
Route::post('news/admin/update/{id}', 'NewsController@update');
Route::get('news/admin/add', 'NewsController@formAddNews')->name('addNews');
Route::get('news/admin/add', 'NewsController@formAddNews')->name('addNews');
Route::post('news/admin/add', 'NewsController@addNews');
Route::get('news/{id}', 'NewsController@moreInfo')->name('moreInfo');
//Контроллер
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-newscontroller-php
//Модели
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-modelbasefunction-php
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-newsfunction-php
//Миграции
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-2018_03_21_123041_create_news_table-php
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-2018_03_21_130202_change_news_title_column-php
//seed
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-newstableseeder-php
//vievs
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-admin-blade-php
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-form-blade-php
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-index-blade-php
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-onenews-blade-php
//роут
https://gist.github.com/platinize/0294ed715cb5aebf62dedbb18cfa6bc8#file-web-php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment