Too few arguments to function Illuminate\Http\Request::has(), 0 passed - php

I have seen many similar questions but most of the answers look complicated and do not seem too similar to my issues. Again, I am new to Laravel and would need the simplest form of explanation.
I want to don't show info in view, show up as long as I searched.
My Controller
public function index(Request $request)
{
$transactions = UserTransaction::query();
$userId = request()->get('userId');
$price = request()->get('price');
$type = request()->get('type');
$status = request()->get('status');
$ordering = request()->get('ordering');
if($userId){
$transactions->where('userId' , $userId);
}
if ($price) {
$transactions->where('price' , $price);
}
if ($type) {
$transactions->where('type' , $type);
}
if ($status) {
$transactions->where('status' , $status);
}
return view('admin.transaction.index',[
'transactions' => $transactions->paginate(5)->appends($request->except('page')),
'stats' => $stats
]);
}
My Blade
#if( $transactions->count() > 0 && request()->has() )
#foreach($transactions as $transaction)
{{ $transaction->id }}
{{ optional($transaction->user)->full_name }}
{{ $transaction->type }}
#endforeach
#endif
I get this error

I think you are looking for hiding view until user searched any one field.So you can do the following
#if( $transactions->count() > 0 &&collect($request->all())->filter()->isNotEmpty())
if you want to ignore page from checking then you can use except
collect($request->except('page'))->filter()->isNotEmpty()
Better don't execute query until one of the filter value is filled because any way you don't to display it in view
public function index(Request $request)
{
$userId = request()->get('userId');
$price = request()->get('price');
$type = request()->get('type');
$status = request()->get('status');
$ordering = request()->get('ordering');
$transactions=[];
if(collect($request->all())->filter()->isNotEmpty()){
$transactions = UserTransaction::query();
if($userId){
$transactions->where('userId' , $userId);
}
if ($price) {
$transactions->where('price' , $price);
}
if ($type) {
$transactions->where('type' , $type);
}
if ($status) {
$transactions->where('status' , $status);
}
$transactions->paginate(5)->appends($request->except('page'))
}
return view('admin.transaction.index',[
'transactions' =>$transactions,
'stats' => $stats
]);
}
Also instead of repeating collect($request->except('page'))->filter()->isNotEmpty() this in multiple place ,you can assign to variable in controller

You should check in the controller whether data has been entered or not. If not, then return the null for $transactions.
public function index(Request $request)
{
if(count($request->all()) > 0) {
$transactions = UserTransaction::query();
$userId = request()->get('userId');
$price = request()->get('price');
$type = request()->get('type');
$status = request()->get('status');
$ordering = request()->get('ordering');
if($userId){
$transactions->where('userId' , $userId);
}
if ($price) {
$transactions->where('price' , $price);
}
if ($type) {
$transactions->where('type' , $type);
}
if ($status) {
$transactions->where('status' , $status);
}
$transactions= $transactions->paginate(5)->appends($request->except('page'))
} else {
$transactions = null;
}
return view('admin.transaction.index',[
'transactions' => $transactions,
'stats' => $stats
]);
}
Then in your view just check $transactions->count() > 0

Related

Pass argument to method

I have functions that I use in my Article model, they add likes to cookies for a specific article and record the time
public static function hasLikedToday($articleId, string $type)
{
$articleLikesJson = \Cookie::get('article_likes', '{}');
$articleLikes = json_decode($articleLikesJson, true);
// Check if there are any likes for this article
if (! array_key_exists($articleId, $articleLikes)) {
return false;
}
// Check if there are any likes with the given type
if (! array_key_exists($type, $articleLikes[$articleId])) {
return false;
}
$likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$articleId][$type]);
return ! $likeDatetime->addDay()->lt(now());
}
public static function setLikeCookie($articleId, string $type)
{
// Initialize the cookie default
$articleLikesJson = \Cookie::get('article_likes', '[]');
$articleLikes = json_decode($articleLikesJson, true);
// Update the selected articles type
$articleLikes[$articleId][$type] = today()->format('Y-m-d H:i:s');
$articleLikesJson = json_encode($articleLikes);
return cookie()->forever('article_likes', $articleLikesJson);
}
The php.blade page itself has buttons
Like Heart
Like Finger
Here are the routes web.php
Route::get('/article', function () {
$articleLikesJson = \Cookie::get('article_likes', '{}');
return view('article')->with([
'articleLikesJson' => $articleLikesJson,
]);
});
Route::get('article/{id}/like', 'App\Http\Controllers\ArticleController#postLike');
And the postLike() function itself in the controller
public function postLike($id) {
$article = Article::find($id);
$like = request('like');
if ($article->hasLikedToday($article->id, $like)) {
return response()
->json([
'message' => 'You have already liked the Article #'.$article->id.' with '.$like.'.',
]);
}
$cookie = $article->setLikeCookie($article->id, $like);
$article->increment('like_{$like}');
return response()
->json([
'message' => 'Liked the Article #'.$article->id.' with '.$like.'.',
'cookie_json' => $cookie->getValue(),
])
->withCookie($cookie);
}
In general, what is the problem, I have 2 types of likes that can be seen in php.blade, and the problem is to pass the choice of the type of like to the postLike() function, if in my function instead of $like I write 'heart', then everything will be work, but I need to determine which type we choose (heart or finger), tell me how this can be done?
You can use Laravel's Request object.
https://laravel.com/docs/8.x/requests#input
Like this:
use Illuminate\Http\Request;
public function postLike($id, Request $request)
{
$type = $request->input('type');
}

