日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

laravel大型项目系列教程(四)之显示文章列表和用户修改文章

發(fā)布時間:2024/4/14 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 laravel大型项目系列教程(四)之显示文章列表和用户修改文章 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

小編心語:不知不覺已經(jīng)第四部分了,非常感謝很多人給小編提的意見,改了很多bug,希望以后能繼續(xù)幫小編找找茬~小編也不希望誤導(dǎo)大家~這一節(jié),主要講的是如何顯示文章列表和讓用戶修改文章,小編預(yù)告一下(一共有八節(jié)哦)如果有不懂得地方,或者本文呢沒有講清楚的地方,敬請期待下一章節(jié)。

一、前言

上節(jié)教程中實現(xiàn)了發(fā)布文章的功能,本節(jié)教程中將大概實現(xiàn)在首頁和用戶主頁分頁顯示文章和標(biāo)簽列表、用戶能夠修改刪除文章。


二、Let's go

1.首頁顯示文章和標(biāo)簽列表

我們需要在首頁顯示文章和標(biāo)簽列表,修改views/index.blade.php

@extends('_layouts.default')@section('main') <div class="am-g am-g-fixed"><div class="am-u-md-8">@foreach ($articles as $article)<article class="blog-main"><h3 class="am-article-title blog-title"><a href="{{ URL::route('article.show', $article->id) }}">{{{ $article->title }}}</a></h3><h4 class="am-article-meta blog-meta">by <a href="#">{{{ $article->user->nickname }}}</a> posted on {{ $article->created_at->format('Y/m/d H:i') }} under @foreach ($article->tags as $tag)<a href="#" style="color: #fff;" class="am-badge am-badge-success am-radius">{{ $tag->name }}</a>@endforeach</h4><div class="am-g"><div class="am-u-sm-12">@if ($article->summary)<p>{{ $article->summary }}</p>@endif<hr class="am-article-divider"/></div></div></article>@endforeach</div><div class="am-u-md-4 blog-sidebar"><br/><div class="am-panel-group"><section class="am-panel am-panel-default"><div class="am-panel-hd"><span class="am-icon-tags"></span> Tags</div><ul class="am-list">@for ($i = 0, $len = count($tags); $i < $len; $i++)<li><a href="#">{{ $tags[$i]->name }} @if ($i == 0)<span class="am-fr am-badge am-badge-danger am-round">{{ $tags[$i]->count }}</span>@elseif ($i == 1)<span class="am-fr am-badge am-badge-warning am-round">{{ $tags[$i]->count }}</span>@elseif ($i == 2)<span class="am-fr am-badge am-badge-success am-round">{{ $tags[$i]->count }}</span>@else<span class="am-fr am-badge am-round">{{ $tags[$i]->count }}</span>@endif</a></li>@endfor </ul></section></div></div> </div> @stop

在custom.css中增加:

