How to modify request text in laravel - laravel-5

I can't think of a good title I'm so sorry but I need help.
I have a field that is added by jquery depending on how many questions are present in the database, so for example I have 3 questions in the db i will have 3 answer fields too, it will look like this:
answer_1
answer_2
answer_3
since i am not sure how many questions there can be, i need to loop the $request->answer_1, 2 and 3 in the controller to store the answers. but i'm not sure how to do it. I have tried:
for($i = 0; $i < total.count.of.answers; i++){
$x = $i + 1;
$answer = new Answer;
$answer->answer = $request->answer_{$x};
$answer->save();
}
but not working. How do I achieve this?
(note i can already send the answers to the backend using jquery, problem is only how i can pull it in the controller)

First, I'd group my inputs as such:
<form action="/submit" method="POST">
{{ csrf_field() }}
<input type="text" name="answers[]">
<input type="text" name="answers[]">
<input type="text" name="answers[]">
<button type="submit">Submit</button>
</form>
Then, in my controller, I would be able to loop through the answers by doing the following:
foreach($request->answers as $answer) {
Answer::create(['answer' => $answer]);
}
This is just an example, but you get the idea.

Laravel: save multiple records in database.
foreach($request->all as $value){
$answer = new Answer;
$answer->answer = $value->answer;
$answer->save();
}

Related

how to get filtered collection backpack laravel

I have a button that needs to pass a filtered collection from a table. Now when I click on the button, I get the entire collection
my button
$this->crud->addButtonFromView('top', 'withdrawDebtCompany', 'withdraw_debt', 'end');
button view
<form action="{{ url($crud->route.'/withdrawAllCompanyDebt') }}" method="POST">
<button class="btn btn-warning" data-style="zoom-in">
<span class="ladda-label">
{{ trans('columns.debt.allwithdraw') }}
</span>
</button>
{{ csrf_field() }}
</form>
method
public function withdrawDebtCompany()
{
$bills = $this->crud->query->get();
Bill::tryWithdrawalsIncrement($bills);
$res['success'] = 0;
$res['err'] = 0;
$bills->each(function($bill) use(&$res){
$paym = new PaymentsController();
$result = $paym->payDebt(new Request([
'bill_id'=>$bill->id,
]));
if($result['code'] == 0) {
$res['success'] += 1;
} else {
$res['err'] += 1;
}
});
\Alert::add('warning', 'Успешно списано: '.$res['success'].' | Неуспешно списано: '. $res['err'])->flash();
return redirect()->back();
}
I tried tracking the filtered collection in the button method, but that doesn't work. This is where the whole collection comes in. Filtered collection only comes after page reload
Hope to find you well.
In your <form> element you don't have any input to be POSTed, so I am wondering, why using a form there and not an <a> or similar.
I would advise you to have a look at the ListOperation https://github.com/Laravel-Backpack/CRUD/blob/main/src/app/Http/Controllers/Operations/ListOperation.php
There you will find the search endpoint that is used by datatables to get it's data.
You can apply a similar solution in your button endpoint to get the filtered results like in table.
Cheers

Laravel 8 multi value select filtering

I'm trying to build Laravel project that will have a multi-select dropdown with list of categories. Selecting category should reload the page and apply filter.
"scopeFilter" in my model is actually doing filtering, but here i just need to find a way to properly form URL. The problem is that this code i have:
<form id="cats-form" action="#" method="GET">
<select multiple class="chosen-select" name="test[]">
#foreach($categories->get() as $cat) //this loop goes through existing categories in the system
#php
//if category is part of URL, pre-select it in the select:
$arr = request()->all();
$selected = '';
if(array_key_exists('test', $arr)) {
$testArr = $arr['test'];
$selected = in_array($cat->id, explode(',', $testArr)) ? 'selected' : '';
}
#endphp
<option {{ $selected }} value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</form>
<script>
$(".chosen-select").chosen({ })
$('.chosen-select').on('change', function(evt, params) {
$('#cats-form').submit();
});
</script>
Is actually giving me this URL:
http://localhost:11089/?test%5B%5D=19&test%5B%5D=5
While i actually need this:
http://localhost:11089/?test=19,5
I guess it's a trivial problem to solve for someone with better knowledge of Laravel, can you tell me pls what i'm doing wrong here?
This is rather how the language or framework or library reads an URL query string. Assuming that your prefered way of URL string is a valid format (as I usually see the format ?arr[]=val1&arr[]=val2 and never see the second format that you preferred), both query string formats should be acceptable to PHP.
As Yarin stated that the best way PHP reads an array is the first method, you don't have to worry too much because the decoded URL query string is exactly in the first format.

Laravel Photo Upload using LaravelCollective