what is the correct way to pass 3 where () conditions in the same function, multiple filters | eloquente - laravel

I would like to know if I am doing it right, if my code is semantic and safe.
I need to load a page from the database, but to do this I need to cross some data and all must be compatible, the verification takes place as follows:
url: mysite.com/company/page/code
1 - Check the first parameter to see if company exists or not.
2 - check the second parameter to find out if company X has that page or not
3 - Check the third parameter to find out if page Y has a code and if that code matches what you typed.
4 - If the user arrived here and all the data are correct, please load the page and the corresponding data.
Here he checks if user X has page Y, my doubt is if I can do it like this or is there another way.
$page = Page::where('name', $name)->where('page_name', $page_name)->first();
if ($page === null) {
return view('company.pages.erros.404', compact('name', page));
}
Here is similar to the other, he checks if user X has page Y and if the code of page Y is correct, as in others, my doubt is if it is correct to put several WHERE clauses in the code
$pagecode = Page::where('name', $name)->where('page_name', $pagen_name)->where('code', $pcode)->first();
if ($pagecode === null) {
return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
}
as I thought you would want the code in general context, here is the full function code
public function loadpage($name, $page_name, $pcode)
{
$company = Company::where('name', $name)->first();
if ($company === null) {
return view('company.not_register', compact('name'));
}
$page = Page::where('name', $name)->where('page_name', $page_name)->first();
if ($page === null) {
return view('company.pages.erros.404', compact('name', page));
}
$pagecode = Page::where('name', $name)->where('page_name', $page_name)->where('code', $pcode)->first();
if ($pagecode === null) {
return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
}
$personality = DB::table('personalities')->where('name', $name)->first();
return view('company.pages.index', compact('company', 'name', 'personality', 'page', pcode));
}
based on laravel's documentation, I came up with the following result:
public function loadpage($name, $page_name, $pcode)
{
$company = Company::where('name', $name)->first();
if ($company === null) {
return view('company.not_register', compact('name'));
}
$page = Page::where([ ['name', $name],
['page_name', $page_name],])->first();
if ($page === null) {
return view('company.pages.erros.404', compact('name', page));
}
$pagecode = Page::where([ ['name', $name],
['page_name', $page_name], ['code', $pcode],])->first();
if ($pagecode === null) {
return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
}
$personality = DB::table('personalities')->where('name', $name)->first();
return view('company.pages.index', compact('company', 'name', 'personality', 'page', pcode));
}
now it's up to colleagues more experienced than me to see if that's right or is it possible to improve / simplify
In case you are searching in a single model and you are not sure when which fields occur you might want to use laravel's when() method. It will help you search the database only when the field is available for you. for an example:
$sortBy = null;
$users = DB::table('users')
->when($sortBy, function ($query, $sortBy) {
return $query->orderBy($sortBy);
}, function ($query) {
return $query->orderBy('name');
})
->get();
You will get the idea from here conditional query in laravel
if you have multiple where clause to pass to a where clause, you can have a array containing arrays with the structure as you would have in the where method, like:
$where = [
['name', $name],
['page_name', $page_name],
['code', $pcode],
/*
the arrays should have one of this two structure
["field", "value"], //using = operator as default
["field", "operator", "value"],
*/
];
and than call ->where() with this array as parameter, like:
Page::where($where)->first();
So your code can become
public function loadpage($name, $page_name, $pcode)
{
$name = ['name', $name];
$pageName = ['page_name', $page_name];
$pageCode = [ 'code', $pcode ];
$company = Company::where([$name])->first();
if ($company === null) {
return view('company.not_register', compact('name'));
}
$page = Page::where([$name, $pageName])->first();
if ($page === null) {
return view('company.pages.erros.404', compact('name', page));
}
$pagecode = Page::where([$name, $pageName, $pageCode])->first();
if ($pagecode === null) {
return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
}
$personality = DB::table('personalities')->where([$name])->first();
return view('company.pages.index', compact('company', 'name', 'personality', 'page', pcode));
}

