Laravel Livewire dynamically creating properties in a component - php

Is it possible to dynamically create properties in a livewire component for "model wiring" radio inputs, using foreach loop in mount method? I keep getting error (property not found on the component).
component:
component
view:
view

set the wire model correctly
don't set value. The value comes from the component. Use dotted notation
<label><div><input type="radio" wire:model="ksb.{{$key}}"></div>learning</label>

<div class="row">
<label for="Contact" class="col-form-label">learning</label>
<input type="text" wire:model="ksb.{{ $key}}.learning" class="form-control" placeholder="learning">
<label for="Contact" class="col-form-label">skills</label>
<input type="text" wire:model="ksb.{{ $key}}.skills" class="form-control" placeholder="skills">
<button wire:click="NextStep('{{ $key }}')">Next Step</button>
</div>
In Component Use This
public function NextStep($key)
{
$this->ksb[$key]['learning'] = '';
}

Related

Laravel 5 form does not redirect with old input

I'm validating laravel forms and old input does not preserve after validation fail.
I'm using laravel 5.8 form request validation and html input fields are filled with default values :
public function store(ProyectoRequest $request){
$input = $request->validated();
DB::transaction(function () use($input) {
$proyecto = new Proyecto();
$proyecto->fill($input);
$proyecto->save();
});
return redirect(route('proyectos.index'));
}
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" class="form-control input-lg" value="{{$proyecto_nombre}}" name="nombre">
</div>
When the form is validated the page reloads with the default values. I expect that input fields values are preserved. That is what I have understood from the documentation.
I am looking for the docs and there is not written if this is the normal behaviour or not.
Anyway you can do yourself with this code:
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" class="form-control input-lg" value="{{ old('proyecto_nombre', $proyecto_nombre) }}" name="nombre">
</div>
In laravel the old function retrieves input fields.

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.

How to get value of input in blade.php

I need to get a value of input to use below, how to do that?
I tried to like this but error says
Undefined variable: name
<div class="col-md-10 col-md-offset-1">
<input id="name" type="text" name="name" />
</div>
<div class="col-md-10 col-md-offset-1">
#php
$nameValue=$_GET['name'];
#endphp
<input id="name2" type="text" name="name2" value="{{$nameValue}}" />
</div>
$nameValue=Request::input('name')
From the blade template you can access the request parameters with the Request facade, you can also print it directly:
{{Request::input('name')}}
In latest versions you can also use:
{{request()->input('name')}}
You have to be aware that your input-values (here "name") ist only available after submitting the form.
If you want to access the form-values before submitting you should take a look at VueJS or any other frontend-framework (React, Angular). Or simply use jQuery.
Therefor you have to use JavaScript if you want to use the input-value before submitting.
Like the others said in the comments, you can access your form-values within your controller and then pass it to your view.
For example (from the documentation):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function formSubmit(Request $request)
{
$name = $request->input('name');
return view('form', ['name' => $name])
}
}
Now you can use the value within your view:
<input id="name2" type="text" name="name2" value="{{$name}}">
Another possibility would be to "by-pass" your controller and return your view directly from your routes.php:
Route::get('/form-submit', function(){
return view('form');
});
But I'm not sure if this is working and you could access $_GET/$_PSOT directly without using Laravels Request.
You can get inputs array from Request class:
Request::all()['your_input']
Also you can check if that input you want is exists not:
#isset(Request::all()['your_input'])
{{-- your input existed --}}
#else
{{-- your input does not existed --}}
#endisset

How could i add attribute in database with different languages

