Laravel - How to only enable Add Button based on condition - laravel

I have a Laravel-8 project with this model:
protected $fillable = [
'id',
'employee_id',
'leave_status',
'commencement_date',
'resumption_date',
'created_at'
];
protected $dates = [
'commencement_date',
'resumption_date',
'created_at',
'updated_at',
];
View:
<div class="panel-heading clearfix">
<div class="container-fluid">
#if ($currentstatus)
<div style="margin-bottom: 10px;" class="row">
<div class="col-lg-12">
<a class="btn btn-info" href="{{ route(" service.leave_requests.create ") }}">
Add
</a>
</div>
</div>
#endif
</div>
</div>
I want the Add button to only be visible when:
leave_status is 0 for the last record (order by created_at)
or
leave_status is 4 and resumption_date is greater than or equal to today's date (order by created_at) for the last record.
or
leave_status is 3 (order by created_at) for the last record.
I tried the code below, but it's not working.
$userID = Auth::user()->id;
$currentstatus = HrLeaveRequest::select('leave_status')->where('employee_id', $userID)->whereIn('leave_status', [0, 3, 4])->orderBy('created_at', 'DESC')->first();
Note: If the last record is previous year, it should automatically make the button visible. But for the current year, it should apply any of the conditions for the rules.
How do I achieve this?
Thanks

Try this:
// This gets last requests this year
$request = HrLeaveRequest::whereEmployeeId($userID)->whereYear('created_at', date('Y'))->whereIn('leave_status', [0,3,4])->latest()->first();
// OR you might remove the whereYear query to check with conditions
If(date('Y', strtotime($request->created_at)) < date('Y')) {
// This checks if the year is the previous year
}
$currentstatus = HrLeaveRequest::where(['employee_id', '==' $userID], ['resumption_date', '>=', date('d-m-Y')])->whereIn('leave_status', [0, 3, 4])->latest()->first();

Related

Laravel 8 - search paginate ( withQueryString ) not working on table when searching NUMBERS on row integer

i can't search when it comes to searching NUMBERS on row int (price), but when searching like String number on row string (name) it's working fine
like this in my table row here is my Product table
category_id
"56"
user_id
"1"
name
"555"
description
"fruit"
price
555
when i am searching the name row "555" it's working fine beacuse its a string. but when it comes to price i can't search it because it's int
here is my code for controller searching
public function index(Request $request){
$user = Auth::user()->id;
if($request->search){
$search = $request->search;
$products = Products::with('category')
->where('name','like',"%$search%")
->orWhere('price','like',"%$search%")
->where('user_id',$user)->paginate(10);
}else{
$products = Products::with('category')->where('user_id',$user)->paginate(10);
}
return view('client.product.index',['products'=>$products]);
}
here is my blade
<form class="w-full" action="{{ route('client.product.index') }}">
<i class="fa fa-search"></i>
<input placeholder="Search" type="search" name="search">
<button type="submit">Search</button>
</form>
#foreach ($products as $product)
<p>{{ $product->name }}</p>
<p>{{ $product->price }}</p>
#endforeach
{{ $products->withQueryString()->links('pagination::bootstrap-4') }}
You need to group the where and orWhere so the user_id will be correctly filtered:
$products = Products::with('category')
->where( function($q) use ($search) {
$q->where('name','like',"%$search%");
$q->orWhere('price','like',"%$search%");
})
->where('user_id',$user)->paginate(10);

How can I save records in attendance table using Laravel?

