Limit latest news usinf foreach - php

How Can I set a limit for "Recent News" posts? I wanted to set a limit for 4, but it's showing all of them. As a bonus insert a "SEE ALL NEWS" button in the end...
I have this:
#foreach($news as $news)
#php
$news_img = ($news['anexo'] ? get_image_small_url($news['anexo']['ane_arquivo']) : '');
$news_img = $news_img ?: 'http://placehold.it/300.jpg?text=%20';
$news_txt = (empty($news['pub_resumo']) ? $news['pub_conteudo'] : $news['pub_resumo']);
#endphp
<div class="media media-thumb">
#if($news_img)
<div class="media-left">
<a href="{{ url('/news/'.$news['post_id']) }}">
<img class="media-object" src="{{ $news_img }}" alt="{{ $news['pub_titulo'] }}">
</a>
</div>
#endif
<div class="media-body">
<div class="post-meta">
<span class="published">{{ date('d/m/Y', strtotime($news['pub_data_cadastro'])) }}</span>
#if(!empty($news['categories']))
<span class="categories">{{ join(', ', array_column($news['categories'], 'tcp_nome')) }}</span>
#endif
</div>
<h4 class="media-heading">
{{ $news['title'] }}
</h4>
<p>{{ get_excerpt($news_txt, 180) }}</p>
</div>
</div>
#endforeach
The controller
$news = Publicacao::select('publicacao_id', 'pub_titulo', 'pub_conteudo', 'pub_resumo', 'pub_data_cadastro', 'anexo_id')
->with(['categorias', 'anexo'])
->where('pub_tipo', 'NOT')
->where('pub_status', 'PUB')
->limit(5)
->orderBy('pub_data_cadastro', 'desc')
->get();
$this->data['news'] = $news->toArray();
return view('site.home', $this->data);
}
Cheers!

Related

How to show image from database with eager loading?

I want to display multiple product image from database with eager loading, and when i tried to displaying it, console said localhost:8000/storage/ 404 not found. Any ideas how to solve this? this is my first time using eager loading & relationship on Laravel. Thank you!
Here is my controller :
public function homeProduct(){
$products = Product::with('productCategory')->get();
$images = Product::with('productImage')->get();
return view('home.index', compact('products', 'images'));
}
Product Model :
public function productImage()
{
return $this->hasMany(ProductImage::class, 'product_id', 'id');
}
Product Image Model :
public function product()
{
return $this->belongsTo(Product::class, 'id');
}
Here are the index.blade.php View :
#foreach ($products as $p)
<div class="col-lg-6 col-12">
<div class="portfolio-thumb mb-5" data-aos="fade-up">
<div id="yoreBeans" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
#foreach ($images as $key => $image)
<div class="carousel-item {{ $key == 0 ? 'active' : '' }}">
<a href="{{ asset('storage/'.$image->path) }}" class="image-popup">
<img src="{{ asset('storage/'.$image->path) }}" class="img-fluid portfolio-image" alt="">
</a>
</div>
#endforeach
</div>
</div>
<div class="portfolio-info">
<h3 class="text-black">{{ $p->name }}</h3>
<h4 class="text-danger">{{ $p->productCategory->name }}</h4>
</div>
</div>
</div>
#endforeach
Your method $images = Product::with('productImage')->get(); will also return Product objects with images.
What you exactly want is to eager load both realtions and then reference it at the same time:
public function homeProduct(){
$products = Product::with(['productCategory', 'productImage'])->get();
return view('home.index', compact('products'));
}
And your view like this:
#foreach ($products as $p)
<div class="col-lg-6 col-12">
<div class="portfolio-thumb mb-5" data-aos="fade-up">
<div id="yoreBeans" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<!-- // this line changed --->
#foreach ($p->productImage as $key => $image)
<div class="carousel-item {{ $key == 0 ? 'active' : '' }}">
<a href="{{ asset('storage/'.$image->path) }}" class="image-popup">
<img src="{{ asset('storage/'.$image->path) }}" class="img-fluid portfolio-image" alt="">
</a>
</div>
#endforeach
</div>
</div>
<div class="portfolio-info">
<h3 class="text-black">{{ $p->name }}</h3>
<h4 class="text-danger">{{ $p->productCategory->name }}</h4>
</div>
</div>
</div>
#endforeach