Transfer variable from one to another function in controller

I am using Laravel at this time to secure a page when a user enters their password on a modal form before it opens. I initialized a variable named $crypt, which is hidden in the form, to make every page unique (to prevent other people from opening the page with a URL).
I want to pass the $crypt data to the PDFView. How can I do that? I've tried a lot of things but none worked.
Error
Undefined variable: crypts
Route:
Route::get('/pdfview/{id}/', 'HomeController#pdfview')->name('pdfview');
Generated key code
<div style="display: none">{{ $crypt = str_random(10)}}
Controller
public function encryptslip(Request $request, $crypt)
{
$crypts = $crypt;
$id = $request->nip;
$pass = $request->password;
$nip = Auth::user()->nip;
if (Hash::check($pass, Auth::user()->password)) {
return redirect('/pdfview/' . $nip . '/', ['crypts' => $crypts])->with('crypt', $crypt);
} else {
return redirect('/home')->with('alert', 'Incorrect password');
}
}
public function pdfview(Request $request, $id)
{
$route = url()->current();
$month = Carbon::now()->month;
$periodeinput = DB::table('payrollinput')->where('nip', '=', $id)->orderBy('periode', 'desc')->pluck('periode')->implode('periode');
$periodehistory = DB::table('payrollhistory')->where('nip', '=', $id)->orderBy('periode', 'desc')->pluck('periode')->implode('periode');
// if ($periodeinput !== $month && $periodehistory !== $month) {
// return redirect('home')->with('alert', 'Slip gaji anda siap.');
// } else {
if (Auth::user()->nip == $id) {
$employees = MasterEmployee::where('nip', '=', $id)->first();
$payrollhistory = MasterPayrollHistory::where('nip', '=', $id)->where('periode', '=', $month)->first();
$payrollinput = MasterPayrollInput::where('nip', '=', $id)->where('periode', '=', $month)->first();
view()->share('employees', $employees);
view()->share('payrollhistory', $payrollhistory);
view()->share('payrollinput', $payrollinput);
view()->share('id', $id);
// calculation code
return view('pdfview', ['id' => $id])->with('id', $id)
->with('earningtotal', $earningtotal)
->with('deductiontotal', $deductiontotal)
->with('takehomepay', $takehomepay)
->with('total', $total);
} else {
return redirect('home')->with('alert', 'Sorry it is personally confidential, you are not able to see it.');
}
}
View
<div><{{$crypts}}</div>
when you use return redirect() method that variable is passed to the view as a session variable and in the blade it must be called form
<div>{{session('crypts')}}</div>
to convert this session variable on $request
{{Form:hidden('crypts', json_encode(session('crypts'))}}

Sort by relationship first in laravel

I have two tables: admins and log_doctor_infos. admins table has relationship hasOne with log_doctor_infos throught doctor_id like this.
In model Admin:
public function logDoctorInfo() {
return $this->hasOne(LogDoctorInfo::class, 'doctor_id', 'id');
// Model LogDoctorInfo is log_doctor_infos table
}
And in Model LogDoctorInfo:
public function doctor(){
return $this->belongsTo(Admin::class, 'doctor_id', 'id');
// Model Admin is admins table
}
I get all data form admins table and i want to sort record has relationship with log_doctor_infos to top.
Yellow record, which has relationship with log_doctor_infos and i want to sort it in top.
Edit: i use paginate in this query and i really want to get quantity of Yellow record.
Thanks for reading!
In my controller, i have custom filter and paginate. Help me.
public function index(Request $request) {
$fullname = $request->query('fullname', NULL);
$phone = $request->query('phone', NULL);
$status = $request->query('status', NULL);
$doctors = (new Doctor)->newQuery();
if ($fullname != NULL) {
$doctors = $doctors->where('fullname', 'LIKE', '%'.$fullname.'%');
}
if ($phone != NULL) {
$doctors = $doctors->where('phone', 'LIKE', '%'.$phone.'%');
}
if ($status != NULL) {
$doctors = $doctors->where('status', $status);
}
$doctors = $doctors
// ->with(array('logDoctorInfo' => function($query) {
// $query->orderBy('updated_at', 'ASC');
// }))
->latest()
->paginate()
->appends([
'fullname' => $fullname,
'phone' => $phone,
'status' => $status
]);
// dd($doctors);
return view('admin.doctors.index', compact('doctors'));
}
you can use the withCount method.
Admin::withCount('logDoctorInfo')
->orderBy('log_doctor_info_count', 'desc')
->paginate(5);
Your controller will look like this
public function index(Request $request) {
$fullname = $request->input('fullname', NULL);
$phone = $request->input('phone', NULL);
$status = $request->input('status', NULL);
$doctorQuery = Doctor::query();
if ($fullname) {
$doctorQuery->where('fullname', 'LIKE', '%'.$fullname.'%');
}
if ($phone) {
$doctorQuery->where('phone', 'LIKE', '%'.$phone.'%');
}
if ($status) {
$doctorQuery->where('status', $status);
}
$doctorQuery->withCount('logDoctorInfo')
->orderBy('log_doctor_info_count');
$doctors = $doctorQuery->paginate()
->appends([
'fullname' => $fullname,
'phone' => $phone,
'status' => $status
]);
// dd($doctors);
return view('admin.doctors.index', compact('doctors'));
}
Doctor::with('logDoctorInfo')->get()->sortByDesc('logDoctorInfo.id');

Laravel troubles with WHERE in relationships

I'm having trouble when a user is not an admin. The goal is to get only those requests that belong to the user, but when I use the where clause, I get all the requests from the DB.
It was supposed to get all the requests only for an admin.
Thank you for the help!
public function index(){
$status = request('status', -1);
$paper_size = request('paper_size', -1);
if (auth()->user()->isAdmin()) {
$requests = Request::
where('paper_size', $paper_size)->orWhereRaw($paper_size. ' = -1')->
where('status', $status)->orWhereRaw($status. ' = -1')->
orderBy(
request('orderby') ? request('orderby') : 'created_at',
request('order') ? request('order') : 'DESC'
)->paginate(10);
$departments = Departament::All();
return view('Requests.index', compact('requests', 'departments'));
}
$requests = auth()->user()->requests()->
where('status', $status)->orWhereRaw($status. ' = -1')->
where('paper_size', $paper_size)->orWhereRaw($paper_size. ' = -1')->
orderBy(
request('orderby') ? request('orderby') : 'created_at',
request('order') ? request('order') : 'DESC'
)->paginate(10);
return view('Requests.index', compact('requests'));
}
UPDATE:
I can already list all user requests, but the status filter does not work.
Ps: the filter "paper_size" is working as expected
SOLVED:
Thanks to the whole community, and especially to #Sandeesh
public function index(){
request('status') == -1 || request('status') == null ?
$statusExists = false : $statusExists = true;
$status = request('status');
request('paper_size') == -1 || request('paper_size') == null ?
$paper_sizeExists = false : $paper_sizeExists = true;
$paper_size = request('paper_size');
$is_admin = auth()->user()->isAdmin();
$requests = Request::when($statusExists, function ($query) use ($status) {
return $query->where('status', $status);
})
->when($paper_sizeExists, function ($query) use ($paper_size) {
return $query->where('paper_size', $paper_size);
})
->when(!$is_admin, function ($query) {
return $query->where('owner_id', auth()->id());
})
->orderBy(request('orderby', 'created_at'), request('order', 'desc'))
->paginate(10);
if (!$is_admin) {
return view('Requests.index', compact('requests'));
}
$departments = Departament::all();
return view('Requests.index', compact('requests', 'departments'));
}
Wrap your where and orWhereRaw conditions together for a single column. Or use when instead of the workaround you apply with -1 = -1. I've also refactored the code for you.
public function index()
{
$status = request('status');
$paper_size = request('paper_size');
$is_admin = auth()->user()->isAdmin();
$requests = Request::when(!is_null($status), function ($query) use ($status) {
return $query->where('status', $status);
})
->when(!is_null($paper_size), function ($query) use ($paper_size) {
return $query->where('paper_size', $paper_size);
})
->when(!$is_admin, function ($query) {
return $query->where('owner_id', auth()->id());
})
->orderBy(request('orderby', 'created_at'), request('order', 'desc'))
->paginate(10);
if (!$is_admin) {
return view('Requests.index', compact('requests'));
}
$departments = Departament::all();
return view('Requests.index', compact('requests', 'departments'));
}
You would need to get the $user_id = Auth::id and then update the second query to have a where user_id = $user_id statement (I'm not sure which of those tables belongs to the user).
Try with:
$requests = Request::with('User')
->where('user_id',\Auth::user()->user_id)
->where('status', $status)
->orWhereRaw($status. ' = -1')
->where('paper_size', $paper_size)
->orWhereRaw($paper_size. ' = -1')
->orderBy(request('orderby') ? request('orderby') : 'created_at',
request('order') ? request('order') : 'DESC')->paginate(10);

Categories