How to get specific value/name using dimsav/laravel-translatable package - laravel

I have followed the doc. I created two tables:
countries
country_translations.
Now I changed the column name => key and value cause I can get the value (lang text) by query key.
Say for example :
$r = 'DE';//App::getLocale(); // 'fr'
$germany = Country::where('code', $r)->first();
// I want to get value where key= 'contacts-last-name'
$translation = $germany->translate($r, true)->where('key', 'contacts-last-name')->value;
print_r($translation);
exit("----");
I get:
ERROR: Undefined property
How may I get specific value using new query/sub query (key).
For an Example here is my method and view
Updated the method as below ::
$translation = $germany->translate($r, true)->where('key', 'contacts-last-name')->first();
echo "<pre>"; print_r($translation->toArray()); exit("----");
and got the answer:
Array
(
[id] => 1
[country_id] => 83
[key] => contacts-last-name
[value] => Achternaam
[locale] => DE
)
In view Page I have a form :
<label class="col-sm-2 control-label">{{trans('labels.contacts-first-name')}}</label>
<div class="col-sm-4">
<input name="first_name" id="first_name" type="text" class="form-control" required disabled>
</div>
<label class="col-sm-2 control-label">{{trans('labels.contacts-last-name')}}</label>
<div class="col-sm-4">
<input type="text" id="last_name" name="last_name" class="form-control" disabled>
</div>
for this one I have a question how may I pass translate data and make transable views all the time {{trans('labels.contacts-last-name')}}

You can access it like so:
$translation = $germany->{'contacts-last-name:'.$r};
https://github.com/dimsav/laravel-translatable/blob/master/src/Translatable/Translatable.php#L153

After
echo "<pre>"; print_r($translation->toArray()); exit("----");
Result:
Array
(
[id] => 1
[country_id] => 83
[key] => contacts-last-name
[value] => Achternaam
[locale] => DE
)

change your this line
$translation = $germany->translate($r, true)->where('key', 'contacts-last-name')->value;
to this, and then try it
$translation = $germany->translate($r, true)->where('key', 'contacts-last-name')->get();
print_r($translation);
exit("----");
Updated
in your view, {{trans('labels.contacts-last-name')}} this way means that you are trying to grab translation from your lang directory exists in your project, in actual this is manual file based/array (key/pair) way.
while you want Dynamic/DB based, you can do this
pass you $translation variable into your view, eg
return view('form-view', compact('translation'));
and then in your view you can do this.
<label class="col-sm-2 control-label">{{$translation[0]->value}}</label>
<div class="col-sm-4">
<input name="first_name" id="first_name" type="text" class="form-control" required disabled>
</div>
<label class="col-sm-2 control-label">{{$translation[1]->value}}</label>
<div class="col-sm-4">
<input type="text" id="last_name" name="last_name" class="form-control" disabled>
</div>

Related

How can i show data from my controller in a textbox?

Hi i calculated a discount in my controller by requesting in a form the percentage and the sale_price, so i did this:
public function store(Request $request){
dd($request->all());
$presupuestoProducto = new PresupuestoProducto();
$presupuestoProducto->sale_price = $request->sale_price;
$presupuestoProducto->discount_percentage = $request->discount_percentage;
$presupuestoProducto->discount = ($sale_price * $discount_percentage)/100;
$presupuestoProducto->save();
Session::flash('success');
return redirect()->route('presupuestos-productos.view');
}
But now i want to make the result of $presupuestoProducto->discount to appear in a textbox. So it would be like an autocomplete field. So up to now i have it this way in my view.
<div class="form-group col-md-2">
<label for="sale_price">Precio de Venta</label>
<input type="number" pattern="[0-9]+([\.,][0-9]+)?" step="00.01" name="sale_price" class="form-control">
</div>
<div class="form-group col-md-3">
<label for="discount_percentage">Porcentaje de descuento (%)</label>
<input type="number" name="discount_percentage" class="form-control">
</div>
<div class="form-group col-md-3">
<label for="discount">Descuento</label>
<input type="number" name="discount" class="form-control" value="discount">
</div>
As you can see my last div is an input but i want it to be a text box that automatically appears the result of $presupuestoProducto->discount as i fill in the first two inputs. How should i do this?
you have to use view() and pass the $presupuestoProducto with compact() then you access to the var in your view with it's name
$presupuestoProducto->save();
return view("ProductView",compact( 'presupuestoProducto'))
in view : ProductView
<div class="form-group col-md-3">
<label for="discount">Descuento</label>
<input type="number" name="discount" placeholder="discount" class="form-control" value={{$presupuestoProducto->discount}} >
</div>
but if you wanna use route you can try route parameter

