Laravel - showing all posts using carbon - php

So I used carbon in my project and now it shows me all posts made today, and that's okay for me. But now I need to see posts from past days, how can I do that with carbon? I would like something like href link for other past days in my view, home.blade.php
Here is my HomeController with carbon
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Post;
use DB;
use Auth;
use Carbon\Carbon;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$date = new Carbon(request('date'));
$posts = Post::where('user_id', Auth::id())
->whereDate('created_at','=',$date)
->orderBy('created_at', 'DESC')
->paginate(30); //add {{ $posts->links() }} if paginate is enabled
return view('home', compact('date', $date))->with('posts', $posts);
}
}
Here is my home.blade.php
#extends('layouts.theme')
#section('content')
<style>
body{
margin: 0;
background-color: #EBEBEB;
}
</style>
<div class="mainl">
<div class="row">
<div class="columna">
<h1>{{ Auth::user()->name }}</h1>
<hr>
</div>
<div class="columns">
<a href="{{ route('logout') }}" id="logout"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('LOGOUT') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
</div>
</br></br></br>
#if(count($posts)> 0)
<table>
<thead>
<tr>
<th>BR.KESICE</th>
<th>IME I PREZIME</th>
<th>BR.TELEFONA</th>
<th>POSAO</th>
<th>CIJENA</th>
<th>PLACANJE</th>
<th>POPUST</th>
<th>DATUM PREUZ.</th>
<th>DATUM IZDAV.</th>
<th>SMJENA</th>
<th>RADNIK</th>
<th>STATUS</th>
<th>IZMIJENI</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->br_kesice}}</td>
<td>{{$post->ime}}</td>
<td>{{$post->br_telefona}}</td>
<td>{{$post->posao}}</td>
<td>{{$post->cijena}}</td>
<td>{{$post->placanje}}</td>
<td>{{$post->popust}}</td>
<td>{{$post->datum_preuz}}</td>
#if($post->status == 1)
<td>/</td>
#else
<td>{{$post->datum_izdav}}</td>
#endif
<td>{{$post->smjena}}</td>
<td>{{$post->radnik}}</td>
<td>
#if($post->status == 0)
<span class="label label-primary" id="statusdeaktivan">Deaktivan</span>
#elseif($post->status == 1)
<span class="label label-success" id="statusaktivan">Aktivan</span>
#elseif($post->status == 2)
<span class="label label-danger" id="statusdeaktivan">Rejected</span>
#else
<span class="label label-info" id="statusdeaktivan">Deaktivan</span>
#endif
</td>
#if($post->status == 3)
#else
<td><i class="far fa-edit"></i></td>
#endif
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>UKUPAN IZNOS: {{ Auth::user()->posts()->whereDate('created_at','=',$date)->sum('cijena')}}€</th>
<th>KARTICA: {{ Auth::user()->posts()->whereDate('created_at','=',$date)->where('placanje', 'Kartica')->sum('cijena')}}€</th>
<th>GOTOVINA: {{ Auth::user()->posts()->whereDate('created_at','=',$date)->where('placanje', 'Kartica')->where('placanje', 'Gotovina')->sum('cijena')}}€</th>
<th>VIRMAN: {{ Auth::user()->posts()->whereDate('created_at','=',$date)->where('placanje', 'Kartica')->where('placanje', 'Virman')->sum('cijena')}}€</th>
</tr>
</tfoot>
</table>
{{ $posts->links() }}
#else
<p>Trenutno nema unosa.</p>
#endif
</div>
#endsection
Any solutions? I tried but with no success.

send 2 query parameters from and to and use whereBetween to show posts from given date range
your url will be like :
/posts?from=2019-07-15&to=2019-07-16
route in your web.php
Route::get('/posts','HomeController#index')->name('posts');
in your controller :
public function index(){
// set default value for from is yesterday (you can set as per your requirement)
// set default value for to is today
$from=$request->has('from')?$request->query('from'):Carbon::now()->subDays(1);
$to=$request->has('to')?$request->query('to'):Carbon::now()->endOfDay();
$posts = Post::where('user_id', Auth::id())
->whereBetween('created_at',[$from,$to]);
->orderBy('created_at', 'DESC')
->paginate(30);
return view('home')->with(['from'=>$from,'to'=>$to,'posts'=>$posts]);
}
use daterangepicker from frontend side will be better .

Just make this line whereDate('created_at','=',$date)
Like this
whereDate('created_at','<=',$date)

Related

Why do I get a "Trying to get property of non-object" error when using Sortable package in Laravel?