/*controller_ problem is that always add the some attribute for the different languages */
`
if ($request->isMethod('POST') && null !== ($request->request->get('ajouter')))` {
$pack = new Packs();
$pack->setPackPrice($request->request->get('pack_price'));
$pack->setDataCreated(new \DateTime('now'));
$pack->setDataStatus($request->request->get('data_status'));
foreach ($listLanguages as $language) {
$packLanguage = new Packs2lng();
$packLanguage->setLanguage($language);
$packLanguage->setPack($pack);
$packLanguage->setPack2lngWording($request->request->get('pack_2lng_wording'));
$packLanguage->setPack2lngDescription($request->request->get('pack_2lng_description'));
$em->persist($packLanguage);
}
//view_ I think that my input request must be variable
{% for i in listLanguages %}
<div class="form-group">
<label class="control-label col-md-3">Titre </label>
<div class="col-md-4">
<input type="text" name="pack_2lng_wording" data-required="1" class="form-control" value="{% if packLanguage.pack2lngWording is defined%}{{packLanguage.pack2lngWording}} {%endif%}"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Description </label>
<textarea cols="60" rows="5" class="span4" name="pack_2lng_description">
{% if packLanguage.pack2lngDescription is defined%}{{packLanguage.pack2lngDescription}} {%endif%}</textarea>
</div>
{%endfor%}
Let's say the users enters a French and English translation. With your current view, the post request would be this:
pack_2lng_wording=foo_FR
pack_2lng_description=bar_FR
pack_2lng_wording=foo_EN
pack_2lng_description=bar_EN
That won't work, because the first pack_2lng_wording would be overridden by the second.
To prevent it, you have to add [] to your name attribute of an input:
<input type="text" name="pack_2lng_wording[]" />
Or add {{ i.code }} to get a associative array (assuming that each Language has a language code, i.e. a ISO 639-1 code) :
<input type="text" name="pack_2lng_wording['{{ i.code }}']" />
That would lead to this post request:
pack_2lng_wording[FR]=foo_FR
pack_2lng_wording[EN]=foo_EN
pack_2lng_description[FR]=bar_FR
pack_2lng_description[EN]=bar_EN
In your controller you have to add [$language]:
foreach ($listLanguages as $language) {
$packLanguage = new Packs2lng();
$packLanguage->setLanguage($language);
$packLanguage->setPack($pack);
$packLanguage->setPack2lngWording($request->request->get('pack_2lng_wording')[$language->getCode()]);
$packLanguage->setPack2lngDescription($request->request->get('pack_2lng_description')[$language->getCode()]);
}
BTW: I would highly recommend to use Symfony Forms. You are now reinventing the wheel. That's OK if you want to learn, but it will make your life easier (and your application) better if you are using components that are well documented, well maintained, etc.

How to show the old data in a form input in the Laravel

I write the form.blade.php like this:
<div class="form-group">
<label>Start at</label>
<div id="start_date" class="input-group date form_datetime col-md-4" data-date-format="yyyy-mm-dd hh:ii:ss">
<input class="form-control" name="start_at" size="16" type="text" value="{{ $activity->start_at }}">
<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
</div>
</div>
Both Create and Edit method use the view to display the form. In the Edit method, the $activity is used and everything is normal. But in the Create method, the $activity is null, so I have a error in {{ $activity->start_at }}.
I know I can use if(!empty($activity)) to prevent this error. but I do not want to use this anywhere.
What is the better way?
You could use this,
{{ $activity->start_at or '' }}
I also like to reuse code and use the same view to create or edit an object. What I do is to pass a brand new instance of the object to the create view. This way I have the object on its initial state including defaults (if any) and I am able to prefill those defaults (if any) on the displayed form. It gives me an additional benefit: if anything goes wrong with the validation at the server level the user doesn't lose any data, I just need to do something like this in the view:
<div class="form-group">
<label for="test_field" class="control-label">Fecha de firma</label>
<input type="text" value="{{ ( !empty($isabi) ? $isabi->fecha_firma : old('fecha_firma')) }}"
name="fecha_firma" id="isabi-fechafirma" class="form-control" placeholder="Este campo es obligatorio">
</div>
This is the create method with extra functionality removed for clarity (check if the user is authenticated, linking the created object with the company the user works for and other stuff):
public function create()
{
return view('isabis.create', [
"isabi" => new Isabi()
])->with($this->data);
}
I use $this->data for view configuration. Hope this helps.

Categories