#foreach inside of #include

I want to add my slider to my home page and when i add using #inclued method and it returns error undefended variable in slider page but it works well in slider page however i added it to home page error occurs. how do i correct this.
error msg-
Undefined variable $data (View: \resources\views\frontendslider.blade.php)
In the: \resources\views/frontendslider.blade.php file at line: 29
codes....
homepage
* LaraClassifier - Classified Ads Web Application
* Copyright (c) BeDigit. All Rights Reserved
*
* Website: https://laraclassifier.com
*
* LICENSE
* -------
* This software is furnished under a license and may be used and copied
* only in accordance with the terms of such license and with the inclusion
* of the above copyright notice. If you Purchased from CodeCanyon,
* Please read the full License from here - http://codecanyon.net/licenses/standard
--}}
#extends('layouts.master')
#section('search')
#parent
#includeFirst([config('larapen.core.customizedViewPath') . 'search.inc.form', 'search.inc.form'])
#endsection
#section('content')
<div class="main-container">
#includeFirst([config('larapen.core.customizedViewPath') . 'search.inc.breadcrumbs', 'search.inc.breadcrumbs'])
#if (config('settings.list.show_cats_in_top'))
#if (isset($cats) && $cats->count() > 0)
<div class="container mb-2 hide-xs">
<div class="row p-0 m-0">
<div class="col-12 p-0 m-0 border border-bottom-0 bg-light"></div>
</div>
</div>
#endif
#includeFirst([config('larapen.core.customizedViewPath') . 'search.inc.categories', 'search.inc.categories'])
#endif
<?php if (isset($topAdvertising) && !empty($topAdvertising)): ?>
#includeFirst([config('larapen.core.customizedViewPath') . 'layouts.inc.advertising.top', 'layouts.inc.advertising.top'], ['paddingTopExists' => true])
<?php
$paddingTopExists = false;
else:
if (isset($paddingTopExists) && $paddingTopExists) {
$paddingTopExists = false;
}
endif;
?>
<div class="container">
<div class="row">
{{-- Sidebar --}}
#if (config('settings.list.left_sidebar'))
#includeFirst([config('larapen.core.customizedViewPath') . 'search.inc.sidebar', 'search.inc.sidebar'])
<?php $contentColSm = 'col-md-9'; ?>
#else
<?php $contentColSm = 'col-md-12'; ?>
#endif
{{-- Content --}}
<div class="{{ $contentColSm }} page-content col-thin-left mb-4">
<div class="category-list {{ config('settings.list.display_mode', 'make-grid') }}{{ ($contentColSm == 'col-md-12') ? ' noSideBar' : '' }}">
<div class="tab-box">
{{-- Nav tabs --}}
<ul id="postType" class="nav nav-tabs add-tabs tablist" role="tablist">
<?php
$aClass = '';
$spanClass = 'alert-danger';
if (config('settings.single.show_listing_types')) {
if (!request()->filled('type') || request()->get('type') == '') {
$aClass = ' active';
$spanClass = 'bg-danger';
}
} else {
$aClass = ' active';
$spanClass = 'bg-danger';
}
?>
<li class="nav-item">
<a href="{!! qsUrl(request()->url(), request()->except(['page', 'type']), null, false) !!}" class="nav-link{{ $aClass }}">
{{ t('All Listings') }} <span class="badge badge-pill {!! $spanClass !!}">{{ $count->get('all') }}</span>
</a>
</li>
#if (config('settings.single.show_listing_types'))
#if (isset($postTypes) && $postTypes->count() > 0)
#foreach ($postTypes as $postType)
<?php
$postTypeUrl = qsUrl(
request()->url(),
array_merge(request()->except(['page']), ['type' => $postType->id]),
null,
false
);
$postTypeCount = ($count->has($postType->id)) ? $count->get($postType->id) : 0;
?>
#if (request()->filled('type') && request()->get('type') == $postType->id)
<li class="nav-item">
<a href="{!! $postTypeUrl !!}" class="nav-link active">
{{ $postType->name }}
<span class="badge badge-pill bg-danger">
{{ $postTypeCount }}
</span>
</a>
</li>
#else
<li class="nav-item">
<a href="{!! $postTypeUrl !!}" class="nav-link">
{{ $postType->name }}
<span class="badge badge-pill alert-danger">
{{ $postTypeCount }}
</span>
</a>
</li>
#endif
#endforeach
#endif
#endif
</ul>
<div class="tab-filter pb-2">
{{-- OrderBy Desktop --}}
<select id="orderBy" title="sort by" class="niceselecter select-sort-by small" data-style="btn-select" data-width="auto">
#if (isset($orderByArray) && !empty($orderByArray))
#foreach($orderByArray as $option)
#if ($option['condition'])
<option{{ $option['isSelected'] ? ' selected="selected"' : '' }} value="{!! $option['url'] !!}">
{{ $option['label'] }}
</option>
#endif
#endforeach
#endif
</select>
</div>
</div>
<div class="listing-filter">
<div class="float-start col-md-9 col-sm-8 col-12">
<h1 class="h6 pb-0 breadcrumb-list">
{!! (isset($htmlTitle)) ? $htmlTitle : '' !!}
</h1>
<div style="clear:both;"></div>
</div>
{{-- Display Modes --}}
#if (isset($posts) && $posts->count() > 0)
<?php $currDisplay = config('settings.list.display_mode'); ?>
<div class="float-end col-md-3 col-sm-4 col-12 text-end listing-view-action">
#if (isset($displayModesArray) && !empty($displayModesArray))
#foreach($displayModesArray as $displayMode => $value)
<span class="grid-view{{ ($currDisplay == $displayMode) ? ' active' : '' }}">
#if ($currDisplay == $displayMode)
<i class="fas fa-th-large"></i>
#else
<a href="{!! $value['url'] !!}">
<i class="{{ $value['icon'] }}"></i>
</a>
#endif
</span>
#endforeach
#endif
</div>
#endif
<div style="clear:both"></div>
</div>
{{-- Mobile Filter Bar --}}
<div class="mobile-filter-bar col-xl-12">
<ul class="list-unstyled list-inline no-margin no-padding">
#if (config('settings.list.left_sidebar'))
<li class="filter-toggle">
<a class=""><i class="fas fa-bars"></i> {{ t('Filters') }}</a>
</li>
#endif
<li>
{{-- OrderBy Mobile --}}
<div class="dropdown">
<a class="dropdown-toggle" data-bs-toggle="dropdown">{{ t('Sort by') }}</a>
<ul class="dropdown-menu">
#if (isset($orderByArray) && !empty($orderByArray))
#foreach($orderByArray as $option)
#if ($option['condition'])
<li>{{ $option['label'] }}</li>
#endif
#endforeach
#endif
</ul>
</div>
</li>
</ul>
</div>
<div class="menu-overly-mask"></div>
{{-- Mobile Filter bar End--}}
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="contentAll" role="tabpanel" aria-labelledby="tabAll">
<div id="postsList" class="category-list-wrapper posts-wrapper row no-margin">
<div class="slider">
#include('frontendslider')
</div>
#if (config('settings.list.display_mode') == 'make-list')
#includeFirst([config('larapen.core.customizedViewPath') . 'search.inc.posts.template.list', 'search.inc.posts.template.list'])
#elseif (config('settings.list.display_mode') == 'make-compact')
#includeFirst([config('larapen.core.customizedViewPath') . 'search.inc.posts.template.compact', 'search.inc.posts.template.compact'])
#else
#includeFirst([config('larapen.core.customizedViewPath') . 'search.inc.posts.template.grid', 'search.inc.posts.template.grid'])
#endif
</div>
</div>
</div>
<div class="tab-box save-search-bar text-center">
#if (request()->filled('q') && request()->get('q') != '' && $count->get('all') > 0)
<a id="saveSearch"
data-name="{!! qsUrl(request()->url(), request()->except(['_token', 'location']), null, false) !!}"
data-count="{{ $count->get('all') }}"
>
<i class="far fa-bell"></i> {{ t('Save Search') }}
</a>
#else
#endif
</div>
</div>
#if ($posts->hasPages())
<nav class="mt-3 mb-0 pagination-sm" aria-label="">
{!! $posts->appends(request()->query())->links() !!}
</nav>
#endif
</div>
</div>
</div>
{{-- Advertising --}}
#includeFirst([config('larapen.core.customizedViewPath') . 'layouts.inc.advertising.bottom', 'layouts.inc.advertising.bottom'])
{{-- Promo Listing Button --}}
<div class="container mb-3">
<div class="card border-light text-dark bg-light mb-3">
<div class="card-body text-center">
<h2>{{ t('do_you_have_anything') }}</h2>
<h5>{{ t('sell_products_and_services_online_for_free') }}</h5>
#if (!auth()->check() && config('settings.single.guests_can_post_listings') != '1')
{{ t('start_now') }}
#else
{{ t('start_now') }}
#endif
</div>
</div>
</div>
{{-- Category Description --}}
#if (isset($cat, $cat->description) && !empty($cat->description))
#if (!(bool)$cat->hide_description)
<div class="container mb-3">
<div class="card border-light text-dark bg-light mb-3">
<div class="card-body">
{!! $cat->description !!}
</div>
</div>
</div>
#endif
#endif
{{-- Show Posts Tags --}}
#if (config('settings.list.show_listings_tags'))
#if (isset($tags) && !empty($tags))
<div class="container">
<div class="card mb-3">
<div class="card-body">
<h2 class="card-title"><i class="fas fa-tags"></i> {{ t('Tags') }}:</h2>
#foreach($tags as $iTag)
<span class="d-inline-block border border-inverse bg-light rounded-1 py-1 px-2 my-1 me-1">
<a href="{{ \App\Helpers\UrlGen::tag($iTag) }}">
{{ $iTag }}
</a>
</span>
#endforeach
</div>
</div>
</div>
#endif
#endif
</div>
#endsection
#section('modal_location')
#includeFirst([config('larapen.core.customizedViewPath') . 'layouts.inc.modal.location', 'layouts.inc.modal.location'])
#endsection
#section('after_scripts')
<script>
$(document).ready(function () {
$('#postType a').click(function (e) {
e.preventDefault();
var goToUrl = $(this).attr('href');
redirect(goToUrl);
});
$('#orderBy').change(function () {
var goToUrl = $(this).val();
redirect(goToUrl);
});
});
</script>
#endsection
controller
public function frontendslider(Request $request){
$data=slider::all();
return view('frontendslider',compact('data'));
}
public function frontendslider2(Request $request){
$data=slider::all();
return view('return',compact('data'));
}
web.php
Route::get('frontendslider',[App\Http\Controllers\Admin\SliderController::class,'frontendslider']);
Route::get('return',[App\Http\Controllers\Admin\SliderController::class,'frontendslider2']);
Anyone face like this kind of issue specelly working with lara classifers use this before your importing page or page that content update..
#php
$data=DB::table('slider')->get();
#endphp
PLS note input your data to $data and table name!!!!

