In my User Model i have this getter method:
public function getWorkedHoursInRangeAttribute($start, $end)
{
$sum = [];
foreach($this->workedTimes as $item) {
if( ($item->start_time->gt($start)) && ($item->end_time->lt($end)) ){
array_push($sum, ceil($item->end_time->diffInMinutes($item->start_time->addMinutes($item->break_time_min))/60 * 4) / 4 );
}
}
return array_sum($sum);
}
And in my view i post this
function(start, end) {
$.ajax({
type: "POST",
url: '/users/workedhours',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: {"start": start.format("DD.MM.YYYY HH:mm"), "end": end.format("DD.MM.YYYY HH:mm")},
and i have this in my Controller
public function getWorkedHoursForRange(Request $request)
{
$start = Carbon::parse($request->start);
$end = Carbon::parse($request->end);
return response()->json(['msg' => $start], 200);
}
and this route:
Route::post('users/workedhours', 'UsersController#getWorkedHoursForRange');
How can i take this start and end variables from ajax to my Model method and make calculation?
I will probably need to do something in my Controller...but what?
UPDATE:
in view i have this foreach loop for my table:
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->total_time_current_year }}</td>
<td>{{ $user->total_time_last_year }}</td>
<td>{{ $user->total_time_current_month }}</td>
<td>{{ $user->total_time_last_month }}</td>
<td>here i need the calculation for date range</td>
</tr>
#endforeach
</tbody>
You need two attributes in your model: start and end. That way you are able to access them in your accessor.
protected $start;
protected $end;
public function getWorkedHoursInRangeAttribute()
{
$sum = [];
foreach($this->workedTimes as $item) {
if( ($item->start_time->gt($this->start)) && ($item->end_time->lt($this->end)) ){
array_push($sum, ceil($item->end_time->diffInMinutes($item->start_time->addMinutes($item->break_time_min))/60 * 4) / 4 );
}
}
return array_sum($sum);
}
You than make your AJAX call to the controller, loop through the users, set start and end vars to each user-model and return all users to the view. There you can access your accessor-attribute.
public function getWorkedHoursForRange(Request $request)
{
$start = Carbon::parse($request->start);
$end = Carbon::parse($request->end);
$users = App\User::all();
foreach($users as $user) {
$user->start = $start;
$user->end = $end;
}
return response()->json(['users' => $users], 200);
}
Related
I want to update and delete multiple images on laravel, the old images will be automatically deleted from storage after the update. And when I click to delete all images and other data are deleted too
Controller:
public function index(Request $request){
if($request->has('search')){
$data = rekap::where('customer','LIKE','%' .$request->search. '%')->paginate(5);
}else{
$data = rekap::paginate(5);
}
return view('rekap')->with([
'data' => $data,
]);
}
public function tambah_rekap(){
return view ('tambah_rekap');
}
public function insert_rekap(Request $request){
// dd($request->all());
$data = $request->validate([
'customer'=>'required',
'vessel'=>'required',
'scopejob'=>'required',
'pergantian_sparepart'=>'required',
'teknisi'=>'required',
'tahun'=>'required',
'keterangan'=>'required'
]);
$new_data= rekap::create($data);
if($request->has('images')){
foreach($request->file('images')as $image){
$imageName = $data['customer'].'-image-'.time().rand(1,1000).'.'.$image->extension();
$image->move(public_path('data_images'),$imageName);
Image_rekap::create([
'rekap_id'=>$new_data->id,
'image'=>$imageName
]);
}
}
return redirect()->route('rekap')->with('success','Data Berhasil Ditambahkan');
}
public function images($id){
$data = rekap::find($id);
if(!$data) abort(404);
$images = $data->images;
return view ('image_rekap',compact('data','images'));
}
public function show_rekap($id){
$data = rekap::find($id);
return view('show_rekap', compact('data'));
}
public function update_rekap(Request $request,$id){
$data = rekap::find($id);
$data->update($request->all());
return redirect()->route('rekap')->with('success','Data Berhasil di Update');
}
public function delete_rekap($id){
$data = rekap::find($id);
$data->delete();
return redirect()->route('rekap')->with('success','Data berhasil dihapus');
}
and this is my HTML
<tbody>
#foreach ($data as $row)
<tr>
<td>{{ $row->customer}}</td>
<td>{{ $row->vessel}}</td>
<td>{{ $row->scopejob}}</td>
<td>{{ $row->pergantian_sparepart}}</td>
<td>{{ $row->teknisi}}</td>
<td>{{ $row->tahun}}</td>
<td>{{ $row->keterangan}}</td>
<td>{{ $row->images->count()}}</td>
<td>
INFO
EDIT
<a href="#" class="btn btn-danger delete" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a>
</td>
</tr>
#endforeach
</tbody>
And this is my view:
enter image description here
What steps can I take to achieve updating new images in my laravel application?
I am new to Laravel. I'm building a small app which displays the user table from the DB, but before sending it to the view, I want to include a custom value from another function.
The accounts table fetches the list of accounts from MySQL, and I want to include a custom function called getStatus() which I get from an API.
Code
<?php
public function accounts()
{
$accounts = DB::table('accounts')
->where('profile_id', '=', Auth::id())
->get();
foreach ($accounts as $account) {
$account->status = getStatus($account->accno);
}
$data = compact('accounts');
return view::make('transactions', ['accounts' => $data]);
}
View
#foreach ($accounts as $account)
<tr>
<td></td>
<td>{{ $account->login }}</td>
<td>{{ $account->status }}</td>
</tr>
#endforeach
You can do it like this.
$accounts = $accounts->map(function($account){
$account->status = getStatus($account->accno)
});
Hope this will help you.
Thanks
$accounts = DB::table('accounts')
->where('profile_id', '=', Auth::id())
->get()
->map(function($item){
$item->status = getStatus($item->accno);
return $item;
});
Now you'll have status in your $accounts.
I have two for-each loop inside my create view [Subject_id, Lead_id], I want to store the for-each value into my database using array approach, and I couldn't make it work can anyone amend my codes or point me to a proper way thanks.
Controller:
public function store(Request $request)
{
//
$input = $request->all();
$items = array(['Subject_id','Lead_id']);
foreach($input as $inputs) {
$items[] = $inputs;
}
$scores = new Score();
$scores->Subject_id=$items['Subject_id'];
$scores->Lead_id=$items['Lead_id'];
$scores->save();
dd($request->all());
return redirect()->route('scores.create')->with('notif', 'Success.');
}
this is the message:
create view
#foreach ($leads as $lead)
<tr>
<td>{{ $lead->student_name }}</td>
<td><input type="checkbox" class="checkbox" name="Lead_id[]" value="{{ $lead->id }}"></td>
</tr>
#endforeach
#foreach($subjects as $subject)
<label >
<input type="checkbox" name="Subject_id[]" value="{{ $subject->id }}">
{{ $subject->subject_name }}
</label>
#endforeach
DD Result:
Try this code in your controller
public function store(Request $request)
{
$data = $request->all();
$leads = $data['Lead_id'];
$subject_ids = $data['Subject_id'];
//insert using foreach loop
foreach($leads as $key => $input) {
$scores = new Score();
$scores->Subject_id = isset($leads[$key]) ? $leads[$key] : ''; //add a default value here
$scores->Lead_id = isset($subject_ids[$key]) ? $subject_ids[$key] : ''; //add a default value here
$scores->save();
}
//insert using array at once
$rows = [];
foreach($leads as $key => $input) {
array_push($rows, [
'Subject_id' => isset($leads[$key]) ? $leads[$key] : '', //add a default value here
'Lead_id' => isset($subject_ids[$key]) ? $subject_ids[$key] : '' //add a default value here
]);
}
Score::insert($rows);
return redirect()->route('scores.create')->with('notif', 'Success.');
}
Every time creating an instance of model in foreach loop in not an efficient way. You can do something like this
foreach($input as $inputs) {
$dataArray[] = [
'Subject_id' => $inputs['Subject_id'],
'Lead_id' => $inputs['Lead_id'],
];
}
DB::table('Score')->insert($dataArray);
You can manipulate the data as you want.
with this code i have this
Update your blade
#foreach ($leads as $lead)
{{ $lead->student_name }}
#foreach($subjects as $subject)
<input type="checkbox" name="Subject_id[$lead->id][]" value="{{ $subject->id }}">
{{ $subject->subject_name }}
#endforeach
#endforeach
This as your controller
public function store(Request $request)
{
//
$subjects = $request->get('Subject_id');
foreach($subjects as $key=>$oneLeadOptions) {
foreach($oneLeadOptions as $option){
$scores = new Score();
$scores->Subject_id = $option;
$scores->Lead_id = $key;
$scores->save();
}
}
//To to other redirects logic here
}
try this
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?
This is my library, here I want to delete or update something from my database
#foreach ($allJobs as $job)
<tr>
<td><img src="{{$job->selected_icon}}" width="50" /> </td>
<td>{{$job->jobtitle_de}}</td>
<td>{{$job->location}}</td>
<td><img src="{{$job->selected_image}}" width="100" /></td>
<td>{{$job->workinghours}}</td>
<td>{{$job->grey_header_de}}</td>
<td>{{$job->date}}</td>
<td>
<button>Edit</button> <a href="/delete">
<button>Delete</button></a></td>
<!--<td> <button type="delete" name="button"></button>-->
<td>
</td>
</tr>
#endforeach
In your controller (I will assume that you have created), implements this two functions.
public function edit($id) {
// Create a var called `$job` and uses the function `find()` passing into the $id that you clicked before
$job = Job::find($id);
// Return a view with the object that you found into a edit view
return view('jobs.edit', [
'job' => $job
]);
}
public function destroy($id) {
// Use the function `find()` passing into the $id that you clicked before and that use the delete method to delete the job
Job::find($id)->delete();
// Returning into a route that contains the jobs, probably
return redirect()->route('jobs');
}
Read the docs https://laravel.com/docs/5.4/controllers
in your route:
Route::post('delete','CallyourController#delete');
Route::post('update','CallyourController#update');
I think this is what you want to do.
my Controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use App\Jobs;
class JobController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return view('library',['allJobs' => Jobs::all()]);
}
//my create function
public function create()
{
return view('add');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$job = new Jobs();
$job->jobtitle_de = array_key_exists('jobtitle_de',$_POST) ?
$_POST['jobtitle_de'] : '';
$job->jobtitle_en = array_key_exists('jobtitle_en',$_POST) ?
$_POST['jobt'] : '';
if (array_key_exists('place', $_POST)) {
$places = $_POST['place'];
$placesString = "";
foreach ($places as $p) {
$placesString .= $p.',';
}
$job->location = $placesString;
}
$job->workinghours = array_key_exists('workinghours',$_POST) ?
$_POST['workinghours'] : '';
$job->workinghours_de = array_key_exists('workinghours',$_POST) ?
$_POST['workinghours'] : '';
$job->selected_image= array_key_exists('selected_image',$_POST) ?
$_POST['selected_image'] : '';
$job->grey_header_de = array_key_exists('grey_header_de',$_POST) ?
$_POST['grey_header_de'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->date;
if (array_key_exists('date',$_POST) && !empty($_POST['date'])) {
$date = $_POST['date'];
$date = explode('/',$_POST['date']);
$newdate = $date[2]."-".$date[0]."-".$date[1];
$job->date = $newdate;
}
$job->grey_header_de = $_POST['grey_header_de'];
if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
=== "full-time") {
$job->workinghours = $_POST['workinghours'];
$job->workinghours_de = "Vollzeit";
}
if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
=== "part-time"){
$job->workinghours = $_POST['workinghours'];
$job->workinghours_de = "Teilzeit";
}
try {
$job->save();
}
catch (Exceptions $e) {
echo $e->getMessage();
}
return redirect()->action('JobController#index');
}
//my edit function
public function edit($id)
{
$job = Job::find($id);
return view('jobs.edit', [
'job' => $job
]);
}
//destroy function
public function destroy($id)
{
Job::find($id)->delete();
return redirect()->route('jobs');
}
now I found this in the internet:
<div class="library">
<table>
#foreach ($allJobs as $job)
<tr>
<td><img src="{{$job->selected_icon}}" width="50" /> </td>
<td>{{$job->jobtitle_de}}</td>
<td>{{$job->location}}</td>
<td><img src="{{$job->selected_image}}" width="100" /></td>
<td>{{$job->workinghours}}</td>
<td>{{$job->grey_header_de}}</td>
<td>{{$job->date}}</td>
<td>
{{ Form::open(['method' => 'DELETE', 'route' => 'job.destroy', $job]-
>id]) }}
{{ Form::hidden('id', $job-id) }}
{{ Form::submit('delete', ['class' => 'library']) }}
{{Form::close}}
</td>
</tr>
#endforeach
and this is my Controller
public function destroy($id)
{
$jobs = Job::findOrFail($id);
$jobs->delte();
return redirect::route('/');
}
I am trying to pass a variable through an href url on my View, and have the Controller function query based on those variables. Here is code to get a better idea.
#foreach ($totalCount as $id => $name) {{-- id is the admin id --}}
<?php
$admin_id = $id;
?>
#foreach($name as $n => $status) {{-- $n is the name, $status is array of the counts --}}
<tr>
<td>
{{$n}}
<br>
Closed
</td>
<td>{{ isset($status[2]) ? $status[2] : 0 }}</td>
<td>{{ isset($status[1]) ? $status[1] : 0 }}</td>
<td>{{ isset($status[3]) ? $status[3] : 0 }}</td>
<td>{{ isset($status[4]) ? $status[4] : 0 }}</td>
<td>{{ isset($status[5]) ? $status[5] : 0 }}</td>
<td>{{ isset($status[6]) ? $status[6] : 0 }}</td>
</tr>
#endforeach
#endforeach
As you can see, I am getting that $id from my data structure and inputting it into $admin_id so I can use it. I take that admin id and place it into the href url so my controller can work with it and query properly.
Here is code from my controller:
public function index()
{
$query = AdvertiserApplication::with('admin');
$status = Input::get('status');
$id = Input::get('admin_id');
dd($id);
if(!empty($id)) {
$query->where('assigned_to', '=', $id);
}
if (!empty($status) || $status === '0')
$query->where('staus', '=', $status);
$applications = $query->get();
return View::make('admin.advertisers.application_list', ['applications' => $applications, 'admin_id' => AuthAdmin::admin(false)]);
}
What I am doing here is querying the whole table if $id and $status empty. (By the way status comes from a drop down table on the application list View.) The problem I am having is that the $id input is not working, it is coming in NULL. Any help would be appreciated!
Should be
Input::get('id');
Instead of
Input::get('admin_id');
You have to add $id as parameter of index function.
When variable is sent through href it is not element of GET/POST array.
So your function will lool like this:
public function index($id)
{
$query = AdvertiserApplication::with('admin');
$status = Input::get('status');
// $id = Input::get('admin_id');
// dd($id);
if(!empty($id)) {
$query->where('assigned_to', '=', $id);
}
if (!empty($status) || $status === '0')
$query->where('staus', '=', $status);
$applications = $query->get();
return View::make('admin.advertisers.application_list', ['applications' => $applications, 'admin_id' => AuthAdmin::admin(false)]);
}