I've encountered a problem with the Kyslik\Column-sortable package for Laravel which has frustrated me for weeks now. :)
The sorting links displays correctly, but when I click on one of the sorting links, I get the following error:
🧨 Trying to get property 'title' of non-object (View: C:\wamp64\www\GeekCollector\resources\views\Lp\show.blade.php)
What's even more strange is that the route goes to the BrowseResults view, but the message sais that the error was encountered in the Show view.
If I remove all the sortable related stuff from the BrowseResults view, the Show view works perfectly.
Here is my model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;
use Kyslik\ColumnSortable\Sortable;
class Lp extends Model
{
use HasFactory;
use Sortable;
public $sortable = ['title', 'artist', 'year'];
}
Here is my BrowseResults controller method:
public function browseResults(Request $request)
{
$chosenCategory = $request->category;
$lps = Lp::where('category','like','%'.$chosenCategory.'%');
$result = $lps->sortable('title')->paginate(5);
return view('Lp.browseResults', compact('result'));
}
And here is my blade view:
<x-app-layout>
<x-slot name="header">
<h1 class="font-semibold text-xl text-gray-800 leading-tight">
Lp-skivor
</h1>
</x-slot>
#sortablelink('title')
#sortablelink('artist')
#sortablelink('year')
<table>
<tr>
<td>Titel</td>
<td>Artist</td>
<td>Kategori</td>
<td>Plats</td>
<td>Position</td>
</tr>
#foreach ($result as $lp)
<tr>
<td>
{{ $lp->title }}
</td>
<td>{{ $lp->artist }}</td>
<td> {{ $lp->category }}</td>
<td>{{ $lp->place }}</td>
<td>{{ $lp->position }}</td>
<td>
Uppdatera
</td>
<td>
<form action="{{ route('lp.destroy', $lp->id) }}" method="post">
#csrf
#method('DELETE')
<button type="submit">Ta bort</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $result->appends(\Request::except('page'))->render() !!}
</x-app-layout>
The route looks like this:
Route::post('/lp/browse-results', [LpController::class, 'browseResults'])->name('lp.browseResults');
Thanks very much in advance for your help!
All the best!

Laravel - summing price with where method for paying method

So right now I'm working on project that needs price summing on each payment method, for example if somebody is paying with cash it needs to sum total price for every cash payment. Here is my code
This is my home.blade.php :
#extends('layouts.theme')
#section('content')
<style>
body{
margin: 0;
background-color: #EBEBEB;
}
</style>
<div class="mainl">
<div class="row">
<div class="columna">
<h1>{{ Auth::user()->name }}</h1>
<hr>
</div>
<div class="columns">
<a href="{{ route('logout') }}" id="logout"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('LOGOUT') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
</div>
</br></br></br>
#if(count($posts)> 0)
<table>
<thead>
<tr>
<th>BR.KESICE</th>
<th>IME I PREZIME</th>
<th>BR.TELEFONA</th>
<th>POSAO</th>
<th>CIJENA</th>
<th>PLACANJE</th>
<th>POPUST</th>
<th>DATUM PREUZ.</th>
<th>DATUM IZDAV.</th>
<th>SMJENA</th>
<th>RADNIK</th>
<th>STATUS</th>
<th>IZMIJENI</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->br_kesice}}</td>
<td>{{$post->ime}}</td>
<td>{{$post->br_telefona}}</td>
<td>{{$post->posao}}</td>
<td>{{$post->cijena}}</td>
<td>{{$post->placanje}}</td>
<td>{{$post->popust}}</td>
<td>{{$post->datum_preuz}}</td>
#if($post->status == 1)
<td>/</td>
#else
<td>{{$post->datum_izdav}}</td>
#endif
<td>{{$post->smjena}}</td>
<td>{{$post->radnik}}</td>
<td>
#if($post->status == 0)
<span class="label label-primary" id="statusdeaktivan">Deaktivan</span>
#elseif($post->status == 1)
<span class="label label-success" id="statusaktivan">Aktivan</span>
#elseif($post->status == 2)
<span class="label label-danger" id="statusdeaktivan">Rejected</span>
#else
<span class="label label-info" id="statusdeaktivan">Deaktivan</span>
#endif
</td>
#if($post->status == 3)
#else
<td><i class="far fa-edit"></i></td>
#endif
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>UKUPAN IZNOS: {{ Auth::user()->posts->sum('cijena') }}€</th>
<th>KARTICA: {{ Auth::user()->posts->where('placanje', 'Kartica')->where('created_at','=',$date)->sum('cijena')}}€</th>
</tr>
</tfoot>
</table>
<br><br>
{{ $posts->links() }}
#else
<p>Trenutno nema unosa.</p>
#endif
</div>
#endsection
In this home.blade.php I put where('created_at','=',$date)
from my HomeController but it's not working. In my homepage it only shows posts made today. And this is how I did it in my
HomeController.php :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Post;
use DB;
use Auth;
use Carbon\Carbon;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$date = new Carbon(request('date'));
$posts = Post::where('user_id', Auth::id())
->whereDate('created_at','=',$date)
->orderBy('created_at', 'DESC')
->paginate(30); //add {{ $posts->links() }} if paginate is enabled
return view('home', compact('date', $date))->with('posts', $posts);
}
}
So all I need is when manager create post and type in method of payment for example 'Kartica', in my homepage it table footer it needs to sum total payment of all posts MADE TODAY and all price for 'Kartica' payment method also from TODAY. If anyone have idea please let me know, thanks !
created_at field use YYYY-MM-DD HH:II:SS format so you have to filter by date not by datetime.
You can do something like this:
public function index()
{
$date = new Carbon(request($date))->format("Y-m-d");
...
->whereRaw('DATE(created_at) = ?', $date)
...
}
whereRaw method can be used to inject a raw where clause into your query.