Posts are not displaying correctly after deactivate

So, I have a problem with displaying for a few posts.After a post was deactivated, on main isn't showing anymore, but the space is still here, even if I have an #if condition.By default, on my page I have 7 posts on every page, but here is remaining only the posts which is activated ( table event, column activate)
Here is the code from main
<div class="clearfix margin-bottom-20"><hr></div>
<!-- News v3 -->
#foreach($events as $event)
#if($event->active != 1)
<div class="row margin-bottom-20">
<div class="col-sm-5 sm-margin-bottom-20">
<div class="easy-block-v1">
<a href="{{ url('topic') }}/{{ $event->category->category_url }}">
<div class="easy-block-v1-badge rgba-{{ $event->category->color }} noticeboard-topic-category">
<i class="icon-hotel-restaurant-183 u-line-icon-pro fa-"></i> / {{ $event->category->category }}
</div>
</a>
<?php
$video_content = preg_replace("/<img[^>]+\>/i", "", $event->information);
preg_match('/src="([^"]+)"/', $video_content, $video);
?>
<?php
$match = '';
$str = $event->information;
$start = "<iframe src='";
$end = "' width='100%' height='281'></iframe>";
$pattern = sprintf(
'/%s(.+?)%s/ims',
preg_quote($start, '/'), preg_quote($end, '/')
);
if (preg_match($pattern, $str, $matches)) {
list(, $match) = $matches;
}
?>
#if(isset($match) && $match != '')
<iframe src="{{ $match }}" width='100%' height='250'></iframe>
#elseif(isset($video[1]))
<iframe src="{{ $video[1] }}" width='100%' height='250'></iframe>
#else
<?php preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $event->information, $image); ?>
#if(isset($image['src']))
<!-- <img class="img-responsive" src="{{ $image['src'] }}" alt=""> -->
<?php $img = str_replace('&', '&', $image['src']); ?>
<img class="img-responsive" src="{{ url('ass/336/212?'.$img) }}" alt="">
#else
<?php $img = "thumbnail/".$event->user->profile_picture; ?>
#if(#getimagesize($img))
<img src="{{ url('ass/336/212?'.$img) }}" alt='' />
#else
<?php $img = "assets/img/main/img12.jpg"; ?>
<img class="img-responsive" src="{{ url('ass/336/212?'.$img) }}" alt="">
#endif
#endif
#endif
</div>
</div>
<div class="col-sm-7 news-v3">
<div class="news-v3-in-sm no-padding">
<h2>{{ $event->subject }}</h2>
<ul class="list-inline" style="right: 10px;position: relative">
<li style="font-style: normal !important">
<li style="font-style: normal !important">
#if($event->user->role[0]->pivot->role_id == 1)
<i style="margin-right: 2px;margin-left: 3px;font-size: 11px" class="icon-user"></i>
#else
<i style="margin-right: 2px;margin-left: 3px;font-size: 11px" class="icon-hotel-restaurant-172 u-line-icon-pro fa- fa-lg"></i>
#endif
<a style="margin-left: 2px" href="{{ url('') }}/{{ $event->user->username }}">{{ $event->user->username }}</a></li>
<li style="font-style: normal !important"><i style="margin-right: 3px" class="icon-hotel-restaurant-183 u-line-icon-pro fa-"></i> <a href="{{ url('view-all-event') }}">Event</li>
<li style="font-style: normal !important"><i style="margin-right: 3px" class="icon-notebook fa-"></i> {{ $event->category->category }}</li>
</ul>
<?php
$information = preg_replace("/<img[^>]+\>/i", "", $event->information);
$Output = preg_replace('/<iframe.*?\/iframe>/i','', $information);
?>
<p>{{ str_limit(trim(strip_tags(preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $Output))), 200) }}</p>
<ul class="social-icons social-icons-color social-cu-icons" style="display:none;">
<div class="social-cu">
<li class="facebook_share share_link" link="{{ url('view-event') }}/{{ $event->id }}_{{ Slugify::slugify($event->subject) }}" name="{{ $event->subject }}" description="{{ $event->subject }}">
</li>
<li class="google_share share_link" link="{{ url('view-event') }}/{{ $event->id }}_{{ Slugify::slugify($event->subject) }}" name="{{ $event->subject }}" description="{{ $event->subject }}">
</li>
<li class="twitter_share share_link" link="{{ url('view-event') }}/{{ $event->id }}_{{ Slugify::slugify($event->subject) }}" name="{{ $event->subject }}" description="{{ $event->subject }}">
</li>
<li class="whatapp_share share_link" link="{{ url('view-event') }}/{{ $event->id }}_{{ Slugify::slugify($event->subject) }}" name="{{ $event->subject }}" description="{{ $event->subject }}">
<a href="whatsapp://send?text={{ url('view-event') }}/{{ $event->id }}_{{ Slugify::slugify($event->subject) }}">
<img class="img-responsive social_whatsapp" src="{{ asset('/assets/img/icons/social/Whatsapp.png') }}" alt="">
</a>
</li>
</div>
</ul>
<ul class="post-shares post-shares-lg">
<li ><i class="rounded-x fa fa-comments-o "><span>{!! $event->event_comment_count !!}</span></i></li>
<li><i class="rounded-x icon-magnifier-add" ><span>{!! $event->views !!}</span></i></li>
<li class="changeview" value="{{ $event->id }}" id="changeview"><i class="rounded-x icon-like "><span class="like_{{ $event->id }}">{!! $event->event_like_count !!}</span></i></li>
<li class="share-link"><i class="rounded-x icon-share"></i></li>
</ul>
<br>
Read more...
</div>
</div>
</div><!--/end row-->
<!-- End News v3 -->
<div class="clearfix margin-bottom-20"><hr></div>
#endif
#endforeach
My controller
public function viewAllEvent($category_id = null,$event_type_id = null,$country_id = null,$starting_date = null,$username = null,$search = null,$page = null)
{
// $eventrecommended = Event::with('user','category','country','event_type','event_like')->withCount('event_like','event_comment')->whereHas('user.contact', function ($query) use ($id) {
// $query->where('contacts.user_id', '=', $id);
// })->orWhere('events.public', '=', 1)->orWhere('events.user_id', '=', $id);
// if($page == ""){
// return redirect('view-all-event/1');
// }
$data = $this->data;
$data['title'] = "View All Event";
$data['breadcrumbs'] = "Events";
$page = Input::get('page');
$perPage = 7;
$offset = ($page * $perPage) - $perPage;
$data['evnetTypeList'] = \App\EventType::all();
$data['countryList'] = [''=>'Country'] + \App\Country::lists('country','code')->toArray();
$data['category'] = Input::get('category');
$data['event_type'] = Input::get('event_type');
$data['country'] = Input::get('country');
$data['starting_date'] = Input::get('starting_date');
$username = Input::get('username');
$search = Input::get('search');
$data['login_user'] = $username;
$data['search'] = $search;
$categoryID = \App\Category::pluck('id');
$event = Event::with('user','category','country','event_type')->withCount('event_like','event_comment')->whereHas('user', function($query) {
$query->where('deleted_at', '=', null);
})->whereIn('category_id',$categoryID);
$eventrecommended = Event::with('user','category','country','event_type','event_like')->whereHas('user', function($query) {
$query->where('deleted_at', '=', null);
})->withCount('event_like','event_comment')->whereIn('category_id',$categoryID);
if ($user = Sentinel::check())
{
if(!$user->inRole('admins'))
{
$id = $user->id;
$event = $event->Where(function($query1) use($id){
$query1->where('public','=', 1)->orWhereHas('user.contact', function ($query) use ($id) {
$query->where('user_id', '=', $id);
})->orWhere('user_id','=',$id);
});
$eventrecommended = $eventrecommended->Where(function($query1) use($id){
$query1->where('public','=', 1)->orWhereHas('user.contact', function ($query) use ($id) {
$query->where('user_id', '=', $id);
})->orWhere('user_id','=',$id);
});
}
}
else{
$event = $event->where('public','=', 1);
$eventrecommended = $eventrecommended->where('public','=', 1);
}
return view('event.view_all_event',$data);
}
And in the second photo is my noticeboard, which I have same problem...
Add to your $event in your controller
where('active', 0)
and delete the if statment in your view
#if($event->active != 1)
#endif

