@Radiss

Как реализовать вывод последних статей блога?

Использую версию 5.2

Выборка материалов реализуется не по id, а через псевдоним alias

route
spoiler

Route::resource('articles','ArticlesController',[
										'parameters'=>[
												
													'articles' => 'alias'
												
												]
												
												]);	
Route::get('articles/cat/{cat_alias?}',['uses'=>'ArticlesController@index','as'=>'articlesCat'])->where('cat_alias','[\w-]+');



Записи выводятся по 3 шт.

Repository (метод get)

spoiler

public function get($select = '*',$take = FALSE,$pagination = FALSE, $where = FALSE) {
		
		$builder = $this->model->select($select);
		
		if($take) {
			$builder->take($take);
		}
		
		if($where) {
			$builder->where($where[0],$where[1]);
		}
		
		
		if($pagination) {
			return $this->check($builder->paginate(Config::get('settings.paginate')));
		}

		return $this->check($builder->get());
	}



ArticlesRepository (getArticles)

spoiler

public function getArticles($alias = FALSE) {
    	
    	$where = FALSE;
    	
    	if($alias) {
    		// WHERE `alias` = $alias
			$id = Category::select('id')->where('alias',$alias)->first()->id;
			//WHERE `category_id` = $id
			$where = ['category_id',$id];
		}
		
		$articles = $this->a_rep->get(['id','title','alias','created_at','img','desc','user_id','category_id','keywords','meta_desc'],FALSE,TRUE,$where);
		
		if($articles) {
			$articles->load('user','category','comments');
		}
		
		return $articles;
		
	}



Статьи выводятся в правом сайдбаре на главной стр. и в разделе "блог"

За их вывод отвечает

SiteController

spoiler

<?php

namespace Corp\Http\Controllers;
use Illuminate\Http\Request;
use Corp\Http\Requests;
use Corp\Repositories\SlidersRepository;
use Corp\Repositories\PortfoliosRepository;
use Corp\Repositories\ArticlesRepository;
use Config;

class IndexController extends SiteController
{
    
    public function __construct(SlidersRepository $s_rep, PortfoliosRepository $p_rep, ArticlesRepository $a_rep) {
    	
    	parent::__construct(new \Corp\Repositories\MenusRepository(new \Corp\Menu));
    	
    	$this->s_rep = $s_rep;
    	$this->p_rep = $p_rep;
    	$this->a_rep = $a_rep;
    	
    	$this->bar = 'right';
    	
    	$this->template = config('settings.theme').'.index';
		
	}
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
   
        $articles = $this->getArticles();
        
             $this->contentRightBar = view(config('settings.theme').'.indexBar')->with('articles',$articles)->render();
        
          return $this->renderOutput();
    }
    
    protected function getArticles() {
    	$articles = $this->a_rep->get(['title','created_at','img','alias'],Config::get('settings.home_articles_count'));
    	
    	return $articles;
    }	
    
    
Макет
indexBar.blade

<spoiler title=""><code lang="php">

				            
				            
				            <div class="widget-first widget recent-posts">
				            
				            @if($articles)
				             	<h3>{{ trans('ru.from_blog') }}</h3>
				             	<div class="recent-post group">
				            	
				            		@foreach($articles as $article)
				            			
				            			<div class="hentry-post group">
					                        <div class="thumb-img"><img src="{{asset(config('settings.theme'))}}/images/articles/{{ $article->img->mini }}" alt="001" title="001" /></div>
					                        <div class="text">
					                            <a href="{{ route('articles.show',['alias'=>$article->alias]) }}" title="Section shortcodes &amp; sticky posts!" class="title">{{ $article->title }}</a>

					                            <p class="post-date">{{ $article->created_at->format('F d, Y') }}</p>
					                        </div>
					                    </div>
				            			
				            		@endforeach
				            	
				            	</div>
				            @endif

				            <div class="widget-last widget text-image">
				                <h3>Customer support</h3>
				                <div class="text-image" style="text-align:left"><img src="{{asset(config('settings.theme'))}}/images/callus.gif" alt="Customer support" /></div>
				                <p>Proin porttitor dolor eu nibh lacinia at ultrices lorem venenatis. Sed volutpat scelerisque vulputate. </p>
				            </div>
				            
				        

