Access inputs from separate forms in Laravel using form collective - laravel

I am very new to Laravel. On my blade I have to forms, First has 11 checkboxes and save button. Basically a user comes to check inputs he needed and clicks save, which takes to controller and stores the values. Now, I have 'accept' button which is completely separate function in controller, but I still need the values from input fields. How would I pass the values from different form.
Example:
{{ Form::checkbox('shopping['.$current->id.']', true, $shopping_cart->getPresence($current->id), ['disabled']) }}
{!! Form::button('<i class="fas fa-btn fa-save"></i>Save', ['type' => 'submit', 'class' => 'btn btn-primary']) !!}
</div>
#endif
{!! Form::close() !!}
{!! Form::model($shipping, [ 'method' => 'POST', 'action' => ['Shopping#storeAcceptShipping', $shopping->id]]) !!}
{!! Form::close !!}

You must use hidden fields y another form. When you send the first form, get in Controller with a standard request and serialize the data like:
$data_form1_serialized = serialize($request->all());
after return the view with this serialized data
return view('form2',compact("data_form1_serialized");
In view form2 make a hidden input with value $data_form1_serialized
{!! Form::model($shipping, [ 'method' => 'POST', 'action' => ['Shopping#storeAcceptShipping', $shopping->id]]) !!}
{!! Form::hidden('data_form1', $data_form1_serialized) !!}
{!! Form::close !!}
OR
Use Vue or(something JS) display a form with tabs o a form step by step, and when all the form is complete part1, part2 etc. Send to Controller. This is for me the right way.

Related

Laravel Form Model binding not showing data

I am trying to build a site and I get to the point where I would like to exploit the Form model binding
I set in the boot method of the RouteServiceProvider the binding between 'material' and 'App\Material' class
This is the creation Form:
{!! Form::open(array('url'=>'material', 'files' => true, 'class' => 'form-horizontal')) !!}
#include('admin_panel.partials.material_form',['submitButtonText' => 'Add'])
{!! Form::close() !!}
This is the include file:
{!! Form::label('title','Title',array('class' => 'control-label col-sm-2')) !!}
{!! Form::text('title','',array('class' => 'form-control')) !!}
{!! Form::label('published_at', 'Ready on:') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
{!! Form::label('file','Choose the material: ',array('class' => 'col-sm-2')) !!}
{!! Form::file('file') !!}
{!! Form::submit($submitButtonText, array('class' => 'btn btn-warning')) !!}
The operation of creating the material and save it to the db works perfectly.
When i want to edit a material before calling the edit view in the edit method of the MaterialController I use dd($material) to check if it is the correct object. The attributes (title, published_at,...) in the object on the screen are the correct one, so I am sure that the object I am passing to the edit view is the right one.
When i call the Edit View I print {!! $material->title !!} before the Form and the string is correct. This is the Form:
{!! Form::model($material, array('method' => 'PATCH', 'route'=>array('material.update', $material), 'files' => true, 'class' => 'form-horizontal')) !!}
#include('admin_panel.partials.material_form',['submitButtonText' => 'Update']);
{!! Form::close() !!}
The problem is that i don't see anything in the fields of the form...
I don't know where I made a mistake.
Thank you.
Well I made a stupid mistake.
In the Form::text (and I think also the other fields) of the include form I forced the second argument (the text displaying in the input text form to be empty instead of NULL, thus overriding the value of the bind model.
my mistake.

Laravel detach Pivot tables

I'm new with Laravel and I'm having problems while I try to detach some values from my pivot tables.
The pivot tables I'm woking with are:
excercise_workout (ejercicio_rutina) & excise_day (ejercicio_dia) (those tables have just two id's each one). The relations are ManyToMany. A workout have a lot of days and a day have a lot of excercises.
I've created these routes:
Route::resource('rutinas','RutinasController');
Route::delete('rutinas.destroyEjercicio/{id}','RutinasController#destroyEjercicio');
I have this button that is a form and call the delete:
{!! Form::open([
'method' => 'DELETE',
'action' => [ 'RutinasController#destroyEjercicio', $ejercicio->id ]
]) !!}
{!! Form::submit('Borrar Ejercicio', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
The destroyEjercicio is the part I don't know how to hadle with:
public function destroyEjercicio($id)
{
$ejercicio = Ejercicio::findOrFail($id);
dias()->$ejercicio->detach($id);
//EXAMPLE DELETE WITH QUERY
// DB::delete('delete from toy_user where toy_id = ? AND user_id = ? AND status = 0', array($toy->id,Auth::id()));
return redirect('rutinas');
}
I recieve this error when I try to submit the delete form:
Call to undefined function App\Http\Controllers\dias()
I've tried a lot of other methods but I don't know how to do it.
I need to know the ID of the day and the ID of the excercise I want to delete. And I don't know how the past it by the post request.
UPDATE -> THIS IS THE FORM I DO NOT HAVE INPUTS TO REQUEST...
#foreach ($rutina->dias as $dia)
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
Ejercicios para el <strong>{{ $dia->nombre }}</strong>
<hr>
#foreach ($dia->ejercicios as $ejercicio)
<ul>
<li>{{ $ejercicio->nombre }}</li>
</ul>
{!! Form::open([
'method' => 'DELETE',
'action' => [ 'RutinasController#destroyEjercicio', $ejercicio->id ]
]) !!}
{!! Form::submit('Borrar Ejercicio', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
#endforeach
</div>
</div>
</div>
#endforeach
You need something like this:
public function destroyEjercicio($ejercicioId, $diasId)
{
$ejercicio = Ejercicio::findOrFail($ejercicioId);
$ejercicio->dias()->detach($diasId);
https://laravel.com/docs/5.1/eloquent-relationships#inserting-many-to-many-relationships
Update
How to use Request object. If you're using forms, Reuqest object will contain all form fields. Just do something like this:
public function destroyEjercicio(Request $request)
{
$ejercicioId = $request->get('ejercicioIdField');
$diasId = $request->get('diasIdField');
I solved this the following way. First I create this new route:
Route::post('rutinas.destroyEjercicio/{ejercicioId}/{diaId}', [
'as' => 'destroy',
'uses' => 'RutinasController#destroyEjercicio'
]);
You must add this array at the form:
{!! Form::open([
'method' => 'POST',
*******'route' => ['destroy', $ejercicio->id, $dia->id]******
]) !!}
{!! Form::submit('Borrar Ejercicio', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
Then in your controller you pass the two id's that you need:
public function destroyEjercicio($ejercicioId, $diaId)
{
$ejercicio = Ejercicio::findOrFail($ejercicioId);
$ejercicio->dias()->detach($diaId);
return redirect('rutinas');
}

Putting image as submit button Laravel

I can't seem to find a way to put image as submit button in blade, is there a way to do this?
{!! Form::submit('Search', array('class'=>'btn')) !!}
Form::input should do the trick:
{!! Form::input('image', 'Search', array('class'=>'btn', 'src' => '...')) !!}
You can create the submit with pure html instead of laravelcollective like that
<input type="image" src="sourse for image" width="48" height="48" alt="Submit" />
For Laravel Collective version 6.2 the solution This small example shows the sending of a variable by means of a button with an image (src='../path/to/file) using the 'submit' passing as parameters the dimensions of the button (30,30).
Note: var_to_send can have a string like $ansver - > 'Hello World' or another value and it will pass it from the controller and it will print it.
// new.blade.php
{!! Form::open([ 'action'=> 'StorageController#save', 'method' => 'POST', 'files' => true]) !!}
{!! Form::hidden('var_to_send', $answer) !!}
{!! Form::image(url('../img/A.png'), 'submit', ['width' => '30', 'height' => '30']) !!}
{!! Form::close() !!}
// StorageController.php
class StorageController extends Controller
{
public function save(Request $request)
{
return $request->input('var_to_send');
}
}
// route wep.php
Route::post('storage/create', 'StorageController#save');

How to use Dropzone in Laravel 5 with existing form and submit everything by pressing a button

I have:
{!! Form::open(['route'=>'admin.some.store', 'method' => 'post', 'id' => 'creation-form']) !!}
{!! Form::text('name', null, ['class' => 'form-control', 'id'=>'name']) !!}
{!! Form::text('name1', null, ['class' => 'form-control', 'id'=>'name1']) !!}
{!! Form::button('Submit', ['class' => 'btn btn-primary', 'type'=>'submit']) !!}
{!! Form::close() !!}
I need to to use dropzone.js with such a form. I need to submit all the data of my form and images to the same controller at once. How can I do it. I discovered other questions and documentation, but I faced with some problems (for example, previews are displayed unstyled, when I am not using dropzone class. This class is not only id which automatically starts the plugin but also important element of styling, programmatical activation, etc). Dropzone has very unlogic documentation.
There's a couple ways about this. Presumably, your current form Model (lets call it Element) has at least a one to many relationship with the images, if not many-to-many.
I generally solve this by processing the uploads normally (as they're dropped in the Dropzone) and appending the returned IDs to my main Form
Create your Laravel form as usual:
{!! Form::open(['method' => 'POST', 'route' => ['some.route.name'], 'class' => 'myForm') !!}
// various fields...
{!! Form::close() !!}
Create your Dropzone form area:
{!! Form::open(['route' => ['some.route.location'], 'class' => 'dropzone', 'files' => true]) !!}
{!! Form::close() !!}
Then add the Javacript for your Dropzone intsance:
$(document).ready(function() {
Dropzone.options.myUploadForm = {
success: function(event, response) {
$('.myForm').append("<input type='hidden' name='image_ids[]' value='"+response.photo_id+"' />");
}
};
});
Then, your main form submits to your Controller Method as normal, at which point you can loop through the image_ids array and pass them to their own method which associates them with your model:
public function storeSomething(Request $request)
{
$new_element = $this->element->create($request->all());
// depending on the type of relationship, you can now use the
// IDs to update your Photos
$new_element->associateWithImages($request->input('image_ids'));
}
The disadvantage with this approach is that the User may upload images but fail to complete the form, in which case, you may end up with a handful of 'orphaned' images. However, this could be handled with a Cron job which deletes orphaned images periodically.
Otherwise, you can attempt to upload everything in one go using some of the Dropzone configuration options. You'll need to queue up the images that are dropped in the Dropzone, and manually process the Queue once your main form is submitted. Take a look here

How to set a default value for a form partial variable in Laravel

I am implementing a simple controller for a mini-project of mine. For the simplicity of this question, only two views matter: the create song, and edit song views. Both of these views contain the same form fields, so I created a form partial called _form.
Since the forms have different purposes - despite having the same fields - I pass on to the partial a couple of variables to specify the value of the submit button label, and the cancel button route.
For example:
edit.blade.php:
(...)
{!! Form::model($song, ['route' => ['songs.update', $song->slug], 'method' => 'PATCH']) !!}
#include('songs._form', [
'submitButtonLabel' => 'Update',
'returnRoute' => 'song_path',
'params' => [$song->slug]
])
{!! Form::close() !!}
(...)
create.blade.php:
(...)
{!! Form::open(['route' => 'songs.store']) !!}
#include('songs._form', [
'submitButtonLabel' => 'Save',
'returnRoute' => 'songs_path'
])
{!! Form::close() !!}
(...)
And here is the _form.blade.php partial:
(...)
<div class="form-group">
{!! Form::submit($submitButtonLabel, ['class' => 'btn btn-success']) !!}
{!! link_to_route($returnRoute, 'Cancel', isset($params) ? $params : [], ['class' => 'btn btn-default', 'role' => 'button']) !!}
</div>
Now, my question is (finally):
As you can see, in the Cancel button of my form partial, I am using isset($params) ? $params : [] to default the $params variable to [] when it is not set.
Is there a better way to do this? Here, under Echoing Data After Checking For Existence, Laravel supports this alternative echo: {{ $name or 'Default' }}, but this does not work since I am trying to use it inside a {!! !!} block already...
So, is the ternary operator using the isset() function the best solution for this case? (The one I am currently using)
You can simply pass the variable $params an empty array ([]) in create.blade.php and remove the condition on your partial.
Then you can set the default value on your .blade files
As an alternative you can set a default value on your controller and send it as $params if they are not set (your slug).
Hope it helps

Resources