Call to a member function delete() on null / AdminHomeController.php line 26:

Using the multi_auth from laravel 5.3 im trying to make a delete/edit/update button.
Im trying to delete an user from the admin dashboard retrieving information from the users table.
Actually my first problem is with the destroy function.
This is my destroy route:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
This is my controller from admin:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AdminHomeController extends Controller
{
public function __construct()
{
$this->middleware('admin.user');
}
public function index()
{
$users = User::all();
return view("admin-home")->with('users', $users);
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
Flash::error('El usuario ' . $users->name . '$ ha sido eliminado con exito!');
return redirect()->route('admin-home');
}
}
View with delete button:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="col-sm-offset-2 col-sm-8">
#if (count($users) > 0)
<div class="panel panel-default">
<div class="panel-heading">
Todos los Usuarios
</div>
<div class="panel-body">
<table class="table table-striped user-table">
<thead>
<th>Nombre:</th>
<th> </th>
<th>Email:</th>
<th> </th>
<th>Acciones:</th>
<th> </th>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td> </td>
<td>{{ $user->name }}</td>
<td> </td>
<td>{{ $user->email }}</td>
<td> </td>
<td>
<i class="glyphicon glyphicon-trash" aria-hidden="true"></i>
</td >
<td>
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
</td>
<td> </td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
</div>
</div>
#endsection
Thank you!
Check $id in
$users = User::find($id);
$users->delete();
Object $users is null because user didn't found in database or $id is incorrect
After playing around with the code i found this usefull:
In the view i had 2 buttons the delete and the edit ones, i changed:
{{ route('users.destroy', $user->id) }}
{{ route('users.edit', $user->id) }}
for:
{{ url('users.destroy', $user->id) }}
{{ url('users.edit', $user->id) }}
And now i can see the buttons without any problems, the issue now is the same as before, the function destroy gives me an error.
This is the route that causes the error:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
Error: No query results for model [App\User].
This is my User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
And still can't find the issue.. #edwardstock

Laravel: Eloquent returning an object I can't iterate over

I have a mySQL DB schema like this:
table RECIPES:
int id, PK;
int salesman_id;
int doctor_id;
date order_date;
int status;
table RECIPE_STATUS:
int id, PK;
int recipe_status_code;
varchar recipe_status_name;
In Laravel I have the following php classes:
AdminRecipesController.php
namespace RatCMS\Controllers;
use App\Http\Controllers\Controller;
use Auth;
use RatCMS\Models\Recipes;
use RatCMS\Models\RecipeStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AdminRecipesController extends Controller
{
public function index()
{
$recipes = Recipes::with('recipeStatus')->get();
return view('admin.recipes.news', compact('recipes'));
}
}
Recipes.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class Recipes extends Model
{
protected $table = 'RECIPES';
protected $fillable = ['salesman_id', 'doctor_id', 'order_date', 'status'];
public function recipeStatus() {
return $this->hasOne(\RatCMS\Models\RecipeStatus::class, 'recipe_status_code', 'status');
}
}
RecipeStatus.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class RecipeStatus extends Model
{
protected $table = 'RECIPE_STATUS';
protected $fillable = [];
public function recipes() {
return $this->belongsTo(\RatCMS\Models\Recipes::class);
}
}
blade view
<div class="box-body">
#include('admin.partials.session_success')
#if($recipes->isEmpty())
<p class="text-center">No recipes available.</p>
#else
<table class="table table-bordered">
<tr>
<th style="width: 10px">#</th>
<th>Salesman</th>
<th>Doctor</th>
<th>Date</th>
<th>Status</th>
<th style="width:100px">Actions</th>
</tr>
#foreach($recipes as $recipe)
{{ $recipe }}
<tr>
<td>{{ $recipe->id }}</td>
<td>{{ $recipe->salesman_id }}</td>
<td>{{ $recipe->doctor_id }}</td>
<td>{{ $recipe->order_date }}</td>
<td>{{ $recipe->recipe_status->recipe_status_name }}</td>
<td>
<form style="display: inline-block" action="{{ url('admin/recipes/' . $recipe->id) }}" method="POST">
{{ csrf_field() }}
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger"><i class="fa fa-close" aria-hidden="true"></i> Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
#endif
</div>
When I do {{ $recipe }} in the view, I get the following result:
{"id":1,"salesman_id":"4","doctor_id":"3","order_date":null,"status":"0","recipe_status":{"id":1,"recipe_status_code":"0","recipe_status_name":"Not Recieved"}}
so there is some data being return by Eloquent regarding the recipe status (Not Recieved text), but when I do {{ $recipe->recipe_status }} it fails every time. Even $recipes['recipe_status'] is no help.
Could someone help? Thanks
Relationship should be belongsTo():
public function recipeStatus() {
return $this->belongsTo(\RatCMS\Models\RecipeStatus::class, 'status', 'recipe_status_code');
}
With correct relationship your code will add relationship data to collection, so you'll be able to get status:
$recipe->recipeStatus->recipe_status_name

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