checkbox values not being received in laravel controller - php

I have this bit of code in my form edit.blade.php :
#php
$imagepath="images/Service/".$services->name."/";
$images=glob($imagepath.'*.*');
#endphp
<div class="row">
#foreach($images as $image)
#php
$count++;
#endphp
<div class="col-md-5">
<img src="{{URL::asset($image)}}" style="height: 150px;object-fit: contain;">
</div>
<div class="col-md-1">
<input form="services" type="checkbox" name="deleteimagelink[]" value="{{($image)}}" >
</div>
#endforeach
</div>
This is for passing the path of those images meant to be deleted.
And I have this snippet in my controller:
print_r($request->input('deleteimagelink'));
$deletables=$request->input('deleteimagelink');
foreach ($deletables as $deletable)
{
print_r($deletable);
unlink($deletable);
}
I have this problem that nothing is being received in the $request->input('deleteimagelink') parameter.
Please guide me if I'm doing anything wrong.
If nothing seems weird, can you please guide me how to deal with these checkbox situations in laravel.
I consulted related answers from internet but nothing seems to work.

<form class="form-group" method="post" action="/destroy" enctype="multipart/form-data">
#csrf
<input type="checkbox" name="deleteimagelink[]" value="1" >
<input type="checkbox" name="deleteimagelink[]" value="2" >
<button class="btn btn-primary" type="submit">Actualizar</button
</form>
Controller
public function destroy(Request $request)
{
return $request;
}
{"_token":"BetJnyujXvJnpkkwDU31kYO7lVz5OqflMQDoCLQy","deleteimagelink":["1","2"]}
This Works for me!

I had included the code above outside the <form></form> tag in order to justify to my view. Interestingly, it didn't work even though that I had included form="services" as a parameter in my input field{services is the form name here}. I had worked something like this before and it had worked pretty good that time. I managed to get the <form></form> tags outside the whole of my form elements and it is working fine now.
Thank you everybody who tried to help.

Related

Button Call to controller function / method

I am using Laravel 7 and am stuck on trying to initiate a Controller method via a button in my view. I am using a form with a simple a tag but am not sure if how I am going about it is the best way. Besides, I am getting an error withe the way I am attempting it. The error is:
Too few arguments to function App\Http\Controllers\TasksController::finished(), 1 passed in C:\laragon\www\taskapp\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
I am truly stumped on how to call a method from a button click. What I am trying to do is (when the button is clicked) change the status of an item in my db called $task->task_status to "Complete".
In my table in the home view, I have a form like this:
<td>
<form method="POST" action="/tasks/{{$task->id}}">
{{ csrf_field() }}
{{ method_field('POST') }}
<div class="ml-5">
<i class="fa fa-check"></i>
</div>
</td>
In my web.php, I have:
Route::get('/finished/{id}', 'TasksController#finished')->name('finished');
And in my TasksController, I have the following:
public function finished(Request $request, $id) {
$task = Task::find($id);
dd($task);
$task->task_status = $request['task_status'] = 'Completed';
$task->save();
return redirect('home')->with('success', 'Task Completed and now viewable in Completed Tasks!');
}
If anyone can show me a better way of accomplishing this (without using axaj) I would really appreciate it.
Thank you in advance.
I ended up fixing this in using the following code:
in my web.php, I used:
Route::get('/finished/{id}', 'TasksController#finished');
in my home.blade.php, I have:
<td>
<form action="finished/{{$task->id}}" method="GET" style="display: inline" class="">
#csrf
#method('POST')
<div class="ml-5">
<button type="submit" class="btn btn-sm btn-success">
<i class="fa fa-check"></i>
</button>
</div>
</form>
</td>
And in my TasksController, I pretty much left that the way it was and it now works.

laravel compact data wont read in home.blade.php

here is my code form my controller
i9ts seem to Image::get() not working when I use image::all() then its work
public function index(){
$images = Image::get();
return view('home', compact('images'));
}
here is my home.blade.php
<div class="container">
<div class="row justify-content-center">
<form action="{{route('ablum.store')}}" method="POST" enctype="multipart/form-data">
#csrf
<input type="file" name="image" class="form-control">
<button class="btn btn-primary" type="submit">submit</button>
</form>
#foreach($images as $image)
<p> this is image name {{$image->name}}</p>
#endforeach
</div>
</div>
when I navigate to the home view I get this error
$images is undefined
Make the variable optional in the blade template. Replace {{ $images }} with {{ $images ?? '' }}
how can I solve this ?
You can try and rewrite your controller code like this:
return view('home')->with(compact('images'));
Official Laravel docs here does not say anything about any second parameters to view() helper.
with() should actually append the data and $images should be available in blade now.
Also, for simplicity, just use Image::all(). If this again is not working, you can try and ditch the compact method and in with() send an array like:
return view('home')->with(['images' => $images]);