@media only screen and (min-width: 641px) {.blog-sidebar {font-size: 1.4rem;} }.blog-main {padding: 20px 0; }.blog-title {margin: 10px 0 20px 0; }.blog-meta {font-size: 14px;margin: 10px 0 20px 0;color: #222; }.blog-meta a {color: #27ae60; }

修改routes.php

Route::get('/', function() {$articles = Article::with('user', 'tags')->orderBy('created_at', 'desc')->paginate(10);$tags = Tag::where('count', '>', '0')->orderBy('count', 'desc')->orderBy('updated_at', 'desc')->take(10)->get();return View::make('index')->with('articles', $articles)->with('tags', $tags); });

上面Article::with()使用了預(yù)加載,可以減少查詢次數(shù)。

發(fā)布幾篇文章然后訪問首頁:

2.實現(xiàn)用戶主頁

我們在發(fā)表文章后應(yīng)該能在用戶主頁看到文章列表,并能對文章進行操作,先在導(dǎo)航欄nav.blade.php的@else上面添加一個按鈕My Articles:


<div class="am-topbar-right"><a href="{{ URL::to('user/'. Auth::id() . '/articles') }}" class="am-btn am-btn-primary am-topbar-btn am-btn-sm topbar-link-btn"><span class="am-icon-list"></span> My Articles</a> </div>
修改 home.blade.php:

@extends('_layouts.default')@section('main') <div class="am-g am-g-fixed blog-g-fixed"><div class="am-u-sm-12"><table class="am-table am-table-hover am-table-striped "><thead><tr><th>Title</th><th>Tags</th>@if ($user->id == Auth::id())<th>Managment</th>@endif</tr></thead><tbody>@foreach ($articles as $article)<tr><td><a href="{{ URL::route('article.show', $article->id) }}">{{{ $article->title }}}</a></td><td>@foreach ($article->tags as $tag)<span class="am-badge am-badge-success am-radius">{{ $tag->name }}</span>@endforeach</td>@if ($user->id == Auth::id())<td><a href="{{ URL::to('article/'. $article->id . '/edit') }}" class="am-btn am-btn-xs am-btn-primary"><span class="am-icon-pencil"></span> Edit</a>{{ Form::open(array('url' => 'article/' . $article->id, 'method' => 'DELETE', 'style' => 'display: inline;')) }}<button type="button" class="am-btn am-btn-xs am-btn-danger" id="delete{{ $article->id }}"><span class="am-icon-remove"></span> Delete</button>{{ Form::close() }}</td>@endif</tr>@endforeach</tbody></table></div> </div> <div class="am-modal am-modal-confirm" tabindex="-1" id="my-confirm"><div class="am-modal-dialog"><div class="am-modal-bd"></div><div class="am-modal-footer"><span class="am-modal-btn" data-am-modal-cancel>No</span><span class="am-modal-btn" data-am-modal-confirm>Yes</span></div></div> </div> <script>$(function() {$('[id^=delete]').on('click', function() {$('.am-modal-bd').text('Sure you want to delete it?');$('#my-confirm').modal({relatedTarget: this,onConfirm: function(options) {$(this.relatedTarget).parent().submit();},onCancel: function() {}});});}); </script> @stop

先添加一個UserController:

$ php artisan generate:controller UserController

在UserController.php中增加:

public function articles(User $user) {return View::make('home')->with('user', $user)->with('articles', Article::with('tags')->where('user_id', '=', $user->id)->orderBy('created_at', 'desc')->get()); }

在routes.php中增加:

Route::get('user/{user}/articles', 'UserController@articles');

并修改原來的Route::get('home'):

Route::get('home', array('before' => 'auth', function() {return View::make('home')->with('user', Auth::user())->with('articles', Article::with('tags')->where('user_id', '=', Auth::id())->orderBy('created_at', 'desc')->get()); }));

現(xiàn)在當(dāng)用戶登錄或點擊My Articles按鈕后會跳轉(zhuǎn)到用戶主頁顯示文章列表,并且點擊標(biāo)題時能跳轉(zhuǎn)到顯示文章內(nèi)容頁面:

用戶主頁完成了,另外當(dāng)在首頁和文章內(nèi)容頁面點擊作者時也能跳轉(zhuǎn)到相應(yīng)用戶的主頁,但是如果不是本用戶是沒有操作權(quán)限的,給views/index.blade.php中的作者增加鏈接地址:

<a href="{{ URL::to('user/' . $article->user->id . '/articles') }}">{{{ $article->user->nickname }}}</a>

給articles/show.blade.php中的作者增加鏈接地址:

<a href="{{ URL::to('user/' . $article->user->id . '/articles') }}" style="cursor: pointer;">{{{ $article->user->nickname }}}</a>

現(xiàn)在點擊這兩個超鏈接的時候就能跳轉(zhuǎn)到相應(yīng)用戶的主頁了,但是沒有操作權(quán)限:

3.首頁分頁顯示文章

當(dāng)文章很多時,我們就要分頁顯示了,Laravel已經(jīng)為我們實現(xiàn)好了分頁邏輯,但它默認(rèn)的是Bootstrap的樣式,由于我們使用AmazeUI,所以需要自定義表示器。先在app目錄創(chuàng)建一個名為Blog的文件夾,這個文件夾中主要放置我們自己寫的擴展類,在其中新建一個名為PaginationPresenter.php的文件,修改:

class PaginationPresenter extends Illuminate\Pagination\Presenter {public function getActivePageWrapper($text){return '<li class="am-active"><a href="">'.$text.'</a></li>';}public function getDisabledTextWrapper($text){return '<li class="am-disabled"><a href="">'.$text.'</a></li>';}public function getPageLinkWrapper($url, $page, $rel = null){return '<li><a href="'.$url.'">'.$page.'</a></li>';} }

完成之后這個類還不能被找到,需要在composer.josn中的autoload classmap中增加"app/Blog",然后執(zhí)行:

$ composer dump-autoload

這樣這個類就能被找到了,現(xiàn)在創(chuàng)建分頁鏈接的視圖:

$ php artisan generate:view pagination

修改pagination.blade.php:

<ul class="am-pagination am-pagination-centered">{{ with(new PaginationPresenter($paginator))->render() }} </ul>

完成后修改app/config/view.php中的pagination的值為pagination,在routes.php中Route::get('/')內(nèi)paginate()的參數(shù)就是指定每頁顯示的數(shù)量,由于我文章比較少,暫時把它設(shè)為2,最后在views/index.blade.php中文章顯示之后添加{{ $articles->links() }},現(xiàn)在訪問首頁就會看到如下分頁鏈接了:

4.修改文章的視圖

這步要實現(xiàn)在用戶主頁能夠修改文章了,自己的文章只能自己或者管理員修改,在ArticleController.php中增加一個過濾器:

public function canOperation($route, $request) {if (!(Auth::user()->is_admin or Auth::id() == Article::find(Route::input('article'))->user_id)){return Redirect::to('/');} }

上面的Route::input('article')可以獲得路由參數(shù),這里就是文章的id值,然后在構(gòu)造函數(shù)中添加使用過濾器,再添加一個csrf過濾器:

$this->beforeFilter('csrf', array('only' => array('store', 'update', 'destroy'))); $this->beforeFilter('@canOperation', array('only' => array('edit', 'update', 'destroy')));

創(chuàng)建修改文章的視圖:

$ php artisan generate:view articles.edit

修改articles/edit.blade.php:

@extends('_layouts.default')@section('main') <div class="am-g am-g-fixed"><div class="am-u-sm-12"><h1>Edit Article</h1><hr/>@if ($errors->has())<div class="am-alert am-alert-danger" data-am-alert><p>{{ $errors->first() }}</p></div>@endif{{ Form::model($article, array('url' => URL::route('article.update', $article->id), 'method' => 'PUT', 'class' => "am-form")) }}<div class="am-form-group">{{ Form::label('title', 'Title') }}{{ Form::text('title', Input::old('title')) }}</div><div class="am-form-group">{{ Form::label('content', 'Content') }}{{ Form::textarea('content', Input::old('content'), array('rows' => '20')) }}<p class="am-form-help"><button id="preview" type="button" class="am-btn am-btn-xs am-btn-primary"><span class="am-icon-eye"></span> Preview</button></p></div><div class="am-form-group">{{ Form::label('tags', 'Tags') }}{{ Form::text('tags', Input::old('tags')) }}<p class="am-form-help">Separate multiple tags with a comma ","</p></div><p><button type="submit" class="am-btn am-btn-success"><span class="am-icon-pencil"></span> Modify</button></p>{{ Form::close() }}</div> </div><div class="am-popup" id="preview-popup"><div class="am-popup-inner"><div class="am-popup-hd"><h4 class="am-popup-title"></h4><span data-am-modal-closeclass="am-close">×</span></div><div class="am-popup-bd"></div></div> </div> <script>$(function() {$('#preview').on('click', function() {$('.am-popup-title').text($('#title').val());$.post('preview', {'content': $('#content').val()}, function(data, status) {$('.am-popup-bd').html(data);});$('#preview-popup').modal();});}); </script> @stop

在routes.php中增加

Route::post('article/{id}/preview', array('before' => 'auth', 'uses' => 'ArticleController@preview'));

這是為了修改文章時能夠預(yù)覽文章。

在ArticleController.php中修改:

public function edit($id) {$article = Article::with('tags')->find($id);$tags = '';for ($i = 0, $len = count($article->tags); $i < $len; $i++) {$tags .= $article->tags[$i]->name . ($i == $len - 1 ? '' : ',');}$article->tags = $tags;return View::make('articles.edit')->with('article', $article); }

現(xiàn)在在用戶主頁點擊修改文章時會跳轉(zhuǎn)到修改頁面:

5.修改文章

在ArticleController.php添加修改文章的業(yè)務(wù)邏輯:

public function update($id) {$rules = ['title' => 'required|max:100','content' => 'required','tags' => array('required', 'regex:/^\w+$|^(\w+,)+\w+$/'),];$validator = Validator::make(Input::all(), $rules);if ($validator->passes()) {$article = Article::with('tags')->find($id);$article->update(Input::only('title', 'content'));$resolved_content = Markdown::parse(Input::get('content'));$article->resolved_content = $resolved_content;$tags = array_unique(explode(',', Input::get('tags')));if (str_contains($resolved_content, '<p>')) {$start = strpos($resolved_content, '<p>');$length = strpos($resolved_content, '</p>') - $start - 3;$article->summary = substr($resolved_content, $start + 3, $length);} elseif (str_contains($resolved_content, '</h')) {$start = strpos($resolved_content, '<h');$length = strpos($resolved_content, '</h') - $start - 4;$article->summary = substr($resolved_content, $start + 4, $length);}$article->save();foreach ($article->tags as $tag) {if (($index = array_search($tag->name, $tags)) !== false) {unset($tags[$index]);} else {$tag->count--;$tag->save();$article->tags()->detach($tag->id);}}foreach ($tags as $tagName) {$tag = Tag::whereName($tagName)->first();if (!$tag) {$tag = Tag::create(array('name' => $tagName));}$tag->count++;$article->tags()->save($tag);}return Redirect::route('article.show', $article->id);} else {return Redirect::route('article.edit', $id)->withInput()->withErrors($validator);} }

這部分較難的是對Tag的處理,可能我的方法不是最好的。

這樣就能真正的實現(xiàn)修改了:

6.刪除文章

在ArticleController.php中增加:

public function destroy($id) {$article = Article::find($id);foreach ($article->tags as $tag) {$tag->count--;$tag->save();$article->tags()->detach($tag->id);}$article->delete();return Redirect::to('home'); }

我們這里刪除文章其實是軟刪除,它在數(shù)據(jù)庫中還是存在的。

當(dāng)點擊Yes后會發(fā)現(xiàn)文章被刪除了。

7.小結(jié)

本節(jié)教程完成了在首頁和用戶主頁顯示文章和標(biāo)簽列表,用戶能夠管理自己的文章,但只在首頁實現(xiàn)了分頁顯示文章,你可以自己實現(xiàn)在用戶主頁也分頁顯示,在刪除文章確認(rèn)提示的時候,你可以加上要刪除文章的標(biāo)題,這樣用戶體驗會更好,你完全可以按你的想法進行實現(xiàn)。這節(jié)就到此結(jié)束了,我們已經(jīng)實現(xiàn)了管理員用戶管理,下節(jié)就將完善管理員模塊,實現(xiàn)文章和標(biāo)簽管理。

別忘記還有最后的代碼下載:

$ git clone https://github.com/shiyanlou/laravel-blog-4.git

關(guān)于laravel的相關(guān)學(xué)習(xí)網(wǎng)站:

  • Laravel官網(wǎng)
  • 中文文檔1、中文文檔2
  • 實驗樓論壇
  • Laravel中文網(wǎng)問答社區(qū)
  • PHPHub中文社區(qū)
  • API文檔
  • laravel.io
  • LARACASTS
最后的最后~小編希望通過這個教程能幫助大家更好的認(rèn)識laravel

總結(jié)

以上是生活随笔為你收集整理的laravel大型项目系列教程(四)之显示文章列表和用户修改文章的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。