Blade and the Negative case

I'm sorry I do not know how to word this question. I'm new to Laravel and I want to either show a photo(s) or if there are no photos I want to show a placeholder. This works but there must be a better way to do it than this.
#foreach ($items as $item)
<?php $totalpics=0; ?>
<div class="col-md-4">
<div class="card mb-4 box-shadow">
#if(! empty($item->photos) )
#foreach ( $item->photos as $photo )
#if ($photo->photo)
<img src="/storage/images/small/{{ $photo->photo }}" class="card-img-top" alt="{{ $item->name }}">
<?php $totalpics++; ?>
#endif
#endforeach
#if(1 > $totalpics)
<img class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="{{ $item->name }}">
#endif
You want to achieve a for loop and an optional statement for when there is nothing to show in the for loop.
Laravel uses the forelse loop for this (see all blade loops in the documentation).
A basic forelse could be:
#forelse($items as $item)
{{$item}}
#empty
There are no items to display
#endforelse
Above code is pseudo code and would not actually run
Which would render as either all the items or as the text There are no items to display.
In your case you could use:
#forelse($items as $item)
<div class="col-md-4">
<div class="card mb-4 box-shadow">
#forelse ( $item->photos as $photo )
#if ($photo->photo)
<a href="/storage/images/large/{{ $photo->photo }}">
<img src="/storage/images/small/{{ $photo->photo }}" class="card-img-top" alt="{{ $item->name }}">
</a>
#endif
#empty
<a href="/items/{{ $item->id }}">
<img class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="{{ $item->name }}">
</a>
#endforelse
</div>
</div>
#endforeach
Side note, this will not render any photos if there is a photo model attached to your item but the photo model does not have the photo property set, i.e. the for loop will be used but the if statement will fail.
You can do
#foreach ($items as $item)
<div class="col-md-4">
<div class="card mb-4 box-shadow">
#unless($item->photos)
<img class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="{{ $item->name }}">
#else
#foreach ( $item->photos as $photo )
#if ($photo->photo)
<img src="/storage/images/small/{{ $photo->photo }}" class="card-img-top" alt="{{ $item->name }}">
#endif
#endforeach
#endunless
There is another way to do that in laravel 5.3+ by using
#forelse($item->photos as $photo)
<img src="/storage/images/small/{{ $photo->photo }}" class="card-img-top" alt="{{ $item->name }}">
#empty
<img class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="{{ $item->name }}">
#endforelse