Laravel - Redirect users back to another form with all data intact, on clicking Previous button

I have two forms as below
Form 1
<form id="form1" action="loc1" method="post">
<div class="form-group">
<label for="exampleDOB">Date of Brth:</label>
<input type="text" class="form-control" id="dob" name="dob" placeholder="Date of Birth"
value="{{$tuser->DOB ?? ''}}" >
<div class="error text-danger"></div>
</div>
<button type="submit">Next Step</button><br><br>
<button type="button">Previous </button>
</form>
Form 2
<form id="form2" action="loc2" method="post">
<div class="form-group">
<label for="exampleMob">Mobile Number:</label>
<input type="text" class="form-control" id="mobno" name="mobno" placeholder="Valid Mobile
Number" value="{{$tuser->mobno ?? ''}}" >
<div class="error text-danger"></div>
</div>
<button type="submit">Final Step</button><br><br>
<button type="button">Previous </button>
</form>
$tuser is an object containing all the data for that user, from the database
When users click on Next Step in Form 1, the data is stored in database and the user is directed to Form 2.
But the problem is- on clicking the Previous button, I am losing all the pre-filled data in the Previous form. How can I retain form data (to be shown in the input fields as available in the database)?
if you have saved them in DB, so you can retrieve all of it using an id and store it in session like:
session->put("form_1_id",$DBInsertedId);
in form 1 you can check if there are any results, you can retrieve it like:
if(session->has("form_1_id"))
return view('form_1',['filled_data' => Model::find(session->get("form_1_id")) ]);
and in the view you can check for parameter existence form_1_id like you did:
<input type="text" class="form-control" id="dob" name="dob" placeholder="Date of Birth"
value="{{$filled_data->DOB ?? ''}}" >
just add a filled name id in your input view and fill it if form has been filled out before. since doing this can assure you that the filled form will be updated if there was a record for it before:
<input type="hidden" id="id" name="id" value="{{$filled_data->id ?? ''}}" >
and in your controller:
Model::insertOrUpdate(['id' => $request->id ], ... );
UPDATE:
insertOrUpdate Equivalent in psudo-code :
if(DB::exist(['id' => $request->id]))
update(['id' => $request->id , ... ]);
else
insert([ ... ]);

Input checkbox with multiple value on laravel

I'm making input using the checkbox, only hardware table need to input multiple checkbox values
When im trying using implode, i got appear errorException: "implode(): Invalid arguments passed".
Here my controller code :
auth()->user()->Form()->create
([
'user_id' => $request->user_id,
'os' => $request->os,
'hardware' => implode(',', $request->input('hardware')),
// $arrayToString = implode(',', $request->input('hardware'));
'software' => $request->software,
'signature' => $signature,
'status_desc' => $request->status_desc,
'cancel_deskripsi' => $request->cancel_deskripsi
]);
dd($form);
return redirect()->route('form')->with('status', 'success');
My view code:
<div class="form-group col-md-12">
<label>Hardware :</label>
<div class="checkbox-list">
<label class="form-group col-md-4">
<input type="checkbox" id="hardware" name="hardware[]" value="Komputer AIO">
<span></span>
Komputer AIO
</label>
<label class="form-group col-md-4">
<input type="checkbox" class="form-group" id="hardware" name="hardware" value="Laptop">
<span></span>
Laptop
</label>
<input id="other" name="how" type="checkbox" class="form-group">
<label for="other" class="form-group">Other :</label>
<div class="other-disclosure">
<input type="text" name="hardware" id="os-other" class="form-group col-md-2" placeholder="...">
</div>
</div>
How to solve this problem ?
You probably want to have all those inputs named hardware[] (so they will all end up in an array as the input hardware) and incase nothing is passed (unchecked checkboxes) you should make sure to handle this:
'hardware' => implode(',', (array) $request->input('hardware', []));
Here if nothing is passed then $request->input('hardware', []) is [], an array. The (array) cast is just to make sure there is an array being passed to implode.

Radio button in my laravel 5.4 cannot be read by request

