Laravel - ToDateString() Behaves abnormally on Live Server - php

In my Laravel-5.8, I have this code:
Controller
public function index()
{
$userCompany = Auth::user()->company_id;
$leaverequests = HrLeaveRequest::where('company_id', $userCompany)
->orderBy('created_at', 'desc')
->get();
$incompleteCount = $leaverequests->filter(function ($item) {
return (
$item->leave_status == 2 ||
$item->leave_status == 3 ||
$item->leave_status == 4
);
})
->count();
$currentstatus = HrLeaveRequest::select('leave_status')
->where('is_resumption_activated', 1)
->whereIn('leave_status', array(3, 4))
->where('resumption_date', '<=', Carbon::now()->toDateString())
->orderBy('created_at', 'DESC')
->first();
return view('leave.employee_leave_requests.index')
->with([
'leaverequests' => $leaverequests,
'incompleteCount' => $incompleteCount
])
->with('currentstatus', $currentstatus);
}
Model:
protected $dates = [
'resumption_date',
];
View
<div class="panel-heading clearfix">
<div class="container-fluid">
#can('leave_request_create')
#if (! $leaverequests->count() || $currentstatus)
<div style="margin-bottom: 10px;" class="row">
<div class="col-lg-12">
<a class="btn btn-info" href="{{ route("leave.employee_leave_requests.create") }}">
Add Leave Request
</a>
</div>
</div>
#elseif (! $currentstatus)
<div style="margin-bottom: 10px;" class="row">
</div>
#endif
#endcan
</div>
</div>
The Purpose is to make the "Add Leave Request" when the condition is fulfilled. I tested it on my Windows Local System, and it works fine.
But when I deployed to Linux Ubuntu server, the "Add Leave Request" remains hidden even when the condition is fulfilled.
But when I removed this code:
where('resumption_date', '<=', Carbon::now()->toDateString())
from the Linux server, it becomes visible (it works).
PHP Version for both local sytem and Ubuntu server is PHP-7.3.
How do I get this resolved.

Related

routes/web route me to another route

My web doesn't seem to be directing to the correct page.
Here is my blade
<div class="container">
<div class="col-lg-12 d-flex justify-content-between align-items-center">
<h2>Informations</h2>
<a href="{{ route('add-new-information') }}" class="btn text-success">
<i class="fas fa-plus-circle fa-2x"></i>
</a>
</div>
<hr>
<div class="row d-flex justify-content-center align-items-center mt-5" style="max-height: 500px !important; overflow-y: scroll">
#foreach ($informations as $info)
<div class="card col-sm-11 p-0 mb-4 clickable-item" onclick='window.location = "{{ route('admin-informations', ['id' => $info->id]) }}"'>
...
</div>
#endforeach
</div>
</div>
Here is my routes/web
Auth::routes();
Route::group(['middleware' => ['auth'], 'prefix' => '/',], function () {
Route::get('/', function () {
return redirect('/home');
});
Route::group(['prefix' => 'admin'], function() {
Route::get('/informations', [App\Http\Controllers\InformationController::class, 'index'])->name('informations');
Route::get('/informations/{id}', [App\Http\Controllers\InformationController::class, 'indexAdminInfo'])->name('admin-informations');
Route::get('/informations/add-new-information', [App\Http\Controllers\InformationController::class, 'add'])->name('add-new-information');
});
});
and here is my controller
public function indexAdminInfo($id){
$information = Information::find($id);
// $comments = Comment::where('information_id', $id)->orderByDesc('created_at')->get();
$ack_count = Acknowledge::where('information_id', $id)->count();
$user_ack = Acknowledge::where([
['information_id', '=', $id],
['user_id', '=', Auth::user()->id],
])->first();
$ack = 'FALSE';
if($user_ack != null){
$ack = 'TRUE';
}
return view('adminviews/infoadmin', compact('information', 'ack_count', 'ack', 'user_ack'));
}
public function add(){
return view('adminviews/addinfo');
}
For some reason, when I click the a tag with the href {{ route('add-new-information') }} to go to the add page 'adminviews/addinfo',
instead the page will go to the 'adminviews/infoadmin' page, which will cause an error, because no parameters are being sent.
I tried checking the code, but it looks correct to me. Can anybody find an error on this?
the problem is with your routes:
these two routes are ambiguous:
Route::get('/informations/{id}');
Route::get('/informations/add-new-information');
just think of below scenario:
router wants to route, this url : /information/add-new-information
router will hit the first defined route, because it is compatible with the definition ('/informations/{id}')
Note :{id} is a variable and can be any string
so it will go with this.
Solution
write the more restricted route first,
and more general route later:
Route::get('/informations/add-new-information');
Route::get('/informations/{id}');