</code></spoiler>



В разделе блог ArticlesController

spoiler
<?php

namespace Corp\Http\Controllers;
use Illuminate\Http\Request;
use Corp\Repositories\PortfoliosRepository;
use Corp\Repositories\ArticlesRepository;
use Corp\Repositories\CommentsRepository;
use Corp\Http\Requests;
use Corp\Category;

class ArticlesController extends SiteController
{
    
     public function __construct(PortfoliosRepository $p_rep, ArticlesRepository $a_rep, CommentsRepository $c_rep) {
    	
    	parent::__construct(new \Corp\Repositories\MenusRepository(new \Corp\Menu));
    	
    	$this->p_rep = $p_rep;
    	$this->a_rep = $a_rep;
    	$this->c_rep = $c_rep;
    	
    	$this->bar = 'right';
    	
    	$this->template = config('settings.theme').'.articles';
		
	}
	
	public function index($cat_alias = FALSE)
    {
        //
        
        $this->title = 'Блог';
		$this->keywords = 'String';
		$this->meta_desc = 'String';
        
        $articles = $this->getArticles($cat_alias);
        
        $content = view(config('settings.theme').'.articles_content')->with('articles',$articles)->render();
        $this->vars = array_add($this->vars,'content',$content);
        
        $comments = $this->getComments(config('settings.recent_comments'));
        $portfolios = $this->getPortfolios(config('settings.recent_portfolios'));

        
        $this->contentRightBar = view(config('settings.theme').'.articlesBar')->with(['comments' => $comments,'portfolios' => $portfolios]);
		
        
        return $this->renderOutput();
    }
    
    public function getComments($take) {
		
		$comments = $this->c_rep->get(['text','name','email','site','article_id','user_id'],$take);
		
		if($comments) {
			$comments->load('article','user');
		}
		
		return $comments;
	}
	
	
    
    public function getArticles($alias = FALSE) {
    	
    	$where = FALSE;
    	
    	if($alias) {
    		// WHERE `alias` = $alias
			$id = Category::select('id')->where('alias',$alias)->first()->id;
			//WHERE `category_id` = $id
			$where = ['category_id',$id];
		}
		
		$articles = $this->a_rep->get(['id','title','alias','created_at','img','desc','user_id','category_id','keywords','meta_desc'],FALSE,TRUE,$where);
		
		if($articles) {
			$articles->load('user','category','comments');
		}
		
		return $articles;
		
	}
	
	public function show($alias = FALSE) {
		
		$article = $this->a_rep->one($alias,['comments' => TRUE]);
		
		if($article) {
			$article->img = json_decode($article->img);
		}
		
		//dd($article->comments->groupBy('parent_id'));
		
		if(isset($article->id)) {
			$this->title = $article->title;
			$this->keywords = $article->keywords;
			$this->meta_desc = $article->meta_desc;
		}
		
		
		$content = view(config('settings.theme').'.article_content')->with('article',$article)->render();
		$this->vars = array_add($this->vars,'content',$content);
		
		
		$comments = $this->getComments(config('settings.recent_comments'));
        $portfolios = $this->getPortfolios(config('settings.recent_portfolios'));

        
        $this->contentRightBar = view(config('settings.theme').'.articlesBar')->with(['comments' => $comments,'portfolios' => $portfolios]);
		
		
		return $this->renderOutput();
	}	
    
}


Макет
reghtBar.blade

spoiler
<div class="sidebar group">
	{!! $content_rightBar !!}
</div>
  • Вопрос задан
  • 164 просмотра
Пригласить эксперта
Ответы на вопрос 1
@jazzus
Я имею ввиду в целом упростить. Repository с методом get только дублирует функции Laravel и ничего кроме путаницы не добавляет. Статьи выводятся просто
Article::where('alias',$alias)
       ->latest()
       ->take($take)
       ->paginate($paginate);

либо через категории
Category::with(['articles' => function($query) use ($alias,$take) {
                  $query->where('alias',$alias)->запрос;
              }])->запрос->paginate($paginate);

будет коллекция категорий со своими статьями. Доставать их вложенным циклом в шаблоне.
Ошибка т.к. в Repository после paginate это уже не билдер
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы