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.
Related
in my project I use Laravel 8, Livewire and Alpine.js.
My livewire toaster code (app\Http\Livewire\ToasterNotification.php):
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ToasterNotification extends Component
{
public $notifications = array();
protected $listeners = ['notificationUpdate', 'notificationRemove'];
public function notificationUpdate($notif)
{
array_push($this->notifications, $notif);
$this->dispatchBrowserEvent('toast-message-show');
}
public function notificationRemove($id)
{
unset($this->notifications[$id]);
}
public function render()
{
return view('livewire.toaster-notification');
}
}
Which executes this blade (resources\views\livewire\toaster-notification.blade.php) and he will call a blade component named toaster on "x-toaster":
<div
wire:poll.5s
aria-live="polite"
aria-atomic="true"
style="z-index:1200; position: absolute; top: 70px; right: 20px; min-height: 200px;"
>
#foreach($notifications as $i => $notification)
<x-toaster id="{{ $i }}" message="{{ $notification['message'] }}" color="{{ $notification['color'] }}"/>
#endforeach
</div>
(resources\views\components\toaster.blade.php):
<div
class="toaster toastAlert show border-{{ $color }}"
style="min-width: 250px"
data-autohide="false"
role="alert"
aria-live="assertive"
aria-atomic="true"
id="toastAlert{{ $id }}"
>
<div class="toast-header">
<svg class="bd-placeholder-img rounded mr-2 bg-{{ $color }}" width="20" height="20" focusable="false" role="img">
<rect width="100%" height="100%" fill="#ffffff00"></rect>
</svg>
<strong class="mr-auto">{{ $message }}</strong>
<button type="button" class="ml-2 mb-1 close" wire:click="notificationRemove({{ $id }})">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
I want improve the old system which reloads every 5s and use alpine along livewire if possible.
Actually my code looks like this :
<script defer src="https://unpkg.com/alpinejs#3.9.0/dist/cdn.min.js"></script>
<style> [x-cloak] { display: none !important; } </style>
<div
x-data="{show:false}"
#toast-message-show.window="
show = true;
setTimeout(() => show=false, 5000);
"
x-show="show"
x-cloak
>
#foreach($notifications as $i => $notification)
<x-toaster id="{{ $i }}" message="{{ $notification['message'] }}" color="{{ $notification['color'] }}"/>
#endforeach
</div>
But I have no display. I think there is an issue because nothing is executed while in the foreach. I've tried to add some test messages like
<h1 x-data="{ message: 'I ❤️ Alpine' }" x-text="message"></h1>
But nothing worked out.
Ok i found out the answer, it was messy but i had to remove the style and put the src in the blade app.
This morning my web app was working. After a few posts were made I tried to login and get the Undefined offset:0 error.
The only information I'm getting from Laravel is that it's in the file path laravel\framework\src\Illuminate\Support\Collection.php
On this file it's saying the error is on line 1688:
public function offsetGet($key)
{
return $this->items[$key];
}
Based on what I found online the issue is related to a bad data call. Perhaps trying to pull data that doesn't exist. I have looked through my database and last 4 Posts and Comments did not have any file attachments so I am not sure where to start looking.
Additionally, the code was written a few years ago by a coworker which makes it more difficult for me to decipher.
Here is my blade file:
#if(app('request')->input('gid'))
<input type="hidden" class="groupid_SeeMore" value="{{app('request')->input('gid')}}"/>
#endif
#foreach($timeline as $post)
<?php
/** the Below Script will grab all Group Names that go with the post and combine into a single stirng **/
$groups= array();
if(strpos($post->grouppermissions,"|")===false){
foreach(explode(',',$post->grouppermissions) as $id){
if($id!=""){
$group = DB::table('groups')->where('groupid','=',$id)->get();
// $groups[] .= $group[0]->name;
$groups[].=explode('|',$group[0]->name)[0];
}
}
}elseif(strpos($post->grouppermissions,"|")!==false){
foreach(explode(',',$post->grouppermissions) as $group){
if($group!="")$groups[].=explode('|',$group)[0];
}
}
$groups=implode(',',$groups);
?>
#if($post->status==0)
<div id="{{$post->id}}" class="Post_Container {{$post->type}} {{$post->type}}{{$post->id}}">
#endif
#if($post->status==1)
<div id="{{$post->id}}" class="Post_Container_Two {{$post->type}} {{$post->type}}{{$post->id}}"><center><p id="cldpsttxt">This post has been closed</center>
#endif
#if($post->favorite==0)
<div class="Post_Header Post_CCthbckgrnd" id="Post_Header{{$post->id}}">
#endif
#if($post->favorite==1)
<div class="Post_Header Post_CCthbckgrnd_Two" id="Post_Header{{$post->id}}"><center><p id="fvrtpsttxt">This post has been Favorited</center>
#endif
<input type="hidden" class="lastid" value="{{$post->id}}"/>
<input type="hidden" class="recent_comment" value="{{$post->recent_comment}}"/>
<div class="Profile_Picture_Container">
<div class="Profile_Picture"><img style="width:100%; height:100%;" src="https://www.vqventure.com/{{$post->pinfo[0]->img}}"/></div>
</div>
#if($groups !="")
<div class="Ginfo">
<center>
<!-- Below the if statement looks for posts with only one group permission-->
#if(strpos($groups, ",") === false)
<b>{{$groups}}</b>
#endif
<!-- Below the if statement looks for posts with multiple group permissions-->
#if(strpos($groups, ",") !== false)
<?php
$key = -1;
$perm = explode(',',$post->grouppermissions);
?>
#foreach(explode(',',$groups) as $group)
<?php $key++;?>
#if($group!="")
<b>{{$group}}</b>
#endif
#endforeach
#endif
</center>
</div>
#endif
<div class="Username_Container">
<div class="Username_Location">
<!--This will be the owner of the post name, for a business it will be the employee name-->
<div class="Username"><b>{{$post->pinfo[0]->name}}</b></div>
</div>
</div>
#if($post->bid != 0 && $post->bid==$user->bid || $post->bid==0 && $post->owner == $user->email)
<div class="Favorite_Container">
<button id="favorite" class="favorite{{$post->id}}" type="{{$post->favorite}}" type2="Timeline"value="{{$post->id}}"></button>
<button id="openclose" class="status{{$post->id}}" type="{{$post->status}}" type2="Timeline" value="{{$post->id}}"></button>
#if($user->bid!=0)
<div class="keywordTypes">
<select class="keywordType" id="{{$post->id}}">
<?php
$cat=$post->category;
if($cat=="")$cat="No category";
?>
<option value="{{$post->category}}" selected>{{$cat}}</option>
#foreach(explode('#$#',$types) as $type)
#if($type!="")<option value="{{$type}}">{{$type}}</option>#endif
#endforeach
</select>
</div>
#endif
</div>
#endif
<b style="position:absolute; top:10%; right:22%;">#{{$post->id}}</b>
#if($post->bid != 0 && $user->admin==1 && $post->bid==$user->bid || $post->owner == $user->email )
<div class="Delete_Button_Container">
<button class="PostDeleteButton" value="{{$post->id}}" id="DeleteMainBTN"></button>
</div>
#endif
</div>
<center>
<!-- Video -->
#if($post->videos!="[]")
<div class="Post_ContentContainer">
<div class="Post_Thumbnail_Container" pid="{{$post->id}}">
<a class="watchVideo" type="" id="{{$post->videos[0]->url}}">
<center> <div class="Post_Thumbnail">
<?php
$vpic = substr($post->videos[0]->url,0,-3)."jpg";
$vpic2 = str_replace("_correted","",$vpic);
?>
<img style="width:100%; height:100%;"src="https://www.vqventure.com/{{$vpic}}" onerror="this.src='https://www.vqventure.com/{{$vpic2}}'" class="video_thumbnail"/>
</div></center>
</a>
</div>
</div>
#endif
<!-- PDF -->
#if($post->else!="[]")
#if($post->else[0]->pics!="" || $post->else[0]->pdf!="")
<div class="Post_ContentContainer">
<div class="Post_Thumbnail_Container" pid="{{$post->id}}">
#if($post->else[0]->pdf!="")
<center><div class="Post_Thumbnail"><a id="wtfPDF" href="https://www.vqventure.com/<?php echo explode('$!$',$post->else[0]->pdf)[0];?>"><img id="PDF_postview" src="https://www.vqventure.com/imgs/pdf.jpeg"/></a></div></center>
#endif
<!-- Images -->
#if($post->else[0]->pics!="")
<center>
<div>
<ul class="Post_Thumbnail" style="list-style-type: none;" id="IMAGES">
#foreach(explode("$!$",$post->else[0]->pics) as $file)
#if($file !="")
<li><img id="IMG_postview" pid="{{$post->id}}"src="https://www.vqventure.com/{{$file}}" class="IMG_postview{{$post->id}}"/></li>
#endif
#endforeach
</ul>
</div>
</center>
#endif
</div>
</div>
<!--This is the end of if pics and pdf-->
#endif
#endif
</center>
<div class="Post_Info_Container2 Post_CCthbckgrnd">
<div class="Post_Info_Header">
<div class="Date_Container">
<!--Input the Date here -->
<?php
$date= explode(' ',$post->timestamp)[0];
$time= explode(" ",$post->timestamp)[1];
?>
<div class="Date"><center><b>{{$date}}</b></center></div>
</div>
<div class="VidTime_Container">
<!--Input the length of the video here -->
<div class="VidTime"><center></center></div>
</div>
<div class="TimeStamp_Container">
<!--Input the TimeStamp here -->
<div class="TimeStamp"><center><b>{{$time}}</b></center></div>
</div>
</div>
#if($post->videos!="[]")
<div class="Post_Title_Container">
<div class="Post_Title_Name"><center><b>Title:</b></center></div>
<div class="Post_Title">{{$post->videos[0]->title}}</div>
</div>
#endif
<div class="Post_Description_Container">
<div class="Post_Description_Name"><center><b>Description:</b></center></div>
<div class="Post_Description">
#if($post->videos!="[]") {!!nl2br(e($post->videos[0]->description)) !!}
#else
<p>{!! nl2br(e($post->else[0]->post)) !!}</p>
#endif</div>
</div>
</div>
#if($showComments=="yes")
<div class="Post_CommentContainer" id="Make_Comment{{$post->id}}">
<textarea class="Post_Comment_TextContainer Post_Comment_TextContainer{{$post->id}}" placeholder="Comment" maxlength="300" rows="2" onkeydown="expandtext(this);" ></textarea>
<input type="hidden" class="gperms{{$post->id}}" value="{{$post->grouppermissions}}"/>
<button class="ChooseFile"><label id="CF" for="CFile{{$post->id}}"></label> <input type="file" name="imgs[]" class="CFile" id="CFile{{$post->id}}" multiple/></button>
<input type="hidden" value="{{ csrf_token() }}" class="CToken{{$post->id}}"/>
<div class="Post"><button id="Pst" pid="{{$post->id}}" ></button></div>
</div>
#if($post->comments!="[]")
<div class="Post_CommentFeedContainer Post_CommentFeedContainer{{$post->id}}">
#foreach($post->comments as $comment)
#if($comment->owner==$user->email)
<div class="Owner_CommentContainer" id="CommentId{{$comment->id}}">
<div class="OCC_Left">
<div class="C_Owner_Name"><center>{{$comment->info[0]->name}}</center></div>
</div>
<div class="OCC_Right">
<div class="C_TimeStamp"><center>{{$comment->timestamp}}</center></div>
#if($post->bid != 0 && $post->bid==$user->bid || $post->bid==0 && $comment->owner == $user->email)
<button class="Delete_Button" value="{{$comment->id}}" id="C_dltbtn" type="Timeline"></button>
#endif
</div>
<div id="CTwo">{!!nl2br(e($comment->comment)) !!}</div>
#if($comment->files!="")
<div class="Owner_Media_Container CommentImages" cid="{{$comment->id}}">
#foreach(explode('#%%#',$comment->files) as $file)
#if(strpos($file, '.pdf') === false && $file!="")<div class="Media_Thumbnail"><img style="width:100%; height:100%;" src="https://www.vqventure.com/{{$file}}" class="CImage{{$comment->id}}"/></div>
#elseif(strpos($file, '.pdf') !== false)<div class="Media_Thumbnail"><img style="width:100%; height:100%;" src="https://www.vqventure.com/imgs/pdf.jpeg"/></div>
#endif
#endforeach
</div>
#endif
</div>
#endif
#if($comment->owner!=$user->email)
<div class="Guest_CommentContainer CommentImages" id="CommentId{{$comment->id}}" cid="{{$comment->id}}">
<div class="GCC_Left">
#if($comment->files!="")
<div class="Guest_Media_Container">
#foreach(explode('#%%#',$comment->files) as $file)
#if(strpos($file, '.pdf') === false && $file!="")<div class="Media_Thumbnail" ><img style="width:100%; height:100%; " src="https://www.vqventure.com/{{$file}}" class="CImage{{$comment->id}}"/></div>
#elseif(strpos($file, '.pdf') !== false)<div class="Media_Thumbnail" ><img style="width:100%; height:100%; " src="https://www.vqventure.com/imgs/pdf.jpeg"/></div>
#endif
#endforeach
</div>
#endif
#if($comment->files!="")
<div class="C_TimeStamp_Guest_Two"><center>{{$comment->timestamp}}</center></div>
#endif
#if($comment->files=="")
<div class="C_TimeStamp_Guest"><center>{{$comment->timestamp}}</center></div>
#endif
</div>
<div class="GCC_Right">
<div class="C_Guest_Name"><center>{{$comment->info[0]->name}}</center></div>
#if($post->bid != 0 && $post->bid==$user->bid && $user->admin==1|| $post->bid==0 && $comment->owner == $user->email)
<button class="Delete_Button" value="{{$comment->id}}" id="C_dltbtn"></button>
#endif
</div>
<div id="COne">{!! nl2br(e($comment->comment)) !!}</div>
</div>
#endif
#endforeach
</div>#endif
#if($post->comments!="[]") <div class="ExpandComment_Container" ><center><div class="Display_AllComments"><button class="Show_All_Comments" id="{{$post->id}}" action=1>Expand Comments...</button></div></center></div> #endif
#endif
</div>
<div id="loading-image" style="display:none; top: 10px; position:relative;"><i>Uploading Comment Please wait....</i></div>
#endforeach
And here is my controller:
public function timeline(Request $request){
if(!isset($this->user->email)){
if(!$request->queryType)return redirect('/');
}
if(isset($this->user->email)){
$email = $this->user->email;
// This needs to query where permissions are equal to the email and the owner = email
$mygroups= groups::where('owner','=',$email)->orwhere('groupadmin','LIKE',"%$email%")->orwhere('members','LIKE',"%$email%")->get();
$groups= "";
foreach($mygroups as $group){
if($group!="")$groups.=','.$group->groupid."$!$".$group->name;
}
$groups=explode(',',$groups);
$timeline = timeline::with('else','videos','comments');
if(!$mygroups->isEmpty()){
$timeline = $timeline->where(function ($query) use($groups) {
for ($i = 0; $i < count($groups); $i++){
if($groups[$i]!=""){
$gid=explode('$!$',$groups[$i])[0];
$gname = explode('$!$',$groups[$i])[1];
$query->orWhere('grouppermissions', 'like', '%' . $gid .'%')
->orWhere('grouppermissions', 'like', '%' . $gname .'%');
}
}
});
$timeline=$timeline->orwhere('owner','=',$this->user->email);
}
if($mygroups->isEmpty()) $timeline=$timeline->where('owner','=',$this->user->email);
if($request->queryType=="Original")$timeline=$timeline->orderBy('id','desc');
if($request->queryType=="Recent" || !$request->queryType)$timeline = $timeline->orderBy('recent_comment','desc')->orderBy('timestamp','desc');
$timeline=$timeline->limit(15)->get();
foreach($timeline as $g){
//THis is for grab business or user info for a post , maynot need it
$pinfo = user::where('email','=',$g['owner']);
$pinfo = $pinfo->get();
$g['pinfo']=$pinfo;
if($g['pinfo'][0]['name']==null)$g['pinfo'][0]['name']=$g['pinfo'][0]['companyname'];
$g['type']="";
foreach($g['comments'] as $c){
$info = user::select("name","img","phone")->where('email','=',$c['owner']);
$info = $info->limit(1)->get();
$c['info']=$info;
$ctimestamp = strtotime($c['timestamp']);
$cdate = new DateTime("#".$ctimestamp); // will snap to UTC because of the
$cdate->setTimezone(new DateTimeZone('America/New_York'));
$c['timestamp']=$cdate->format('Y-m-d H:i:s');
}
$timestamp = strtotime($g['timestamp']);
$date = new DateTime("#".$timestamp); // will snap to UTC because of the
$date->setTimezone(new DateTimeZone('America/New_York'));
$g['timestamp']=$date->format('Y-m-d H:i:s');
}
//if($this->user->admin==1){
//the $list will need to be the businesses branches data exploded by ','
$branches = DB::table('users')
->wherein('email',explode(',',$this->user->branches))->select('bid','email','name')
->get();
// The next few lines are for invitessent
// }
$sess= $this->user->invitessent;
$emails = explode(",",$sess);
$info = array();
foreach($emails as $email){
$test =user::select("name","img")->where('email','=',$email)->limit(1)->get();
if(!$test->isEmpty())$info[]=$test;
}
$website = $this->user->website;
$posts = DB::table('inquiry')->select('*')->where('bid','=', $this->user->bid)->latest()->get();
$types="";
if($this->user->bid!=0){
$biz= user::select('keywords')->where(array(['bid','=',$this->user->bid],['admin','=',1]))->limit(1)->get();
$types = $biz[0]->keywords;
}
if(!$request->queryType)return view('layouts.Timeline',['timeline'=>$timeline,'types'=>$types,'branches'=>$branches, 'posts'=>$posts ,'showComments'=>'yes','user'=>$this->user,'gp_admins'=>'','gp_members'=>'','type'=>'timeline']);
if($request->queryType)return view('includes.Timeline_Posts',['timeline'=>$timeline,'types'=>$types,'user'=>$this->user,'showComments'=>'yes']);
}
}
In addition to fixing the issue and allowing users to access their data, I am hoping someone can help me understand what caused the issue in the first place.
The entire project is in the process of being re-built and I would like to avoid issues with the revamp from lessons learned on this structure. However, I need a quick fix to get it back online until we complete the revamp.
UPDATE:
I changed the code to use ->first instead of [0] but its still giving the same issue. I think the issue is related to the following line of code but not sure how....
<?php
$key = -1;
$perm = explode(',',$post->grouppermissions);
?>
#foreach(explode(',',$groups) as $group)
<?php $key++;?>
So far I have not been able to get any progress...
How do I implement a scope where in the user will claim a reward on a specific level and once they claim their rewards, the reward field will no longer display the reward that they have claimed. So for example:
The user is on level 20, on his reward panel, there are 3 available rewards to be claimed, level 10, 15 and 20. So if the user claimed the level 10 reward, it will no longer display on the panel except for level 15 and 20 rewards.
Here is the code for the blade:
#foreach(App\LevelRewards::getRewards()->get() as $rewards)
#if(Auth::user()->level >= $rewards->level_required || Auth::user()->level == $rewards->level_required)
#if(App\ClaimReward::claimLevel()->get())
<div class="col-lg-2 col-md-3 col-sm-6 col-xs-6" style="margin: 5px 0px;">
<div class="hovereffect">
<a href="#" class="d-block mb-4 h-100">
<input type ="hidden" name="id" value="{{$rewards->id}}"/>
<img class="img-responsive" src="{{asset('rewards_img/'.$rewards->picture)}}" alt="">
</a>
<div class="overlay">
<h2 style="font-size: 14px;">{{$rewards->details}}</h2>
#if($rewards->type == 'physical')
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#claimPhysical" data-details="{{$rewards->details}}" data-id="{{$rewards->id}}" data-level="{{$rewards->level_required}}" data-physical="{{$rewards->item_name}}">
CLAIM
</button>
#else
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#claimDigital" data-id="{{$rewards->id}}" data-level="{{$rewards->level_required}}" data-physical="{{$rewards->item_name}}">
CLAIM
</button>
#endif
</div>
<div style="background: #2d2d2d; padding: 9px;">
<span class="credits_top">Required Level: <span>{{$rewards->level_required}}</span></span>
<p>{{$rewards->item_name}}</p>
</div>
</div>
#endif
#endif
#endforeach
And this is the code for the model ClaimReward model:
public function scopeClaimLevel2($query)
{
return $query->join('level_rewards','level_rewards.id','=','claim_rewards.reward_id')->select('level_rewards.*');
}
Any links and source of information regarding this question will be highly appreciated. Thank you.
Edit: I tried;
public function scopeClaimLevel($query)
{
return $query->join('claim_rewards','claim_rewards.reward_id','=','level_rewards.id')->select('level_rewards.*');
}
public function scopeGetRewards($query)
{
return $query
->join('claim_rewards','claim_rewards.reward_id','=','level_rewards.id')
->whereDoesntHave('claimLevel', function (Builder $query) {
$query->where('claim_rewards.status', '=', '0');
})
->select('level_rewards.*');
}
But it says
Call to undefined method Illuminate\Database\Query\Builder::getRelated()'
add another table that will hold rewards thats user already claimed,
and in the foreach check if this reward id exists in this user claimed rewards,
if not so show it and if yes so skip it.
the table will hold 2 fields:
1) user_id
2) rewards_id
regarding the comments above,
and after your edit to what you tried,
looks like the order of the query is wrong... put whereDoesntHave before the select,
and change to implementation of it as wrote in Laravel documentation example.
try this:
public function scopeClaimLevel2($query)
{
return $query
->join('claim_rewards','claim_rewards.reward_id','=','level_rewards.id')
->whereDoesntHave('claim_rewards', function (Builder $query) {
$query->where('status', '=', '0');
})
->select('level_rewards.*');
}
edit:
try to change the join, as wrote here: https://laravel.com/docs/5.4/queries#joins
build the join and in it's function set how to join and where status=0
return $query
->join('claim_rewards', function ($join) {
$join->on('claim_rewards.reward_id', '=', 'level_rewards.id')->where('status', '=', '0');
})
->select('level_rewards.*');
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();
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 :)