How to use if/else in a form - php

I am trying to use if/else on a submit button given that if an employee time in is null a Sign In button will be shown otherwise Sign Out button is displayed. Below is my set_attendance form. The if/else does not work as expected. Could you please help how to make it work.
<table class="table table-bordered table-striped">
<thead>
<tr>
<th> {{ __(' SL') }}</th>
<th> {{ __(' Employee Name') }}</th>
<th> {{ __('Action') }}</th>
</tr>
</thead>
<tbody>
#foreach($attendances as $key => $attd)
<tr>
<td>{{$key+1}}</td>
<td>{{ $attd['name'] }}</td>
<td>
<form action="{{ route('attendance.timeclock') }}" method="post" name="department_add_form">
{{ csrf_field() }}
<input type="hidden" name="id" id="id" value="{{ $attd['id'] }}">
#if($timein[1]['timein'] == Null)
<button type="submit" class="btn btn-primary btn-flat"><i class="icon fa fa-plus"></i> {{ __('Sign IN') }}</button>
#else
<button type="submit" class="btn btn-primary btn-flat"><i class="icon fa fa-plus"></i> {{ __('Sign Out') }}</button>
#endif
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
Below is my timeclockcreate method in a controller
public function timeclockcreate(Request $request){
$id = $request->input('id');
$data['attendances'] = User::all()->toArray();
$data['timein'] = User::query()
->leftjoin('attendances', 'attendances.user_id', '=', 'users.id')
->select('attendances.*', 'users.*')
->orderBy('users.name', 'ASC')
->get()
->toArray();
return view('fms.attendances.set_attendance',$data)->with('id', $id)->with('message', 'Inserted successfully.');
}
My attendance table
public function up()
{
Schema::create('attendances', function (Blueprint $table) {
$table->increments('id');
$table->integer('created_by');
$table->integer('user_id')->unsigned();
$table->time('timein')->nullable();
$table->time('timeout')->nullable();
$table->date('logdate');
$table->string('status');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}

It looks like you are accessing the same 'timein' for each employee with
$timein[1]['timein']
I'm guessing this is why it's not working.
You can search through the timein array to find the right timein row for the user you are currently looking at.
But instead you should set up an eloquent relationship with models that way you dont need to use joins. It simplifies queries a lot. https://laravel.com/docs/9.x/eloquent-relationships. Hope that makes sense.

#if( $attd['timein'] === NULL )

Related

How do i calculate and view total work_time for specific id in laravel in one row by date from to?

I have two tables employes and attendances . What I want is to sum work_time for each employe id and show in my view.
employes Table id attendances Table id employe_id work_time
I want to sum work_time column for specific employe id by date from to?. I am new to laravel so how do I do that with laravel eloquent.
Employe.php
class Employe extends Model
{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function attendances(){
return $this->hasMany('App\Models\Attendance');
}
}
Attendance.php
class Attendance extends Model
{
use HasFactory;
protected $fillable=['id','employe_id','attendence_date','clock_in','clock_out','work_time','attendence_status'];
public function employe()
{
return $this->belongsTo('App\Models\employe', 'employe_id');
}
AttendanceController.php
public function attendanceReport(){
$empname = Employe::get();
return view('pages.Attendance.attendance_report', compact('empname'));
}
public function attendanceSearch(Request $request){
$empname = Employe::get();
if($request->employe_id == 0){
$emp = Attendance::whereBetween('attendence_date', [$request->from, $request->to])->get();
return view('pages.Attendance.attendance_report',compact('emp','empname'));
}
else{
$emp = Attendance::whereBetween('attendence_date', [$request->from, $request->to])
->where('employe_id',$request->employe_id)->get();
return view('pages.Attendance.attendance_report',compact('emp','empname'));
}
}
attendance_report.blade.php
<form method="post" action="{{ route('attendance.search') }}" autocomplete="off" id="sh11">
#csrf
<div class="row">
<div class="col-md-3">
<div class="form-group">
<select class="custom-select mr-sm-2"name="employe_id">
<option value="0">all</option>
#foreach($empname as $empname)
<option value="{{ $empname->id }}">{{$empname->employe_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="card-body datepicker-form">
<div class="input-group" data-date-format="yyyy-mm-dd">
<span class="input-group-addon">Date</span>
<input type="text" class="form-control range-from date-picker-default" value={{ date('Y-m-d') }} required name="from">
<span class="input-group-addon">to date</span>
<input class="form-control range-to date-picker-default" value={{ date('Y-m-d') }} type="text" required name="to">
</div>
</div>
</div>
<button class="btn btn-success btn-sm nextBtn btn-lg pull-right" type="submit">{{trans('Students_trans.submit')}}</button>
</form>
#isset($emp)
<div class="table-responsive">
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50"
style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">code</th>
<th class="alert-success">name</th>
<th class="alert-success">work_time</th>
<th class="alert-success">attendence_date</th>
<th class="alert-warning">###</th>
</tr>
</thead>
<tbody>
#foreach($emp as $EMP)
<tr>
<td>{{ $loop->index + 1 }}</td>
<td>{{ $EMP->employe->employe_code }}</td>
<td>{{ $EMP->employe->employe_name }}</td>
<td>Hour {{ $EMP->work_time }} </td>
<td>{{ $EMP->attendence_date }}</td>
<td>
#if($EMP->attendence_status == 0)
<span class="btn-danger">Presence</span>
#else
<span class="btn-success">Absence</span>
#endif
</td>
</tr>
#endforeach
</table>
</div>
#endisset
you can try to add selectRaw to your releation
public function attendances(){
return $this->hasMany('App\Models\Attendance')->selectRaw('SUM(work_time) as total_work_time');
}
check the decumentation

laravel 8 crude operation not showing

i have laravel connected
to database mysql
when i do insert/update i find it on the mysql table
but the page show data does not reflect the change
my page is products.
the web route:
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\ProductController;
Route::get('/', function () {
return view('welcome'); });
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::resource('products', ProductController::class);
the show index.blade.php page :
#extends('products.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD Example from scratch - ItSolutionStuff.com</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('products.create') }}"> Create New Product</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Details</th>
<th width="280px">Action</th>
</tr>
#foreach ($products as $product)
<tr>
<td>hi</td>
<td>{{ $product->name }}</td>
<td>{{ $product->detail }}</td>
<td>
<form action="{{ route('products.destroy',$product->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
#endsection
does any one can give me the reason why change not reflected
enter image description here
In your controller, after updating product, try to do:
return redirect()->back();

I Want to Disable Delete Button Base On auth()->user()->id (LARAVEL 8)

I have make Users Index where on that table displaying all user data except Password and at the last field i put action for Delete user. The problem is i want to disable delete button only for the user who login at that time. But what i have done is all user delete button disable, please help me how to solve this. i have trying to find tutoril but didn't find yet. Below my condition code:
#if (auth()->user()->id)
<button class="btn btn-outline-danger
btn-xs" disabled><i class="fe fe-trash"></i>Delete</button>
#else
<button class="btn btn-outline-danger
btn-xs"><i class="fe fe-trash"></i>Delete</button>
#endif
In UserController to display all user data i use this code:
public function index(){
$users = User::all();
return view('admin.users.index', ['users'=> $users]);
}
in index.blade i aplly this code to display all data:
<table id="dataTableBasic" class="table" style="width:100%">
<thead>
<tr>
<th>{{ __('Username') }}</th>
<th>{{ __('Name') }}</th>
<th>{{ __('Email') }}</th>
<th>{{ __('Role') }}</th>
<th>{{ __('Posts') }}</th>
<th>{{ __('Action') }}</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{$user->username}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>Administrator</td>
<td>100</td>
<td>
<form action="{{route('users.destroy',$user->id)}}" method="post" enctype="multipart/form-data">
#csrf
#method('DELETE')
#if (auth()->user()->id)
<button class="btn btn-outline-danger btn-xs" disabled><i class="fe fe-trash"></i>{{ __('Hapus') }}</button>
#else
<button class="btn btn-outline-danger btn-xs"><i class="fe fe-trash"></i>{{ __('Hapus') }}</button>
#endif
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
Below the screenshot:
You need to check if the $user->id is the same as the authenticated user's id:
#if(auth()->id() === $user->id)
Also, since the only different between the buttons in the disabled attribute, you could do:
<button class="btn btn-outline-dangerbtn-xs"
#if($user->id === auth()->id()) disabled #endif>
<i class="fe fe-trash"></i>
Delete
</button>
<td>
<form action="{{route('users.destroy',$user->id)}}" method="post" enctype="multipart/form-data">
#csrf
#method('DELETE')
#if (auth()->id())
<button class="btn btn-outline-danger btn-xs" disabled><i class="fe fe-trash"></i>Delete</button>
#else
<button class="btn btn-outline-danger btn-xs"><i class="fe fe-trash"></i>Delete</button>
#endif
</form>
</td>

Method Illuminate\Support\Collection::orWhere does not exist

I am trying to connect 2 tables and search in them and show results from them in table on view.
I've got this erro on this line: $query->orWhere($field, 'like', '%'.$search.'%');
in this search metod of my controller:
public function search3(Request $request)
{
$query = DB::table('users')
->join('proforms', 'users.id', '=', 'proforms.user_id')
->get();
$search = $request->get('search');
$requestData = ['showname'];
/* $query = Proform::query(); */
foreach ($requestData as $field){
$query->orWhere($field, 'like', '%'.$search.'%');
}
$data2=$query->paginate(5);
return view('proforms.index', ['proforms' => $data2])->with('i', ($request->input('page', 1) - 1) * 5);
}
This error comes after clicking search button on this view:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Zarządzanie proformami</h2>
</div>
<div class="col-md-4">
<form action="/search3" method="get">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-prepend">
<button type="submit" class="btn btn-primary">Wyszukaj</button>
</span>
</div>
</form>
</div>
<div class="pull-right">
#can('product-create')
<a class="btn btn-success" href="{{ route('proforms.create') }}"> Utwórz nową proformę</a>
#endcan
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th scope="col">#sortablelink('id', 'Numer')</th>
<th scope="col">#sortablelink('proformnumber', 'Numer proformy')</th>
<th scope="col">#sortablelink('user_id', 'Kontrachent')</th>
<th scope="col">#sortablelink('proformdate', 'Data wystawienia')</th>
<th scope="col">#sortablelink('selldate', 'Data sprzedaży')</th>
<th scope="col">#sortablelink('paymentdate', 'Termin płatności')</th>
<th scope="col">#sortablelink('status', 'Status')</th>
<th scope="col">#sortablelink('nettotal', 'Netto razem')</th>
<th scope="col">#sortablelink('grosstotal', 'Brutto razem')</th>
<th width="280px">Akcja</th>
</tr>
#foreach ($proforms as $proform)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $proform->proformnumber }}</td>
<td>{{ $proform->user->showname }}</td>
<td>{{ $proform->proformdate }}</td>
<td>{{ $proform->selldate }}</td>
<td>{{ $proform->paymentdate }}</td>
<td>{{ $proform->status }}</td>
<td>{{ $proform->nettotal }}</td>
<td>{{ $proform->grosstotal }}</td>
<td>
<form action="{{ route('proforms.destroy',$proform->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('proforms.show',$proform->id) }}">Więcej</a>
#can('product-edit')
<a class="btn btn-primary" href="{{ route('proforms.edit',$proform->id) }}">Edytu</a>
#endcan
#csrf
#method('DELETE')
#can('product-delete')
<button type="submit" class="btn btn-danger">Usuń</button>
#endcan
</form>
</td>
</tr>
#endforeach
</table>
{!! $proforms ?? ''->appends(request()->except('page'))->render() !!}
<p class="text-center text-primary"><small>ARTplus 2020</small></p>
#endsection
This is my routes for it:
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth']], function () {
Route::resource('roles', 'RoleController');
Route::resource('users', 'UserController');
Route::resource('permissions', 'PermissionController');
Route::resource('products', 'ProductController');
Route::resource('invoices', 'InvoiceController');
Route::resource('category', 'CategoryController');
Route::resource('invoices', 'InvoiceController');
Route::resource('proforms', 'ProformController');
Route::get('/search', 'UserController#search');
Route::get('/search2', 'ProductController#search2');
Route::get('/search3', 'ProformController#search3');
Route::get('data', 'UserController#index');
Route::get('posts', 'PostController#index');
Route::get('/prodview', 'TestController#prodfunct');
change
$query = DB::table('users')
->join('proforms', 'users.id', '=', 'proforms.user_id')
->get();
to
$query = DB::table('users')
->join('proforms', 'users.id', '=', 'proforms.user_id');
When you call get() method on a query the query will be executed and will return a Collection instance instead of a builder instance. Error is because Collection class does not have the orWhere method. The Builder has that method. So call the get() method when the query is finished.

Undefined variable: user_id in Laravel view

The Routes
Route::get('/adminContacts/{user_id}', 'AdminContactsController#index')->name('adminContacts.index')->middleware('is_admin');
Route::get('/adminContacts/{user_id}/create', 'AdminContactsController#create')->name('adminContacts.create')->middleware('is_admin');
adminContactController
public function index($user_id)
{
// Confirm User exists
User::findOrFail($user_id);
$filter = request('filter', NULL);
$contacts = NULL;
if ($filter == NULL)
$contacts = Contacts::query()->where('owner_id', $user_id)->sortable()->paginate(5);
else
$contacts = Contacts::query()->where('owner_id', $user_id)->where('name', 'like', '%'.$filter.'%')
->orWhere('number', 'like', '%'.$filter.'%')
->sortable()->paginate(5);
return view('adminContacts.index')->withContacts($contacts)->withUserId($user_id);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($user_id)
{
return view('adminContacts.create')->withUserId($user_id);
}
index.blade.php
<div class="container">
<h1 class="jumbotron">Sample Phone Book</h1>
Add Contact
</div>
<!--Search Field -->
<div class="container">
<form method="GET" action="{{ route('adminContacts.index') }}">
<input type="text" name='filter' class='input' placeholder='Search' value="{{ request('filter') }}">
#if (request('filter'))
<a class="btn btn-primary btn-sm" href="{{ route('adminContacts.index') }}">X</a>
#endif
</form>
</div>
<!-- Table -->
<div class="container">
<div class="row" >
<table class="table table-hover" id="contactsTable">
<thead>
<tr>
<th>#</th>
<th>#sortablelink('name', 'Contact Name')</th>
<th>#sortablelink('number', 'Phone Number')</th>
<th>
<button class="btn btn-primary btn-sm">Prepend</button>
</th>
</tr>
</thead>
<!--Loop through all the cutomers and output them on the table-->
#foreach($contacts as $contact)
<tbody>
<tr>
<td>{{ $contact->id }}</td>
<td>{{ $contact->name }}</td>
<td>{{ $contact->number }}</td>
<td>
View
</td>
</tr>
</tbody>
#endforeach
</table>
{!! $contacts->appends(\Request::except('page'))->render() !!}
</div>
</div>
The error is:
Undefined variable: user_id (View: D:\laragon\www\SampleContacts\resources\views\adminContacts\index.blade.php)
Am I missing something? The idea is to pass the $user_id to the adminContact.create form where i can use it to set
$contact->owner_id = $user_id;
so the entered contact apears under that users table.
I don't think you can pass variables into your view like you're doing now.
In your controller, try changing this line:
return view('adminContacts.index')->withContacts($contacts)->withUserId($user_id);
To this:
return view('adminContacts.index')->with('contacts', $contacts)->with('user_id', $user_id);
You could explicitly name the variable when passing it to the view, either this way
return view('adminContacts.index')->with('user_id', $user_id);
Or
return view('adminContract.index', compact('user_id'));
I'm not sure what the name of the variable becomes when passed to the view via withUserId, but I'm guessing this is the issue.
Found the problem.
#extends('layouts.app')
#section('content')
<div class="container">
<h1 class="jumbotron">Sample Phone Book</h1>
Add Contact
</div>
<!--Search Field -->
<div class="container">
<form method="GET" action="{{ route('adminContacts.index', $user_id) }}">
<input type="text" name='filter' class='input' placeholder='Search' value="{{ request('filter') }}">
#if (request('filter'))
<a class="btn btn-primary btn-sm" href="{{ route('adminContacts.index', $user_id) }}">X</a>
#endif
</form>
</div>
<!-- Table -->
<div class="container">
<div class="row" >
<table class="table table-hover" id="contactsTable">
<thead>
<tr>
<th>#</th>
<th>#sortablelink('name', 'Contact Name')</th>
<th>#sortablelink('number', 'Phone Number')</th>
<th>
<button class="btn btn-primary btn-sm">Prepend</button>
</th>
</tr>
</thead>
<!--Loop through all the cutomers and output them on the table-->
#foreach($contacts as $contact)
<tbody>
<tr>
<td>{{ $contact->id }}</td>
<td>{{ $contact->name }}</td>
<td>{{ $contact->number }}</td>
<td>
View
</td>
</tr>
</tbody>
#endforeach
</table>
{!! $contacts->appends(\Request::except('page'))->render() !!}
</div>
</div>
#endsection
Anywhere where there is a {{ route('adminContacts.index') }} it also needed the $user_id to be passed along with it because I'm also using it in the routes as '/adminContacts/{user_id}'
Thank you for all the help.

Categories