Display only if query is found via search in Laravel using php

I have referral code search box that query referral codes. this code must be available before user can register. So basically on Auth.register I have two boxes, firs t box holds the referral code search box and the other one is the registration box. My goal is to hide first the registration box and appear only if the code has found.
RegisterController
public function index(Request $request)
{
$keyword = $request->get('search');
$referral = Referral::where('code', 'LIKE', '%'.$keyword.'%')->get();
if (count ( $referral ) > 0)
return view ( 'Auth.register')->withDetails ( $referral )->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided is not existing.' );
}
register.blade.php
<!-- THIS IS THE FIRST BOX THAT HOLDS THE CODE SEARCH BOX -->
<div class="card mx-4">
<div class="card-body p-4">
<h1>Referral Code</h1>
<p class="text-muted">Please provide the referral code given to you by your collector</p>
#if(isset($message))
<div class="alert alert-success">
{{ $message }}
</div>
#endif
{!! Form::open(['method' => 'GET', 'url' => '/register', 'class' => 'form-inline my-2 my-lg-0', 'role' => 'search']) !!}
<div style="width: 100%;">
<input type="text" class="form-control" name="search" style="width: 100%;" placeholder="Enter your referral code here!">
</div>
<div style="width: 150px; margin: auto; margin-top: 20px; ">
<button class="btn btn-success btn-default" type="submit">
<i class="fa fa-search"></i> Check Availability
</button>
</div>
{!! Form::close() !!}
</div>
</div>
<!-- THIS IS THE 2ND BOX THAT HOLDS THE REGISTRATION FORM -->
#if(isset($details))
<div class="card mx-4">
<div class="card-body p-4">
#foreach($details as $code)
#if($code->status==0)
<h2>Code is available</h2>
#else
<h2>Code is already taken</h2>
#endif
#endforeach
... the rest of registration form ...
</div>
</div>
#endif
My problem now is, the #details is displaying the current rows of "Referrals"
Is there a way that query from this line,
$referral = Referral::where('code', 'LIKE', '%'.$keyword.'%')->get();
should only display if the result is match from $keyword?
because currently the page is look like this
Thanks!
I think you want something like to match the keyword against your database. So instead of partial matching use exact matching.
public function index(Request $request)
{
$keyword = $request->get('search');
$referral = Referral::where([
['code', $keyword],
['status', 0]
])->first();
if ($referral)
return view ( 'Auth.register')->withDetails ( $referral )->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided does not exist or already used.' );
}
And in view you need not to use the following lines.
#foreach($details as $code)
#if($code->status==0)
<h2>Code is available</h2>
#else
<h2>Code is already taken</h2>
#endif
#endforeach
Just add your registration form after #if(isset($details)).
Its weird how you are doing this. You can use AJAX to do it in a single page

Slug not work properly

