How to update and delete multiple images in laravel? - php

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?

Related

Custom Calculation in Laravel Controller

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.

Laravel - pass ajax variables to model

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);
}

updateExistingPivot won't work

I'm trying to update my pivot table approve_document where it has a extra column isApprove using ->withPivot method.
Model:
Document
class Document extends Model
{
public function sentToApprovers()
{
return $this->belongsToMany('App\Models\Approve', 'approve_document')->withPivot('isApprove');
}
}
Approve
class Approve extends Model
{
public function createdpendingDocuments()
{
return $this->belongsToMany('App\Models\Document', 'approve_document')->withPivot('isApprove');
}
}
This is where I get all my records in my approve_document.
Controller:
public function documentsSentForApproval()
{
$pendingDocumentLists = DB::table('approve_document')
->select('documents.title', 'documents.content', 'categories.category_type', 'users.username', 'approve_document.dateReceived', 'documents.id', 'approves.approver_id')
->join('documents', 'documents.id', '=', 'approve_document.document_id')
->join('categories', 'categories.id', '=', 'documents.category_id')
->join('approves', 'approves.id', '=', 'approve_document.approve_id')
->join('users', 'users.id', '=', 'approves.approver_id')
->where('approver_id', '=', Auth::id())
->orWhere('requestedBy', '=', Auth::id())
->get();
return view ('document.pending')
->with('pendingDocumentLists', $pendingDocumentLists);
}
View:
#foreach ($pendingDocumentLists as $list)
<tr class = "info">
<td>{{ $list->title }}</td>
<td>{{ strip_tags(substr($list->content, 0, 50)) }} {{ strlen($list->content) > 50 ? "..." : '' }}</td>
<td>{{ $list->category_type }}</td>
<td>{{ $list->username }}</td>
<td>{{ date('M, j, Y', strtotime($list->dateReceived)) }}</td>
<td>
#if (Auth::id() == $list->approver_id)
<a href = "{{ route ('document.pending', $list->id) }}">
<button type = "submit" class = "btn btn-success glyphicon glyphicon-thumbs-up"> Approve</button>
</a>
#endif
</td>
<td></td>
</tr>
#endforeach
You can see here I have a approve button where I need to set isApprove to true when the button is clicked. You can see that I get the current id of the document when the button was clicked.
This part of the Controller where I'm having a hard time updating my pivot table. It gives me a error MethodNotAllowedHttpException. Any tips or help would greatly appreciated!
public function updateIsApprove($id)
{
$document = new Document();
foreach ($document as $update)
{
$approve = new Approve();
$document->sentToApprovers()->updateExistingPivot([$approve->id => ['isApprove' => '1']],false);
}
return redirect()->route('document.pending');
}
routes:
Route::post('/documents/pending/approve/{id}',
[
'uses' => '\App\Http\Controllers\DocumentController#updateIsApprove',
'as' => 'document.pending',
]);
public function updateExistingPivot($id, array $attributes, $touch = true)
First parametr should be id of related thing.
public function updateIsApprove($documentId, $approveId)
{
$document = Document::find($documentId);
if (!$document) {
// Handle error that document not exists.
}
$approve = $document->sentToApprovers()->find($approveId);
if (!$approve) {
// Handle that approve not exists or is not related with document.
}
$document->sentToApproves()->updateExistingPivot($approve->id, ['isApprove' => 1]);
return redirect()->route('document.pending');
}
MethodNotAllowedHttpException is not for your controller but is for your Route. As you can see, in your Routes file, you have Route for handling POST request, but in your view you are making a GET request by accessing the URL directly.
So, just change the POST route to GET in your Routes file.
Route::get('/documents/pending/approve/{id}',
[
'uses' => '\App\Http\Controllers\DocumentController#updateIsApprove',
'as' => 'document.pending',
]);

Laravel 5 check if pivot data is already in database