how to update database using laravel controller? MethodNotAllowedHttpException No message error message

I'm trying to update my database using a form on my
edit.blade.php page as shown below. The edit part works correctly as the fields are filled in in the form as expected, however when i try to save, an error message of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
is displayed. I have tried so many ways on how to fix it and I'm not sure where I'm going wrong. Hopefully it's something simple to fix?
edit.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="post" action="{{ action('PostsController#update', $id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH" />
<h1>Edit Item</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="{{$post->item}}" class="form-control" required>
</div>
<div class="form-group">
<label for="weight">Weight (g):</label>
<input type="number" id="weight" value="{{$post->weight}}" name="weight" class="form-control">
</div>
<div class="form-group">
<label for="noofservings">No of Servings:</label>
<input type="number" id="noofservings" value="{{$post->noofservings}}" name="noofservings" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" value="{{$post->calories}}" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" value="{{$post->fat}}" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
#endsection
PostsController.php
<?php
public function update(Request $request, $id)
{
$this->validate('$request', [
'item' => 'required'
]);
$post = Post::find($id);
$post->item = $request->input('item');
$post->weight = $request->input('weight');
$post->noofservings = $request->input('noofservings');
$post->calories = $request->input('calories');
$post->fat = $request->input('fat');
$post->save();
return redirect('/foodlog');
}
web.php
<?php
Route::get('edit/{id}', 'PostsController#edit');
Route::put('/edit', 'PostsController#update');
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'id',
'user_id',
'item',
'weight',
'noofservings',
'calories',
'fat',
'created_at'
];
}
My website is a food log application and this function is so that they can edit their log.
Any help is greatly appreciated!
Based on Michael Czechowski I edited my answer to make this answer better, The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second problem is , the form method field is 'patch' and your route method is 'put'.
The difference between 'patch' and 'put' is:
put: gets the data and update the row and makes a new row in the database from the data that you want to update.
patch: just updates the row and it does not make a new row.
so if you want to just update the old row change the route method to patch.
or if you really want to put the data, just change the put method field in your form.
simply by : {{method_field('PUT')}}
Remember, the form's and the route's methods must be same. If the form's method is put, the route method must be put; and vice-versa.
The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second one is inside your HTML template:
<input type="hidden" name="_method" value="PUT" />
To hit the right route you have to add the corresponding method to your route Route::put('/edit/{id}', 'PostsController#update');.
A possible last problem
<form method="post" action="{{ action('PostsController#update', $post->id) }}">
I am not sure how your template works, but $id is possible not set inside your template. Maybe try to specify the ID depending on your post. Just to make it sure the ID comes from the shown post.
Further suggestions
Best practice is to use the symfony built-in FormBuilder. This would make it easier to target those special requests like PUT, PATCH, OPTIONS, DELETE etc.

Laravel - Method Not Allowed HTTP Exception (RouteCollection.php line 218)