How to create dynamic layout in Laravel with Blade?

So I'm building my first blog, and I'd like to dynamically show to posts on my landing page. I want the layout to become like this (might be a little weird):
post-image - post-preview
post-preview - post-image
post-image - post-preview
This is what I have right now to show to blog posts:
#foreach($posts as $post)
<div class="col-sm-4">
<a href="/post/{{ $post->slug }}">
<img src="{{ Voyager::image( $post->image ) }}" class="img-responsive" style="width:100%">
<span>{{ $post->title }}</span>
</a>
</div>
#endforeach
web.php (route):
$posts = App\Post::take(3)->orderBy('created_at')->get();
return view('welcome', compact('posts'));
Now as I'd like to make the layout dynamically. I think I can do this by checking if the ID even or odd. However I have no idea on how to do this even when I've searched 50% of the web already :) .
If there is a better way on doing this just let me know! Greatly appreciated guys!
Yes you can do it by checking if current post or loop iteration is odd or even. (https://laravel.com/docs/5.5/blade#the-loop-variable) For Odd loop iteration, you can write image code first and in even loop iteration you can write preview code first to achieve your desired layout. You can check the following code:
#foreach($posts as $post)
<div class="row">
#if( $loop->iteration % 2 == 0 )
<div class="col-md-4">
<a href="/post/{{ $post->slug }}">
<img src="{{ Voyager::image( $post->image ) }}" class="img-responsive" style="width:100%">
</a>
</div>
<div class="col-md-8">
<span>{{ $post->title }}</span>
</div>
#else
<div class="col-md-8">
<span>{{ $post->title }}</span>
</div>
<div class="col-md-4">
<a href="/post/{{ $post->slug }}">
<img src="{{ Voyager::image( $post->image ) }}" class="img-responsive" style="width:100%">
</a>
</div>
#endif
</div>
#endforeach
Ok I guess I got your question. so there is no direct solution but you can measure inside your for loop by adding extra variable such as:
<?php $inc = 0;?>
#foreach($posts as $post)
<div class="col-sm-4">
<a href="/post/{{ $post->slug }}">
#if($inc%2 == 0)
<img src="{{ Voyager::image( $post->image ) }}" class="img-responsive" style="width:100%">
<span>{{ $post->title }}</span>
#else
<span>{{ $post->title }}</span>
<img src="{{ Voyager::image( $post->image ) }}" class="img-responsive" style="width:100%">
#endif
<?php $inc++;?>
</a>
</div>
#endforeach
Or you can use for loop instead of foreach of loop and inside for loop you can check variable i.e. i is odd or even.

Categories