I am try create slug with laravel on admin its work but on front-end view its work too except one problem, i have four article and work nice on admin but when on view front end its always open same article even-tough slug is different URL.
Controller code
public function singleArticle($slug){
Article::where('slug', '=', $slug)->increment('viewed');
$navi['country'] = Country::get();
$navi['genre'] = Genre::get();
$articles = Article::orderBy('created_at','desc')->limit(3)->get();
$latest_movies = Movie::where('type', '=', 'movie')->orderBy('created_at','desc')->limit(4)->get();
$latest_tv = Movie::where('type', '=', 'tv')->orderBy('created_at','desc')->limit(4)->get();
$most_viewed_movies = Movie::where('type', '=', 'movie')->orderBy('viewed','desc')->limit(3)->get();
$most_viewed_tv = Movie::where('type', '=', 'tv')->orderBy('viewed','desc')->limit(4)->get();
$most_viewed_article = Article::orderBy('created_at','desc')->orderBy('viewed','desc')->limit(4)->get();
$article = Article::where('slug', '=', $slug)->first();
and for view front end
#if(count($articles) > 0)
<div class="articles_list">
#foreach($articles as $article)
<div class="col-md-6">
<div class="article_item row">
<div class="article_info">
#if($article->thumb)
<a href="{{route('articles.single',$article->slug)}}"><img class="img-responsive" src="{{ url(Image::url($article->thumb,350,200,array('crop'))) }}" alt="{{$article->title}}">
#else
{{-- <img class="img-responsive" src="{{ url(Image::url($article->thumb,250,250,array('crop'))) }}" alt="{{$article->title}}"> --}}
#endif
<div class="artice_title"><h3>{{$article->title}}</h3></div>
<div class="article_time">
<span class="author">By Admin</span>
<span class="cateogry">Category</span>
<span class="time">{{date('F d, Y', strtotime($article->created_at))}} </a></span></div>
<!--<div class="article_descr">
<?php echo mb_substr($article->content, 0, 200) . ' ...'; ?>
</div>
<a class="btn btn-default read_more" href="{{route('articles.single',$article->id)}}">Read more</a> -->
</div>
</div>
</div>
#endforeach
</div>
<div class="clearfix"></div>
<div class="text-center col-xs-12">
{{$articles->links()}}
</div>
#else
<div class="col-xs-12">
Nothing found in there
</div>
#endif
For routing below code :
// Category
Route::get('category/{slug}', ['as' => 'category.index', 'uses' => 'CommonController#categoryIndex']);
// Articles
Route::get('articles', ['as' => 'articles.index', 'uses' => 'CommonController#articleIndex']);
// Specific article
Route::get('articles/{slug}', ['as' => 'articles.single', 'uses' => 'CommonController#singleArticle']);
thanks before.
It is just issue of naming convention.Please choose different names for variables.
#foreach($articles as **$article**). It is in your view which have $article variable.
**$article** = Article::where('slug', '=', $slug)->first(); It is in your controller. so it is just because of conflict.

Laravel 5.1 Order by multiple times

I'm trying to make something 'like facebook'...
Now, I want to order the posts using the created_at table. But also, if the post has a comment, order it by the comments. So actually, the posts need to be ordered by the comment and if the post doesn't have a comment, then it needs to order by the post (acting as a fallback).
To make it all clear, I have made some screenshots:
So this is just one post, nothing to mention about it.
But when I add a second post with 456 as content, that post needs to be on top, wich works:
All good, but now, when I add a comment, the message with the comment needs to be on top (since it has a newer post). This is my problem, it doesn't work:
So here is my code:
Controller:
public function index()
{
$getallposts = DB::table('social_posts')->select('users.*', 'social_posts.created_at as PostAt', 'social_posts.description', 'users_images.*', 'social_posts.id as PostID')
->join('users', 'social_posts.user_id', '=', 'users.id')
->join('users_images', 'social_posts.user_id', '=', 'users_images.user_id')
->orderBy('social_posts.created_at', 'DESC')
->whereNull('social_posts.deleted_at')
->get();
//var_dump($getallposts);
$getallcomments = DB::table('social_comments')->select('users.*', 'social_comments.created_at as PostAt', 'social_comments.description', 'social_comments.post_id', 'users_images.*')
->join('users', 'social_comments.user_id', '=', 'users.id')
->join('users_images', 'social_comments.user_id', '=', 'users_images.user_id')
->orderBy('social_comments.created_at', 'ASC')
->whereNull('social_comments.deleted_at')
->get();
//var_dump($getallposts);
$getrandomusers = DB::table('users')->select('users.*', 'users.id as UID', 'users_images.*')
->join('users_images', 'users.id', '=', 'users_images.user_id')
->orderByRaw('RAND()')
->where('users.id', '!=', Auth::id())
->take(16)
->get();
return view('dashboard', ['posts' => $getallposts, 'comments' => $getallcomments, 'randomuser' => $getrandomusers]);
}
View:
#foreach($posts as $post)
<div class="row row-sm">
<div class="col-sm-12">
<div class="card">
<div class="card-heading">
<a href class="pull-left w-32 m-r" href="{!! url(Auth::user()->slug) !!}">
<img src="{!! asset('avatars/'.$post->image) !!}" class="w-full img-circle">
</a>
<div class="clear">
{!! ucwords($post->firstname) !!} {!! ucwords($post->lastname) !!}
<div class="text-xxs font-thin text-muted">{!! \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $post->PostAt)->diffForHumans() !!}</div>
</div>
</div>
<div class="card-body">
<p>
{!! nl2br(e($post->description)) !!}
</p>
<p style="color:grey;font-size:10px;">Aantal likes - {!! \Cussion\SocialReaction::where('post_id', $post->PostID)->count() !!} {!! (\Cussion\SocialReaction::where('post_id', $post->PostID)->count() == 1) ? 'reactie' : 'reacties' !!} </p>
<p style="font-size:14px;">Leuk vinden</p> <!-- KNOP OM STATUS TE LIKEN -->
</div>
<div class="list-group no-radius no-border" style="background-color:#F5F5F5;">
#foreach($comments as $comment)
#if($comment->post_id == $post->PostID)
<div class="md-list-item">
<div class="md-list-item-left">
<img src="{!! asset('avatars/'.$comment->image) !!}" class="w-full circle">
</div>
<div class="md-list-item-content">
<small class="font-thin">{!! ucwords($comment->firstname) !!} {!! ucwords($comment->lastname) !!}</small>
<div class="text-xxs font-thin text-muted" style="font-size:12px;">{!! nl2br(e($comment->description)) !!}</div>
<div class="text-xxs font-thin text-muted" style="font-size:10px;">{!! \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $comment->PostAt)->diffForHumans() !!}</div>
</div>
</div>
#endif
#endforeach
<div class="md-list-item">
<form action="{!! url('/dashboard') !!}" method="post" role="form">
{!! csrf_field() !!}
<div class="input-group">
<input type="text" class="form-control" name="message" placeholder="Wat wil je reageren?">
<input type="hidden" name="post_id" value="{!! $post->PostID !!}">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Reageer</button>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endforeach
And my database structure:
Demo can be found on http://cussion.org
You can easily use the concept of "touching parent timestamps", read more about it here https://laravel.com/docs/5.1/eloquent-relationships#touching-parent-timestamps
But here is a simple explanation, since the comments are related to posts, you can instruct the comments model to update the updated_at field of the parent post whenever a comment is added or even edited, so now you have the post's updated_at always up-to-date.
I would defer the sorting to your PHP script. Writing that kind of sorting algorithm in MySQL could get very complicated and hard to read. Instead, I would store the results in a collection and then sort using a custom function. Something like this:
$getallposts = DB::table('social_posts')
->select('users.*', 'social_posts.created_at as PostAt', 'social_posts.description', 'users_images.*', 'social_posts.id as PostID')
->join('users', 'social_posts.user_id', '=', 'users.id')
->join('users_images', 'social_posts.user_id', '=', 'users_images.user_id')
->whereNull('social_posts.deleted_at')
->get();
$getallcomments = DB::table('social_comments')
->select('users.*', 'social_comments.created_at as PostAt', 'social_comments.description', 'social_comments.post_id', 'users_images.*')
->join('users', 'social_comments.user_id', '=', 'users.id')
->join('users_images', 'social_comments.user_id', '=', 'users_images.user_id')
->orderBy('social_comments.created_at', 'ASC')
->whereNull('social_comments.deleted_at')
->get();
//add comments to their posts and put post
foreach($getallposts as $post){
$post->comments = [];
foreach($getallcomments as $comment){
if($comment->post_id == $post->PostID){
$post->comments[] = $comment;
}
}
}
$getallposts->sortBy(function($item, $key){
//run your sorting logic here based on comments and created_at date
});
Even better yet, convert your sql queries to Eloquent objects and this gets MUCH MUCH easier.