I'm currently new on Laravel and trying to develop my first project. I have this MethodNotAllowedHttpException in RouteCollection.php line 218 error during my development for inserting data into database. I have searched both Google & Stackoverflow for solutions but non are related to my current problem and some of them way too complex for this simple problem (I think so...).
I have my form in my checklist page:-
<form action="{{url('addchecklist')}}" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-12">
<div class="text-left">
<input type="hidden" name="schmFK" value="{{$id}}">
<div class="col-sm-6">
<h4>
<label>Section</label>
<select class="selectpicker form-control" data-live-search="true" name="sctionPK">
<option selected>Select the Section</option>
#foreach ($sction as $key=>$slct1)
<option value="{{$slct1->ssctionPK}}">{{strtoupper($slct1->ssctionName)}}</option>
#endforeach
</select>
</h4>
</div>
<div class="col-sm-2">
<button type="button" data-toggle="modal" data-target=".bs-example-modal-lg" class="btn btn-primary btn-sm" style="margin-top:33px; padding-top:7px; padding-bottom:7px;">Add Section</button>
</div>
<div class="col-sm-4">
<h4>
<label>Severity</label>
<select class="selectpicker form-control" name="svrityPK">
<option selected>Select the Severity</option>
#foreach ($svrity as $key=>$slct2)
<option value="{{$slct2->severityPK}}">{{strtoupper($slct2->severityName)}}</option>
#endforeach
</select>
</h4>
</div>
<div class="col-sm-12">
<h4>
<label>Question</label>
<input class="form-control" type="text" placeholder="Question" name="question">
</h4>
</div>
<div class="col-sm-6">
#include('widgets.button', array('class'=>'primary btnaddstd', 'size'=>'lg', 'type'=>'submit', 'value'=>'Add Checklist'))
</div>
</div>
</div>
</div>
</form>
Then I have this route for inserting data from the form into database:-
Route::post('/addchecklist', function (Request $request){
// Create instance to store record
$scheme = new App\checklists;
$scheme->schmFK = $request->schmFK;
$scheme->schSectionFK = $request->sctionPK;
$scheme->severityFK = $request->svrityPK;
$scheme->clQuestion = $request->question;
$scheme->save(); // save the input
// Sort all records descending to retrieve the newest added record
$input = App\checklists::orderBy('cklistPK','desc')->first();
// Set search field variable default value of null
$src = isset($src) ? $src : null;
// Get Checklist reference from cklists_stddetails with the designated ID
$chkstd = App\Cklists_stddetail::where('cklistFK', $input->cklistPK)
->join('stddetails', 'stdDtlFK', '=', 'stddetails.sdtlPK')
->get();
// Get the newest stored record
$chcklst = App\checklists::where('cklistPK', $input->cklistPK)->firstOrFail();
// Get all data from table 'stddetails'
$stddetail = App\stddetails::all();
// Get all data from table 'standards'
$stndrd = App\standard::all();
// Get all data from table 'sections'
$sction = App\Section::all();
// Redirect to 'addref.blade' page with the newest added record
return redirect('addref/'.$input->cklistPK)
->with('src', $src)
->with('chkstd', $chkstd)
->with('id',$input->cklistPK)
->with('schmid', $request->schmFK)
->with('chcklst', $chcklst)
->with('stddetail', $stddetail)
->with('stndrd', $stndrd)
->with('sction', $sction);
});
My scenario is this, I have a form for user to input data in it. Then when the data is saved, they will be redirected to the page of that data to do something there. The data is successfully saved in the database but the redirection to the designated page (addref.blade) with the newest record ID return error:-
But the URL goes where I wanted it to go (means the URL is right):-
As you can see, the usual solution from the net that I found are:-
Make sure both method from routes and the form is the same, and mine it is:-
method="POST"
Route::post
Make sure the URL routes can recognize the form's action URL, and mine it is:-
<form action="{{url('addchecklist')}}" method="POST">
Route::post('/addchecklist', function (Request $request)
Include CSRF token field in the form, and mine it have been included:-
<form action="{{url('addchecklist')}}" method="POST">
{{ csrf_field() }}
I have tried those simple solution provided on the net and nothing is helpful enough. I'm still wondering what else I have missed and hoped that anyone here can assist on solving my issue.
I think the error is that you have a redirect which you have not registered in your routes or web.php file.
Sample redirect:
Route::post('/addchecklist', function (Request $request){
//some post process here...
return redirect('addref/'.$input->cklistPK)
->with('src', $src)
->with('chkstd', $chkstd)
->with('id',$input->cklistPK)
->with('schmid', $request->schmFK)
->with('chcklst', $chcklst)
->with('stddetail', $stddetail)
->with('stndrd', $stndrd)
->with('sction', $sction);
});
Route::get('addref/{id}', function(Request $request){
//show the blade.php with data
});
Can you please write :
url('/addchecklist')
instead of :
url('addchecklist')
and then print_r('in');
and die; and check what you get.
Route::post('/addchecklist', function (Request $request){
print_r('in');
die;
});

Passing variable from button to controller Laravel

I am having a little routing problem in Laravel 5.2. I have a result page which shows detailed information about personnel. I would like a button, which when enabled, generates a PDF page. Passing the variables has been a problem but I am very close now! I will public my code to elaborate.
result page
<form action="generatePDFpage" method="get">
<button type="submit" class="btn btn-default">Generate PDF!</button>
</form>
routes.php
Route::get('/dashboard/result/generatePDFpage', 'resultController#GeneratePDFc');
GeneratePDFc controller
public function GeneratePDFc(){
$id_array_implode = "HALLO";
$pdf= PDF::loadView('GeneratePDF', ["test"=>$id_array_implode])->setPaper('a4', 'landscape');
return $pdf->stream('invoice.pdf');
}
So, on the result page I am using a array ($id_array) to search the database for the matching records. I need to pass this variable onto the GeneratePDFc controller, so that I can pass that again to the loadView function!
Could someone please help me out? :-)
When you're using get method, you can do just this:
<a href="{{ route('route.name', $parameter) }}">
<button type="submit" class="btn btn-default">Generate PDF!</button>
</a>
For other methods you can use something like this (this one is for DELETE method):
<form method="POST" action="{{ route('route.name', $parameter) }}" accept-charset="UTF-8">
<input name="_method" type="hidden" value="DELETE">
{{ csrf_field() }}
<button type="submit" class="btn btn-sm btn-default">Generate PDF!</button>
<input type="hidden" value="someVariable" />
</form>
To get variable, use something like this:
public function generatePDF(Request $request)
{
$someVariable = $request->someVariable;
I don't know Laravel but I think when in your action="" of the form you can put your route with its parameters no ?
I've found it here : https://laravel.com/docs/4.2/html#opening-a-form
And access the variable in your controller using the $request var

Categories