All of the other request in my view is included already in the request using
dd($request), but my radio button input is cannot be read by request.
attached here is my code
View
<form method="post" action="{{route('update-dependent')}}">
<div class="form-group">
{{csrf_field()}}
<div class="form-group">
<label>Last Name</label>
<input type="text" name="lname" value="{{$dependent->lname}}" class="form-control">
</div>
<div class="form-group">
{{-- conditional statement to check what geneder --}}
<input type="hidden" name="gender" value="bading" class="form-control">
<label>Male</label>
<input type="radio" name="gender" value="male" class="form-control">
<label>Female</label>
<input type="radio" name="gender" value="female" class="form-control">
</div>
<div class="form-group">
<label>Relationship</label>
<input type="text" name="relationship" value="{{$dependent->relationship}}" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
Controller
HMO::UpdateDependent($request);
return redirect()->route('edit', request('hmo_id'));
Model
public static function updateDependent($request)
{
DB::table('hmos_detail')
->where('id', $request->get('dependent_id'))
->update([ 'lname' => $request->get('lname'),
'gender' => $request->get('gender'),
'relationship' => $request->get('relationship'),
return true;
}
result
array:2 [▼
"_token" => "sP9FVEbL3pI5Yaf2jlSfDATNtOTSz2Rheb4bH9Ti"
"lname" => "test"
"relationship" => "WIFE"
]
First of all if you want value of radio then make sure you have proper validation in place.
If you don't know how to validate then have a look at following link
https://laravel.com/docs/5.5/validation#validation-quickstart
Furthermore
If you want some default value for radio button then make sure you have a hidden field that will have default value is this case you dont need validation.
So the basic example would be
<input type="hidden" name="gender" value="bading" class="form-control">
The radio btn will always have bading as default weather its selected or not. But If you add
<input type="radio" name="gender" value="male" class="form-control">
<input type="radio" name="gender" value="female" class="form-control">
Then the hidden field is replaced with the selected value.
As #Sree mentioned, You need to give gender to the fillable.
protected $fillable = ['gender', ....];
As from the documentation :
Mass Assignment You may also use the create method to save a new model
in a single line. The inserted model instance will be returned to you
from the method. However, before doing so, you will need to specify
either a fillable or guarded attribute on the model, as all Eloquent
models protect against mass-assignment by default.
It might be because you forgot to add gender in your Mass Assignment. In your model add,
protected $fillable = ['gender', ....];

PhpUnit testing, how to check a checkbox if there are multiple checkboxes with same name in a form

I am testing a form. In the form, there are some checkboxes which are with the same name as there are multiple checkboxes to select from.
So my check boxes are like this:
<div class="col-sm-10">
<div class="checkbox">
<input id="department_1" name="departments[]" type="checkbox" value="1">
<label for="department_1">Sales</label>
</div>
<div class="checkbox">
<input id="department_2" name="departments[]" type="checkbox" value="2">
<label for="department_2">Marketing</label>
</div>
<div class="checkbox">
<input id="department_3" name="departments[]" type="checkbox" value="3">
<label for="department_3">Tech Help</label>
</div>
</div>
My testing code is like this:
public function testUserCreation()
{
$this->be(User::find(10));
$this->visit('/users/create')
->type('First', 'first_name')
->type('Last', 'last_name')
->type('test#esample.com', 'email')
->type('123456', 'password')
->type('123456', 'password_confirmation')
->check('departments')
->press('Submit')
->seePageIs('/users');
}
When I am trying to check if throws error:
InvalidArgumentException: Nothing matched the filter [permissions] CSS
query provided for
If you specify the index for the multiple checkbox in both your form and test, then it works.
Form:
<input id="department_1" name="departments[0]" type="checkbox" value="1">
<input id="department_2" name="departments[1]" type="checkbox" value="2">
Unit test:
public function testUserCreation()
{
$this->be(User::find(10));
$this->visit('/users/create')
->type('First', 'first_name')
->type('Last', 'last_name')
->type('test#esample.com', 'email')
->type('123456', 'password')
->type('123456', 'password_confirmation')
->check('departments[0]')
->press('Submit')
->seePageIs('/users');
}
Using named indexes works as well.
<input name="departments[department_1]" type="checkbox" value="1">
// [...]
$this->check('departments[department_1]');
The only way I managed this was:
$this->visit('/users/create')
->submitForm('Submit', [
...
...
'departments[0]' => '1',
'departments[1]' => '2'
])
->seePageIs('/users');
Note that if you want to check the first and last item, you have to follow the order the inputs are placed.
$this->visit('/users/create')
->submitForm('Submit', [
...
...
'departments[0]' => '1',
'departments[2]' => '3' // index 2 instead 1.
])
->seePageIs('/users');

Resources