When I try to submit the form an Error occurs.
public function store(){
$story = new Story;
$story->file_link = $request->resume_link;
$story->save();
$fileName = $story->id . '.' .
$request->file('file_link')->getClientOriginalExtension();
$requests->file('file_link')->move(
base_path() . '/public/uploads', $fileName
);
$story->file_link = $fileName;
return redirect('home');
}
What this does is mainly to store the file i uploaded. Please upvote this post. I am banned due to this question. Thanks
To be more precise, Laravel Collective is really a collection of packages that are removed from Laravel core. I am assuming you are talking about the HTML/Forms package. To answer your question, I think the docs are self-explanatory enough.
To generate a file input (front end)
{{ Form::file('image') }}
To "retrieve" the file (back end controller)
$file = $request->file('image');
You need to be more precise on your question. What are you confused about?
I think this might solve your problem.
Your blade template code will be
<div class="form-group">
<label for="image">Chose the picture</label>
<input type="file" class="form-control" name="image" id="image" {{ $errors->has('image') ? 'class=has-error' : '' }} value="{{ $photo->image }}">
</div>
Your Controller code will be
$logo=$request->file('image');
$upload='uploads/logo';
$filename=$logo->getClientOriginalName();
$success=$logo->move($upload,$filename);
$doctor->image = $filename;

Keeping select values across pages

I have a couple of routes
Route::get('/route_one', 'IndexController#index');
Route::get('/route_two', 'IndexController#index');
They call the same controller function because these pages need the same array of data. This function is as follows
public function index()
{
$user = Auth::user();
if( $user ) {
$fileData = $this->fillArrayWithFileNodes(new DirectoryIterator( public_path(). '/images'));
$currentPath= Route::getFacadeRoot()->current()->uri();
if(!empty($fileData)) {
return view('index', compact('fileData', 'currentPath'));
}
} else {
return view('auth.login');
}
}
Now the index view is pretty straight forward, but it does has this part
#if($currentPath == 'route_one')
#include('layouts.searchbarRouteOne')
#endif
#if($currentPath == 'route_two')
#include('layouts.searchbarRouteTwo')
#endif
So depending on what route is called, a different sidebar is displayed. Now the sidebars essentially contain a load of select inputs like the following
<div class="col-lg-3">
<div class="form-group">
<label>Year</label>
<select id="year" class="form-control">
<option value=""></option>
#foreach($fileData["route_one"] as $year => $products)
<option value="{{ $year }}">{{ $year }}</option>
#endforeach
</select>
</div>
</div>
Both sidebars have different selects. When select options are selected, an ajax call is made to display an image. This all works fine.
This is my problem. I have a link to get to route_one or route_two. As the page refreshes when the link is clicked, the selects are at their default state. What I would like to do somehow is keep the last state of the select inputs. I am not storing this data within a database which may be an issue?
Furthermore, route_two relies on the select options from route_one. So when route_two is selected, I need to pass it route_ones options.
What would be the best way to achieve what I am after?
Thanks
Think what you are trying to accomplish here: remember the old input values.
You could send the form when clicking the link and flash the data in your controller or use JavaScript saving input values to the browser's storage.
Simple example using plain JavaScript
// Get all select-elements
var inputs = document.querySelectorAll('select');
// Loop through them
for (var i = 0; i < inputs.length; i++) {
// Set the old input value
inputs[i].value = localStorage.getItem(inputs[i].name);
// Start listening changes
inputs[i].addEventListener('change', store);
}
// The function to call when the value has changed
function store(event) {
// Set the new value to the browser's storage
localStorage.setItem(event.target.name, event.target.value);
}
In that example your form elements are required to have unique name attributes. Of course it can be switched out using e.g. id attribute.

Add Checkbox to database in Laravel 5

Im not 100% great in html and databases but I'm getting there. What I did works but not when I'm editing a page that has checkboxes.
In my database migration:
$table->string('check_this')->nullable();
In views:
<div class="checkbox">
#if ($job->check_this == 'selected')
<label><input type="checkbox" name="check_this" value="selected" checked>Yes.</label>
#else
<label><input type="checkbox" name="check_this" value="selected">Yes.</label>
#endif
</div>
Once the checkbox is checked, it writes to the db so my if statement wont work correctly. Is there a way that if unchecked it deletes the value from the database?
Maybe I have go about this is the wrong way as in the correct format for checkboxes in a migration.
Your migration should looks like this:
$table->boolean('check_this');
and the view part:
#if ($job->check_this)
See: http://laravel.com/docs/master/schema#adding-columns for all avail types of 'columns' in Laravel.
Checkbox don't send nothing if is not cheched so the database will not update unless you check in controller and if "check_this" is not set in your request set this to 0 on database.
$obj = Obj::find($id); //get your object from database
$input = Request::all(); //or $request->all() if you use requests
if(!isset($input['check_this'])){
$input['check_this'] = 0; //or whatever you want
}
$obj->fill($input);
$obj->save();
Note:
You can simplify your view
<div class="checkbox">
<label><input type="checkbox" name="check_this" value="selected" #if ($job->check_this == 'selected') checked #endif>Yes.</label>
</div>
And of course the answer about using boolean for this field will optimize your database if you don't need this specific string.

Resources