Laravel join query returns Null while raw query has a value

I'm stuck with a really stupid query.
I tried to find the solution for like days, but nothing helped and so I don't find the answer.
I want to get the newest reaction from a table, to display the username.
First of all, these are my Database schemes:
comments (Has a model Comment)
threads (Has a model Thread)
So My raw query looks like this:
select `comments`.`username` from `comments` inner join `threads` on `comments`.`tid` = `threads`.`tid` where `comments`.`deleted_at` is null and `threads`.`cid` = '$categorie->id' order by `comments`.`posted_at` desc limit 1
A var_dump() of $categorie->id returns int(3) where the 3 stands for the categorie number.
When I execute the query (raw) in navicat, it returns this:
What is good, since that is the corract value it needs to return.
However when I rebuild this query in "Laravel-eloquent-style", the query looks like this:
Comment::join('threads', 'comments.tid', '=', 'threads.tid')->where('threads.cid', '=', $categorie->id)->orderBy('comments.posted_at', 'DESC')->pluck('comments.username')
Be aware of that the query is build in a foreach loop and has an if-statement before. But that will be sown later on.
This does return nothing.
When I inspect elements, I just got nothing.
I tried the DB::select(DB::raw('query')), but that doesn't work either.
I render my page in the ForumController:
public function index()
{
$forums = Forums::orderBy('disp_order', 'asc')->get();
$categories = Categorie::orderBy('disp_order', 'asc')->get();
return View::make('index')->with('forums', $forums)->with('categories', $categories);
}
This works fine, and the view looks like this:
#foreach($forums as $forum)
<div class="panel-group col-sm-12">
<div class="panel panel-default">
<div class="panel-heading" style="background-color: {{ $forum->color }};">
<i class="fa fa-folder-open-o fa-fw"></i>
<strong>{{ $forum->name }}</strong>
</div>
<div id="forum4" class="panel-collapse collapse in">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>Forum naam</th>
<th class="text-right">Topics</th>
<th class="">Laatste post info</th>
</tr>
</thead>
<tbody>
<tr>
#foreach($categories as $categorie)
#if($categorie->fid == $forum->fid)
<td class="topic-marker-forum">
<i class="fa fa-comments fa-3x"></i>
</td>
<td class="col-md-6 col-sm-6">
<div><strong>{{ $categorie->name }}</strong></div>
<div class=""><em>{{ $categorie->description }}</em></div>
</td>
<td class="col-md-1 col-sm-1 text-right"><span class="badge">{{ Thread::where('cid', '=', $categorie->id)->remember(15)->count() }}</span></td>
<td class="col-md-4 col-sm-4 ">
<div>
#if(Thread::where('cid', '=', $categorie->id)->exists() && Comment::join('threads', 'comments.tid', '=', 'threads.tid')->where('threads.cid', '=', $categorie->id)->orderBy('comments.posted_at', 'DESC')->exists())
{{ Helper::HTMLFilter(Thread::where('cid', '=', $categorie->id)->orderBy('date_posted', 'DESC')->pluck('title')) }}<br>
<i class="fa fa-clock-o"></i> {{ \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', Comment::join('threads', 'comments.tid', '=', 'threads.tid')->where('threads.cid', '=', $categorie->id)->orderBy('comments.posted_at', 'DESC')->pluck('posted_at'))->format('d/m/Y H:i') }}<br>
<i class="fa fa-user"></i> {{ Comment::join('threads', 'comments.tid', '=', 'threads.tid')->where('threads.cid', '=', $categorie->id)->orderBy('comments.posted_at', 'DESC')->pluck('comments.username') }}
#else
<b>-</b>
#endif
</div>
</td>
</tr>
#endif
#endforeach
</tbody>
</table></div>
</div>
</div>
</div>
#endforeach
The strangest part is that this:
{{ \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', Comment::join('threads', 'comments.tid', '=', 'threads.tid')->where('threads.cid', '=', $categorie->id)->orderBy('comments.posted_at', 'DESC')->pluck('posted_at'))->format('d/m/Y H:i') }}
Just works. Like nothing is wrong with that, when I call that item, it returns the correct value.
My Models are just normal;
<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Comment extends Eloquent
{
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
protected $table = 'comments';
public $timestamps = false;
public function user()
{
return $this->belongsTo('User', 'uid');
}
}
And
<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Thread extends Eloquent
{
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
protected $table = 'threads';
public $timestamps = false;
}
Hope someone can help me out!
Try something like this
Comment::with(['threads'=>function($query) use ($categorie){
$query->where('threads.cid',$categorie->id)
->whereNull('comments.deleted_at');
}])
->orderBy('comments.posted_at', 'DESC')
->limit(1)
->pluck('comments.username');
If you need - were 'deleted_at' not null
->whereNotNull('comments.deleted_at');
DB::table('coments')
->join('threads', 'comments.tid', '=', 'threads.tid')
->where('threads.cid',$categorie->id)
->whereNull('comments.deleted_at');
->orderBy('comments.posted_at', 'DESC')
->limit(1)
->pluck('comments.username');

Categories