Based on how get random row laravel-5 I adjusted my query, but still not receiving the expected result.
I have 20 articles in the database and want to get randomly only 3 of them and show them on the page.
My class is just like the following:
public function article()
{
$article = DashArticle::where('category', '=', 0)->get()->random(3);
$articleTitle0 = $article[0]->titel;
$articleAutor0 = $article[0]->autor;
$articleAbstract0 = $article[0]->abstract;
$articleSource0 = $article[0]->source;
$articleTitle1 = $article[1]->titel;
$articleAutor1 = $article[1]->autor;
$articleAbstract1 = $article[1]->abstract;
$articleSource1 = $article[1]->source;
$articleTitle2 = $article[2]->titel;
$articleAutor2 = $article[2]->autor;
$articleAbstract2 = $article[2]->abstract;
$articleSource2 = $article[2]->source;
return compact(
'articleTitle0', 'articleAutor0', 'articleAbstract0', 'articleSource0',
'articleTitle1', 'articleAutor1', 'articleAbstract1', 'articleSource1',
'articleTitle2', 'articleAutor2', 'articleAbstract2', 'articleSource2'
);
}
And here part of the view:
<div id="a-slide" class="carousel slide auto panel-body">
<ol class="carousel-indicators out">
<li class="active" data-slide-to="0" data-target="#a-slide"></li>
<li class="" data-slide-to="1" data-target="#a-slide"></li>
<li class="" data-slide-to="2" data-target="#a-slide"></li>
</ol>
<div class="carousel-inner">
<div class="item active" style="padding: 0 16px;">
<p style="font-size: 16px; font-weight: bold;">{!! $articleTitle0 !!}</p>
<p class="text-muted">{!! $articleAutor0 !!}</p>
<p><strong>Abstract:</strong><br />{!! $articleAbstract0 !!}</p>
<p>
<a href="$articleSource !!}" target="_blank">
{!! $articleSource0 !!}
</a>
</p>
</div>
<div class="item" style="padding: 0 16px;">
<p style="font-size: 16px; font-weight: bold;">{!! $articleTitle1 !!}</p>
<p class="text-muted">{!! $articleAutor1 !!}</p>
<p><strong>Abstract:</strong><br />{!! $articleAbstract1 !!}</p>
<p>
<a href="{!! $articleSource1 !!}" target="_blank">
{!! $articleSource1 !!}
</a>
</p>
</div>
The problem is when I let the random = 3
($article = DashArticle::where('category', '=', 0)->get()->random(3);
I get following error: "Undefined offset: 1"
and when I user random = 20 (the total number of rows in the table) it works but I don't become any random articles but always the first 3 lines of the table.
I would appreciate any help! Thanks!
The problem is that random method preserves keys from original collection. To avoid this you should get a pure values:
$article = DashArticle::where('category', '=', 0)->get()->random(3)->values();
You can get random rows by like this :
public function article()
{
$article = DashArticle::orderBy(DB::raw('RAND()'))->take(3)->get();
//pass data to view
if(view()->exists('article.list')){
return view('article.list',compact('article'));
}
}
Try this
$article = DashArticle::where('category', '=', 0)->get()->shuffle()->all();
Related
I'm having an issue that possibly a lot of people already had on here, but I can't seem to figure it out.
I'm trying to use Carbon and Paginate in the same variable, but keep getting the error shown in the title.
The code that I'm trying to use it with is:
Controller:
public function index()
{
$announcements = Announcement::withCount('replies')->orderBy('created_at', 'desc')->paginate(5);
$birthdays = User::whereRaw('DAYOFYEAR(curdate()) <= DAYOFYEAR(birthday) AND DAYOFYEAR(curdate()) + 365 >= dayofyear(birthday)')
->orderByRaw('DAYOFYEAR(birthday)')
->get();
$date = Carbon::create($announcements->created_at)->locale('nl');
return view('home', compact('announcements', 'birthdays', 'date'));
}
View:
#foreach($announcements as $announcement)
<div class="announcement">
<div class="row">
<div class="col-lg-11">
<h2 style="font-size:1.5rem;" class="text-capitalize">{{$announcement->post_title}}</h2>
#if($announcement->post_image == null)
#else
<img src="{{$announcement->post_image}}" style="width:100%;">
#endif
<p style="font-size: 0.8rem;">{{$birthday->isoFormat('LL')}} | Geplaatst door <span>{{$announcement->username}}</span> | <span style="color:#007ac3">{{$announcement->replies_count}} reacties</span></p>
<p style="margin-top: -10px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;">{!! Str::words($announcement->post_content, 20) !!}</p>
</div>
<div class="col-lg-1">
#if(Auth::user()->admin == 1)
<i class="fal fa-dumpster" style="text-align: center;position: relative;font-size: 20px;"></i>
#endif
</div>
</div>
<p>Meer lezen <i class="fas fa-angle-double-right"></i></p>
<hr>
</div>
#endforeach
I'm expecting it to translate the date to Dutch, but for now all I'm getting is the error.
The ->paginate() method returns a LengthAwarePaginator object, not a single model. You'll need to map the date function over each element in the Collection object.
The following Codeigniter controller outputs a JSON when accessed through url.
Codeigniter controller
function ttoday(){
$this->load->model('dashboard_stats');
$tours_today = $this->dashboard_stats->upcoming_tours();
$data_json = json_encode($tours_today);
echo $data_json;
}
Codeigniter Model
function upcoming_tours()
{
mysql_query("SET time_zone = '+3:00'");
$this->db->order_by('from_start_time','asc');
$this->db->where('DATE(from_start_time) = CURDATE()');
$this->db->where('from_start_time > DATE_SUB(NOW(), INTERVAL 90 MINUTE)');
$query = $this->db->get('tours');
return $query->result();
}
Angularjs Controller
translineClassic.controller('homeController', ['$scope', '$http', '$window', '$rootScope', function($scope, $http, $window, $rootScope){
$http.get('http://122.222.22.2/booking/public_html/admin/api/cities')
.success(function(result){
$scope.cities = result;
});
$http.get('http://122.222.22.2/booking/public_html/admin/api/ttoday')
.success(function(result){
$scope.tours = result;
});
}]);
Encoded Json
[{"tour_id":"4260","route_time":"121473438600","tour_route":"12","from_start_time":"2016-09-09 19:30:00","available_seats":"47","start_price":"800.00","additional":"0","book_online":"0","date_created":"2016-08-30 09:50:05"},{"tour_id":"4412","route_time":"111473438600","tour_route":"11","from_start_time":"2016-09-09 19:30:00","available_seats":"47","start_price":"800.00","additional":"0","book_online":"0","date_created":"2016-08-30 11:34:46"}]
In the database where the routes are stored. We have stored the tour_route id and not the route name. There is a separate table that stores the routes, and I can get the route name by using the following code.
function get_route_name($id){
$this->db->select('route_name');
$this->db->where('route_id', $id);
$query = $this->db->get('routes');
if ($query->num_rows() > 0)
{
$row = $query->row();
return $row->route_name;
}
}
Using the code as shown above, I can be able to use the $http for angularjs to get the data and then bind with the view.
The problem arises when I need to show the route name. but instead I have tour_route, I can be able to do this in php using the get_route_name() function, How can I print route name instead of tour_route? Do I have to use the $http again? Please help me on this. I am new to angularJs and any help will be appreciated.
My View
<article class="result">
<div ng-repeat="tour in tours">
<div class="one-fourth heightfix"><img class="img-responsive" src="assets/images/translinebus.JPEG" alt="" /></div>
<div class="one-half heightfix">
<h3>{{ tour.tour_route }} ?</h3>
<ul>
<li>
<span class="ico people"></span>
<p>Max people</strong> <br/>
Seats Remaining </strong> </p>
</li>
<li>
<span class="ico luggage"></span>
<p>Max <strong>3 suitcases</strong> <br />per vehicle</p>
</li>
<li>
<span class="ico time"></span>
<p>Departure Time<br />
<strong><span class="icon-clock" style="color:red;">
{{ tour.from_start_time }} </span>
</strong></p>
</li>
</ul>
</div>
<div class="one-fourth heightfix">
<div>
<div class="price"><small>KES</small> {{ tour.start_price }}</div>
<span class="meta">per passenger</span>
<button value="{{ tour.tour_id }}" type="submit" class="btn grey large">select</button>
</div>
</div>
<div class="full-width information" ng-show="showDetails">
x
<p>Free Wifi, Charging</p>
</div>
</div>
</article>
My model code
how we can call this function in blade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasicModel extends Model
{
public static function get_product_count($id){
$query = "select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id";
print_r($query);
return $query->row_array();
}
}
My view.blade.php code
count in foreach loop or show in all category
#foreach ($r as $row)
<li class="grid-item type-rent">
<div class="property-block">
<img src="{{ URL::to('/template/images/background-images/sub-category-images/' .$row->sub_cat_images. '')}}" alt=""> <!-- <span class="images-count"><i class="fa fa-picture-o"></i> 2</span> <span class="badges">Rent</span> -->
<div class="property-info">
<h4>{{ ucwords(substr($row->sub_cat_name, 0, 22)) }}</h4>
<span class="location">NYC</span>
<div class="price"><strong>Items</strong><span>
<!-- start count code from here -->
$data = $this->BasicModel->count {{ ($row->sub_id) }}
echo $data['count'];
</span></div>
</div>
<!-- <div class="property-amenities clearfix"> <span class="area"><strong>5000</strong>Area</span> <span class="baths"><strong>3</strong>Baths</span> <span class="beds"><strong>3</strong>Beds</span> <span class="parking"><strong>1</strong>Parking</span> </div> -->
</div>
</li>
#endforeach
My BasicController Code
public function grid(Request $request, $id)
{
if ($id == 1) {
$r = DB::table('sub_category')->select('*')->where('cat_id', $id)
->where('sub_status', '1')->orderBy('sub_id', 'asc')->get();
$name = DB::table('category')->where('cat_id', $id)->get();
return view('buy-and-sell/grid', compact('r','name','count'));
}
image for your help
image for your help
problem in this image please solve the problem
I think you are closing the PHP tag in the wrong place. Change to this:
<?php print_r($count);
$data = $this->BasicController->count {{ ($row->sub_id) }}
echo $data['count'];//here is the rightplace to close your PHP ?>
</span></div>
All PHP code needs to stay between the <?php and ?>
Looking to your image, apparently, it's printing the $count and then it's printing the plain text , so you have 80$data = ...
If you counted your rows in controller by the code below
$count = DB::table('products')->where('sub_id', $id)->count();
then why wrote so many code in html for counting?
Remove all code form counting form your html and just use this {{ $count }}
My search function is not returning the results I expect.
How can I output the query object to see what is returned by the db query?
public function search()
{
//Save requests to variables
$price = Helper::explodeString(Request::get('price'));
$texts = Helper::explodeString(Request::get('texts'));
$minutes = Helper::explodeString(Request::get('minutes'));
$data = Helper::explodeString(Request::get('data'));
$contract = Request::get('contract');
$phone_option = Request::get('phone-option');
//get all selected carriers
$carriers = array();
foreach(Carrier::all() as $carrier){
if(Request::has($carrier->name)){
$carriers[] = $carrier->id;
}
}
// build query
$query = Plan::whereBetween('price', $price)
->whereBetween('text', $texts)
->whereBetween('minutes', $minutes)
->whereBetween('data', $data)
->whereIn('carrier', $carriers)
->where('contract', $contract)
->where('phone_inlcuded', $phone_option);
return view('planresults')->with('plans', $query);
}
I am then trying to output the object into my view as follows
#foreach($plans as $plan)
<div class="panel price">
<div class="panel-heading arrow_box text-center">
<h3>{{$plan->Carrier->name}}</h3>
<h3>{{$plan->name}}</h3>
</div>
<div class="panel-body text-center">
<p class="lead" style="font-size:40px"><strong>${{$plan->price}} / month</strong></p>
</div>
<ul class="list-group list-group-flush text-center">
<li class="list-group-item">{{$plan->Carrier->name}}</li>
<li class="list-group-item">{{$plan->contract}} Month term contract</li>
#if($plan->phone_included == 0)
<li class="list-group-item">No phone included</li>
#else
<li class="list-group-item">Phone option included</li>
#endif
</ul>
<div class="panel-footer">
<a class="btn btn-lg btn-block btn-success" href="{{$plan->url}}">BUY NOW!</a>
</div>
</div>
<!-- /PRICE ITEM -->
#endforeach
No results are being displayed in my view so I assume my object is empty... I'm very confused and have been stuck on this for ages now
You never execute the query in $query. Read up: http://laravel.com/docs/5.0/queries
You'll need to specify one of the following:
$query->pluck()
$query->get()
$query->first()
I've just recently started using Laravel and I've got a problem, that my page is really slow.
The issue is that my queries are not ideal:
`
<div class="container">
#foreach ($product as $single)
<?php
$tagy = $single->tags()->get();
echo "<div class='item";
foreach($tagy as $tag) {
$premenna = Tags::where('id','=',$tag->tagID)->first();
echo " item".$premenna->id;
}
echo "'>";
?>
<div class="thumbnail porfolio">
<img class="image" src="<?=Croppa::url($single->destinationPath.'/'.$single->coverphoto, 250)?>" />
<div class="caption">
<div class="info">
<h4 style="font-weight: bold;">{{ $single->name }}</h5>
<p style="font-size: 15px; margin-bottom: 0px;">{{ $single->city }}</p>
<p class="date">{{ $single->date }}</p>
</div>
<div class="map-location">
<i class="fa fa-dot-circle-o fa-2x"></i>
</div>
<div class="tagy">
<?php
foreach($tagy as $tag) {
$variable= Tags::where('id','=',$tag->tagID)->orderBy('name')->first();
echo "<a class='hashtag tag".$variable->id."'>".$variable->name." </a>";
}
?>
</div>
</div>
</div>
</div>
#endforeach
</div>`
This is my Controller function:
protected function index()
{
$product = Product::where('active','=',1)->orderBy('date')->get();
$tagy = Tags::orderBy('name')->get();
return View::make('uvod',['product' => $product, 'tags' => $tagy]);
}
I've made one-to-many relationship between Product Class and ProductTag Class - that's the fucntion tags();
Could you please somehow help me optimizing the code (queries)? I would like to use #foreach function only once if possible - when i deleted the foreach functions inside the main one the page speed significantly improved.
Thank you very much for any kind of help :)