Got a ManyOnMany system (3 tables, projects, users, project_user)
Many users can work on a project, and a user can have many projects.
When checkbox = checked it sends the database to the pivot table.
Now I'm facing the problem that everytime I click the project/user id will get send to the project_user table.
And I need to have the checkbox already checked when the user is actually added to the project.
So how I see it: the form::checkbox has a third function checked or not checked, and with an if/else statement in my controller.edit I will have a validation somehow. Please help me!
Blade:
#foreach($users as $user)
<tr>
<td>
{{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
</td>
<td>
{!! Form::checkbox('contribute['.$user->id.']', '1', $checkifinproject) !!}
</td>
</tr>
#endforeach
Controller:
public function edit($id, Project $project)
{
$users = User::all();
$project = $this->project->find($id);
if ($users == $project)
{
$checkifinproject = 'checked';
}
else {
}
return view('project.edit', ['project' => $project, 'id' => 'edit', 'project_id' => $id], compact('users'));
}
public function update(CreateProjectRequest $request)
{
if($request->get('contribute'))
{
foreach($request->get('contribute') as $k => $contribute)
{
if($contribute == 1)
{
$project = $this->project->find($request->project_id);
$project->users()->attach($k);
}
}
}
$project = $this->project->find($request->project_id);
$project->fill($request->input())->save();
return redirect('project');
}
Model:
User
public function projects()
{
return $this->belongsToMany('App\Project', 'project_user', 'user_id', 'project_id');
}
Project
public function users()
{
return $this->belongsToMany('App\User', 'project_user', 'project_id', 'user_id');
}
I think the issue is you are comparing two things that will never be the same and trying to determine if that user belongs to the project. A better thing to do would be to query all the users with their projects and as you loop through the users, check to see that the project you are modifying is one of the projects the user belongs to.
That can be done like this...
Controller
public function edit($id, Project $project)
{
$users = User::with('projects')->get();
$project = $this->project->find($id);
return view('projects.edit', ['users' => $users, 'project' => $project]);
}
View
#foreach($users as $user)
<tr>
<td>
{{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
</td>
<td>
{!! Form::checkbox('contribute['.$user->id.']', '1', $user->projects->contains('id', $project->id)) !!}
</td>
</tr>
#endforeach

Search form with multiple criteria , Symfony2

I'm trying to create a search form with multiple criteria but it doesn't work, and I think the controller does not receive the form because when I click Button Submit the page reloads only.
This is the Controller
/**
* #ParamConverter("agence", options={"mapping": {"agence_slug":"slug"}})
*/
public function indexAction(Agence $agence, Request $request)
{
$form = $this->createForm(new SearchTravelType());
$request = $this->getRequest();
$em = $this->getDoctrine()->getManager();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$criteria = $form->getData();
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->getListBy($criteria, $agence);
}
}
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->findByAgence($agence);
return $this->render('ProjectDashboardBundle:Travel:index.html.twig',
array(
'listTravels' => $listTravels,
'agence' => $agence,
'form' => $form->createView() ,
));
}
and this is the queryBuilder
class TravelRepository extends EntityRepository
{
public function getListBy($criteria, $agence)
{
$qb = $this->createQueryBuilder('t');
$qb = $this->whereAgence($qb, $agence);
$qb ->leftJoin('t.airport', 'a')
->addSelect('a');
foreach ($criteria as $field => $value) {
if (!$this->getClassMetadata()->hasField($field)) {
// Make sure we only use existing fields (avoid any injection)
continue;
}
$qb ->andWhere($qb->expr()->eq('t.'.$field, ':t_'.$field))
->setParameter('t_'.$field, $value);
}
return $qb->getQuery()->getResult();
}
public function whereAgence (\Doctrine\ORM\QueryBuilder $qb, $agence)
{
$qb->where('a.agence = :agence')
->setParameter('agence', $agence);
return $qb;
}
}
and this is the page twig and the form
<form class="form-horizontal" role="form" method="post" >
<td>{{ form_widget(form.id) }}</td>
<td class="center">-</td>
<td>{{ form_widget(form.title) }}</td>
<td>{{ form_widget(form.country) }}</td>
<td>{{ form_widget(form.destination) }}</td>
<td>{{ form_widget(form.airport) }}</td>
<td>{{ form_widget(form.departureDate) }}</td>
<td>{{ form_widget(form.returnDate) }}</td>
<td>{{ form_widget(form.price) }}</td>
<td>{{ form_widget(form.enabled) }}</td>
<td><span class="input-group-btn">
<button type="submit" class="btn btn-purple btn-sm">Search
<i class="icon-search icon-on-right bigger-110"></i></button>
</span>
</form>
I think the first problem is that form is not recovered in the controller, I tried with
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->find(1);
instead
getListBy($criteria, $agence)
to see what gives. the controller ignores the form and it goes directly to the following queries
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->findByAgence($agence);
You can remove $request = $this->getRequest(); from action as you are passing REquest object to this action;
You need to add action to your form,
like this:
$this->createForm(new SearchTravelType(), null, [
'action' => $this->generateUrl('ROUT')
]);
or like this:
<form class="form-horizontal" role="form" method="post" action="{{ path('ROUT') }}" >
EDIT:
We create a filter form with GET method (you should use POST method for inserting to DB, not for fetching results), disable CSRF protection. We create a controller action:
public function indexAction(Agence $agence, Request $request)
{
$form = $this->createForm(new SearchTravelType(), null, [
'action' => $this->generateUrl('ROUTE'),
'method' => 'GET'
]);
$form->handleRequest($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$criteria = explode('&', $request->query->get($form->getName())); // I didn't test this line, you should check it..
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->getListBy($criteria, $agence);
// Terminate the request
return $this->render('ProjectDashboardBundle:Travel:index.html.twig',
array(
'listTravels' => $listTravels,
'agence' => $agence,
'form' => $form->createView() ,
));
}
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->findByAgence($agence);
return $this->render('ProjectDashboardBundle:Travel:index.html.twig',
array(
'listTravels' => $listTravels,
'agence' => $agence,
'form' => $form->createView() ,
));
}
You can try this bundle:
https://github.com/petkopara/PetkoparaMultiSearchBundle
Provides form or service for multi criteria search in Doctrine Entity.
In your case the form solution will solve your issue:
First in your form type just only add the MultiSearchType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('search', MultiSearchType::class, array(
'class' => 'ProjectTravelBundle:Travel'));
}
Then in your Controller add the following code
public function indexAction(Request $request)
{
$search = $request->get('search');
$em = $this->getDoctrine()->getManager();
$queryBuilder = $em->getRepository('ProjectTravel:Travel')->createQueryBuilder('e');
$filterForm = $this->createForm('ProjectTravelBundle\Form\TravelType');
// Bind values from the request
$filterForm->handleRequest($request);
if ($filterForm->isValid()) {
// Build the query from the given form object
$queryBuilder = $this->get('petkopara_multi_search.builder')->searchForm($queryBuilder, $filterForm->get('search'));
}
..
}
At the last render your Travel form in your template
{{form_render(filter_form)}}

Categories