I am having issue with saving attendance record of student in attendance listings. The frontend part is working well but record saved in backend of attendance table is not shown. How can I save record in backend table of attendance which consists of level_id, teacher_id and student_id
Here is my attendance migrations table
$table->id();
$table->unsignedBigInteger('level_id');
$table->unsignedBigInteger('teacher_id');
$table->unsignedBigInteger('student_id');
$table->foreign('level_id')->references('id')->on('levels');
$table->foreign('teacher_id')->references('id')->on('teachers');
$table->foreign('student_id')->references('id')->on('students');
$table->date('attendance_date');
$table->string('attendance_status');
$table->timestamps();
Here is my students migrations tables
$table->id();
// The Parents table must exist and Must have 'id' as Primary Key
$table->unsignedbiginteger('parent_id');
$table->unsignedbiginteger('level_id');
$table->foreign('parent_id')->references('id')->on('parents')
->onDelete('cascade');
$table->foreign('level_id')->references('id')->on('levels');
$table->string('student_roll_no');
$table->string('student_surname');
$table->string('student_middle_name')->nullable();
$table->string('student_given_name');
$table->string('student_place_of_birth');
$table->date('student_date_of_birth');
$table->string('student_gender');
$table->text('student_home_address');
$table->string('student_suburb')->nullable();
$table->string('student_post_code');
$table->string('student_home_phone')->nullable();
$table->string('student_work_phone')->nullable();
$table->string('student_mobile_phone');
$table->string('student_email')->nullable();
$table->string('student_photo')->nullable();
$table->string('language_spoken_at_home')->nullable();
$table->string('school_name');
$table->string('student_semester')->nullable();
$table->string('school_suburb')->nullable();
$table->text('school_address')->nullable();
$table->string('student_oversea_full_paying')->nullable();
$table->string('emergency_person_one_name')->nullable();
$table->string('emergency_person_one_mobile_number');
$table->string('emergency_person_one_house_number')->nullable();
$table->string('emergency_person_two_name')->nullable();
$table->string('emergency_person_two_mobile_number')->nullable();
$table->string('emergency_person_two_house_number')->nullable();
$table->string('medical_condition')->nullable();
$table->boolean('medical_health_support')->nullable();
$table->boolean('family_court_orders');
$table->string('family_court_file')->nullable();
$table->boolean('authority_to_school_staff');
$table->boolean('authorize_school_staff_to_arrange_medical_treatment');
$table->boolean('authorize_school_staff_administering_medication');
$table->boolean('notify_the_school_absent');
$table->boolean('withdraw_child_from_school');
$table->boolean('authorize_photograph_to_school');
$table->boolean('authorize_child_name_school_newsletter_website');
$table->boolean('authorize_short_local_walks');
$table->boolean('authorize_participate_in_any_incursions');
$table->boolean('information_contained_in_this_form_correct');
$table->boolean('status')->default(1);
$table->timestamps();
Here is my levels tables
$table->bigIncrements('id');
$table->string('level_name');
$table->timestamps();
Here is my Teachers migrations tables
$table->id();
// The Parents table must exist and Must have 'id' as Primary Key
$table->unsignedbiginteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->string('teacher_name');
$table->string('teacher_email')->unique();
$table->string('teacher_home_phone')->nullable();
$table->string('teacher_mobile_phone');
$table->string('teacher_work_phone')->nullable();
$table->string('teacher_home_address');
$table->string('teacher_suburb')->nullable();
$table->string('teacher_postcode');
$table->timestamps();
Here is my Attendance Controller
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Levels;
use App\Models\Teacher;
use App\Models\Student;
use App\Models\Attendance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AttendanceController 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($level_id = NULL)
{
$levels = Levels::all();
$students = Student::all();
return view('admin.attendance.list', compact( 'levels', 'students','level_id'));
}
/**
* Perform Actions in attendance.add
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function add()
{
$levels = array();
$students = array();
return view('admin.attendance.add', compact('levels', 'teachers'));
}
/**
* Store values in application dashboard
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function store(Request $request, $level_id)
{
//get form data
$data = $request->all();
//Creeate Student record
$students = Student::all();
$levels = Levels::all();
if($level_id){
$levels = Levels::find($level_id);
if($levels){
$attendance = Attendance::with(['student', 'levels'])->first();
return view('admin.attendance.add', compact('students','level_id', 'levels', 'attendance'));
}
}
}
}
Here is my Attendance model
public function student()
{
return $this->belongsTo(Student::class,'student_id');
}
public function teacher()
{
return $this->belongsTo(Teacher::class, 'teacher_id');
}
public function levels()
{
return $this->belongsTo(Levels::class, 'level_id');
}
Here is my list.blade.php file of containing attendance
#section('content')
#if(session()->has('message'))
<div class="row">
<div class="col-md-12">
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
</div>
</div>
#endif
#if(isset($levels) || $levels == '')
<div class="form-row justify-content-center">
<div class="form-group col-xs-6">
<label for="Date"> Please Select Date</label>
<input type="date" name="attendance_date" value="{{ date('Y-m-d') }}" class="form-control" required>
</div>
<div class="form-group col-xs-6">
<label for="Attendance">Please Select Level to see registered students</label>
<select class="form-control" id="level_id" name="student_id">
<option value="" disabled selected>Select Level</option>
#foreach($levels as $level)
<option value="{{#$level->id}}">{{#$level->level_name}}</option>
#endforeach
</select>
</div>
</div>
#endif
#stop
#section('js')
<script>
jQuery(document).ready(function($) {
// get your select element and listen for a change event on it
$('#level_id').change(function() {
// set the window's location property to the value of the option the user has selected
window.location = '/attendance/add/'+$(this).val();
});
});
</script>
#endsection
Here is my add.blade.php file containing attendance
<form action="{{ route('attendance.index') }}" method="GET" class="w-full max-w-xl px-6 py-12" enctype="multipart/form-data">
#csrf
#php
$heads = [
'Name',
'Roll Number',
'Semester',
['label' => 'Attendance', 'no-export' => true, 'width' => 5],
];
/*$btnDetails = '<button class="btn btn-xs btn-default text-teal mx-1 shadow" title="Details">
<i class="fa fa-lg fa-fw fa-eye"></i>
</button>';*/
$config = [
'data' => $students,
'order' => [[1, 'asc']],
'columns' => [null, null, null, null, ['orderable' => true]],
];
#endphp
{{-- Minimal example / fill data using the component slot --}}
<x-adminlte-datatable id="table6" :heads="$heads" head-theme="light" theme="light custom-head-theme dt-responsive"
striped>
#if($config['data'])
#foreach($config['data'] as $row)
<tr class="{{ (isset($row['status']) && $row['status']==0) ? 'table-danger' : ''}}">
<td>{!! $row['student_given_name'] !!}</td>
<td>{!! $row['student_roll_no']!!}</td>
<td>{!! $row['student_semester']!!}</td>
<td>
<nobr>
<select class="form-control" name="attendance_status" value="{{old('attendance_status'), #$attendance->attendance_status}}" id="attendance_status" required>
<option value="" {{#$attendance->attendance_status == '' ? 'selected' : ''}} disabled selected>Select Option</option>
<option value="Present" {{#$attendance->attendance_status == 'present' ? 'selected' : ''}} selected>Present</option>
<option value="Absent" {{#$attendance->attendance_status == 'absent' ? 'selected' : ''}}>Absent</option>
</select>
<input type="text" name="textinput" id="level_id" placeholder="Reason">
</nobr>
</td>
</tr>
#endforeach
#endif
</x-adminlte-datatable>
<div class="row mt-3">
<div class="col-md-12">
<div class="card-footer">
<div class="float-left col-md-4 mb-2">
<button type="submit" name="save_close" value="true" class="btn btn-primary btn-lg btn-block">Save & Close</button>
</div>
<div class="float-right col-md-4 mb-2">
<button type="button" class="btn btn-secondary btn-lg btn-block">Cancel</button>
</div>
</div>
</div>
</div>
</form>
#stop
What modifications are required in attendance controller in order to save record in table and I can view it on frontend side as well
On your AttendanceController you just show data, not insert data to database, you should get the request data and insert data to database, but first check your blade file, you must make an input for level_id, teacher_id, and student_id
to check your attachment you can use
dd($request);
die();
on your first line AttendanceController function store
public function store(Request $request, $level_id)
{
dd($request);
die();
//get form data
$data = $request->all();
//Create Student record
$students = Student::all();
$levels = Levels::all();
if($level_id){
$levels = Levels::find($level_id);
if($levels){
$attendance = Attendance::with(['student', 'levels'])->first();
return view('admin.attendance.add', compact('students','level_id', 'levels', 'attendance'));
}
}
}
if your system catch the good request
you should try this
public function store(Request $request, $level_id)
{
$levels_id = $request->level_id;
$teachers_id = $request->teacher_id;
$students_id = $request->student_id;
$data = [$levels_id,teachers_id,students_id];
attendance::create($data);
}
there's the code to save data into your laravel project, you should approve my solution

Property [costo] does not exist on this collection instance

i need to print the price of a service, but can't find the column with the price.
maybe I'm doing something wrong with relationships, but I can't figure it out on my own
database:
Controller:
public function details(Request $request,$id){
$datax = [
'category_name' => 'apps',
'page_name' => 'calendar',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$evento = Eventos::find($id);
$servicio = \App\Models\Eventos::select("servicio_id")->where('servicio_id', $evento->id)->get('servicio_id');
$event = Eventos::find($id);
$event->asistencia = $request->asistencia;
$event->cancelado = $request->cancelado;
$event->save();
return view("evento",[
"event" => $event,
"servicio" => $servicio
])->with($datax);
}
blade.php
<div class="input-group mb-4">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="text" value="{{$servicio->costo}}" class="form-control col-md-3" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text"></span>
</div>
</div>
I need to print the "costo" column in relation to service_id
help please
you can use laravel elequent relationship one to one.
if you have this two Servicio.php & Evento.php in App/Models or whatever your models name is, only replace your models in below code do this:
1-
in App/Models/Servicio.php define this relationship:
public function evento()
{
return $this->hasOne(Evento::class);
}
in App/Models/Evento.php define this relationship:
public function servicio()
{
return $this->belongsTo(Servicio::class);
}
now in controller add this:
$evento = Eventos::where('id' , $id)->with('servicio')->first();
in blade use this:
<input type="text" value="{{$evento->servicio->costo}}" >
2- also you can do this but i suggest you the first one:
only in your Codes change this:
$servicio = \App\Models\Servicio::where('id', $evento->servicio_id)->first();

How to update column in database in blade.php file Laravel

Hello I have row in a database table have an id and name and etc.. and active = 1
I want in blade.php file when someone click a button it change into 0 in 1 click
What I tried is {{$referral_detail->update('active', 1)}}
And
{{$referral_detail->IDT->where('active', 0)->update('active', 1)}}
Function in Controller is
public function DriverReferAll()
{
$query = DriverReferralDiscount::where([['referral_driver_id', '!=', 0],
['referral_sender_id', '!=', 0], ['active', '<>', 1]
]);
$referral_details = $query->paginate(25);
return view('merchant.driver.driver_referall', compact('referral_details', 'query'));
}
I got it thedit('{{$referral_detail->IDT->update(['active' => 1])}}')
and function
function thedit(a) {
$("input:submit").val(a);
}
But when I do it , it change the first 2 column not only 1 tho I put the specific id any idea?
its in onClick""
<span onClick=" thedit('{{$referral_detail->IDT->update(['active' => 1])}}')
" data-target="#addMoneyModel"
data-toggle="modal" id="{{ $referral_detail->GetterDriver->id }}"><a
data-original-title="Add Money"
data-toggle="tooltip"
id="{{ $referral_detail->GetterDriver->id }}" data-placement="top"
class="btn text-white btn-sm btn-success menu-icon btn_detail action_btn"> <i
class="fa fa-money-bill"></i> </a></span>
For that you must create a link in your blade template when that link is clicked It must have an href which point to the laravel route which will perform the update of your active state.
<a href="{{ route('your_route_name', ['id' => $referral_detail->id]) }}>Change</a>
the route can be define like this
Route::get('/route_path/{id}', 'ControllerName#action_name')->name('route_name');
Or If you want the browser to not refresh you can perform and Ajax

Laravel Select the First Row From HasMany Relation

I have 2 table where 1 products have many prodphotos
I can retrieve all prodphotos from products with the same id, but my case is listing all the products but only take 1 photo from prodphotos.
Controller :
public function daftarproduk()
{
$produks = Product::orderBy('created_at', 'desc')->get();
$select = Product::with('prodphotos')->firstorfail();
$photo = $select->prodphotos->pluck('photo');
$kategori = Category::orderBy('created_at', 'asc')->get();
return view('guest.daftarproduk')
->with('produks',$produks)
->with('kategori',$kategori)
->with('select',$select)
->with('photo',$photo);
}
View :
#foreach($produks as $value)
<div class="col-xs-6 col-md-4 col-lg-3 box-product-outer">
<div class="box-product">
<div class="img-wrapper">
<a href="detail/{{$value->id}}/{{str_slug($value->name)}}">
<img alt="Product" src="images/gambarproduk/thumb_{{ i dont know what i must throw here to only get first picture }}">
</a>
</div>
<h6>{{$value->name}}</h6>
</div>
</div>
#endforeach
I dont know what function I must use to get the first photo name from $select or $photo from controller. or my foreach logic is wrong? Please help me.
Add a featured photo relation with hasOne type to your Product model.
Product model
public function featuredPhoto() {
return $this->hasOne(PhotosModel);
}
In your controller
public function daftarproduk()
{
// Get the products with featured image
$produks = Product::with('featuredPhoto')->orderBy('created_at', 'desc')->get();
$kategori = Category::orderBy('created_at', 'asc')->get();
return view('guest.daftarproduk')
->with('produks',$produks)
->with('kategori',$kategori);
}
View
#foreach($produks as $value)
<div class="col-xs-6 col-md-4 col-lg-3 box-product-outer">
<div class="box-product">
<div class="img-wrapper">
<a href="detail/{{$value->id}}/{{str_slug($value->name)}}">
<img alt="Product" src="images/gambarproduk/thumb_{{ $value->featuredPhoto->photo }}">
</a>
</div>
<h6>{{$value->name}}</h6>
</div>
</div>
#endforeach

Resources