[Contact form]How to convert object to string in Laravel? - laravel

I'm studying contact form script. It works fine but after I add this lines
I'm having this error.
htmlspecialchars() expects parameter 1 to be string, object given (View: /home/------/resources/views/mail.blade.php)
Here is my contact.blade.php
#php
$week = array( "日", "月", "火", "水", "木", "金", "土" );
$s_date = date("Y年m月d日 H時i分");
$dayofweek = "(".$week[date("w")].")";
$s2_date = $s_date . $dayofweek;
$k_no_raw = strval("km_".date("Y_md_His_A") ."_". date('w'));
#endphp
<br>
<input name="sdate" type="hidden" value="{{ $s2_date }}">
<input name="k_no" type="hidden" value="{{ $k_no_raw }}">
I tried to change object to string.
but I still got same error.
Controller part of this section
\Mail::send('mail', array(
'sdate' => $request->get('sdate'),
'k_no' => $request->get('k_no'),
),
Here is mail.blade.php
{{ $k_no }}
Could someone teach me right code please?
UPDATE

Related

Undefined variable $attendance_status using radio button laravel

i am using laravel query builder but the problem is i am using radio buttons but i want to update the attendance at the radio button but it returns an error Undefined variable $attendance_status
i don't know why please help and how can i pass the $attendance_status variable
here is my code
my form
<form action="{{route('Attendances.update',$student->id)}}" method="post">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{$student->id}}">
<label class="block text-gray-500 font-semibold sm:border-r sm:pr-4">
<input name="attendences"
{{ $student->attendances()->first()->attendence_status == 1 ? 'checked' : '' }}
class="leading-tight" type="radio" value="presence">
<span class="text-success">حضور</span>
</label>
<label class="ml-4 block text-gray-500 font-semibold">
<input name="attendences"
{{ $student->attendances()->first()->attendence_status == 0 ? 'checked' : '' }}
class="leading-tight" type="radio" value="absent">
<span class="text-danger">غياب</span>
</label>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-dismiss="modal">{{trans('Students_trans.Close')}}</button>
<button class="btn btn-danger">{{trans('Students_trans.submit')}}</button>
</div>
</form>
here is my controller
update
public function update(Request $request, $id)
{
// return $request;
if($request->attendances == 'absent'){
$attendance_status = 0;
}
else if($request->attendances == 'presence'){
$attendance_status = 1;
}
Attendance::find($id)->update([
'student_id'=> $id,
'grade_id'=> $request->grade_id,
'class_id'=> $request->classroom_id,
'section_id'=> $request->section_id,
'attendance_date'=> date('Y-m-d'),
'status' => $attendance_status,
]);
return back();
You have an if and an elseif in your Controller, so only 2 conditions would create a variable named $attendance_status. You probably want to add a default branch, else basically, to make sure that the variable gets created with some default value before you try to use it in your update call.
Not sure which one of those 2 options you want to be the default but this would simplify things:
$attendance_status = $request->attendences == 'presence';
https://laravel.com/docs/9.x/redirects#redirecting-with-flashed-session-data
You may use the withInput method provided by the RedirectResponse instance to flash the current request's input data to the session before redirecting the user to a new location. Once the input has been flashed to the session, you may easily retrieve it during the next request:
return back()->withInput();
Surely {{ $student->attendances()->first()->attendence_status == 0 ? 'checked' : '' }} logic does not work in this way.
try this instead
<input name="attendences" checked="{{ $student->attendances()->first()->attendence_status == 0 ? true : false}}" class="leading-tight" type="radio" value="absent">

Laravel 5: Check for Specific Error

I have Password and Confirm Password inputs. I have coded these inputs so that in the event of an error the inputs highlight, like so:
<div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}>
<label>Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group {{ $errors->has('password_confirmation') ? 'has-error' : '' }}>
<label>Password</label>
<input type="password" name="password_confirmation" class="form-control">
</div>
In my Controller, I validate these inputs as follows:
$this->validate($request, [
....
'password' => 'required|min:8|confirmed',
'password_confirmation' => 'required',
....
]);
When either input is null and/or less than 8 characters, the inputs highlight as expected. However, when the inputs don't match, I would logically expect the Confirm Password input to highlight. However, it is the Password field that highlights, because that is the input that the "confirmed" rule is set to.
The "$errors->has()" method simply checks if an error exists for an input. Is there a way to check if an input has a specific kind of error?
Yes, you can get the array of errors for a given input name by using:
{{ $errors->get('password') }}
So you can check if the password errors array has the confirmation error and then add the additional class to your confirmation input field:
#if (in_array(trans('validation.confirmed', ['attribute' => 'password']), $errors->get('password'))) has-error #endif
And the helper methods may vary between Laravel versions:
Laravel < 5.4: trans('validation.confirmed', ['attribute' => 'password'])
Laravel 5.4: __('validation.confirmed', ['attribute' => 'password'])

How to populate edit form fields in laravel 5.3

I have a problem in populating edit form fields in my first Laravel 5.3 application. In examples I have found online, they have used Form facade to do it. However, I prefer to use plain html.
This is my controller action
public function edit()
{
$profile = Profile::find(Auth::user()->id);
return view('profile.edit', ['profile' => $profile]);
}
In my view file I have a form like this
<form method="POST" action="{{ url('profile/update') }}">
{{ csrf_field() }}
<input id="name" type="text" name="name" value="{{ old('name') }}">
...
</form>
Problem is, above input field is not populated with the value of the $profile->name.
I can get it to work, setting the value attribute like
{{ (old('name')) ? old('name') : $profile->name }}
Since I'm new to Laravel framework I want to know if there is a better way to do that.
Use old($key, $default). It will return $default if $key is not found.

Laravel form only saving last in array

Right now I have a chat and what I am working on is being able to take selected chat messages and turn them into a post with comments. My struggle is that right now I am only getting the very last comment to save and none of the comments before it. This has to do with not being able to write the foreach loop correctly when saving in the controller I believe.
The error I am getting right now is
Invalid argument supplied for foreach()
I am showing the commenters array but not saving it correctly. The commentors are ids of users involved and the user_id (not userId) is what I need to save for both, right now only getting '11' and not '9'. as you can see from the error message
...'commenters' => ' 9, 11, ', 'user_id' => '11', 'comment' => 'hey there'), 'userId' => '9', 'commentorIds' => array(), 'createPost' => object(Post)))
Form
<div class="selectedChatSection" style="padding: 15px 15px 15px 15px;">
{!! Form::open(['url'=>'post/selectedChatPost']) !!}
<div class="jumbotron">
<center><img src="/img/icons/icon-chat.png"></center>
</div>
#foreach ($postSavers as $postSaver)
<div class="postSaverId" data-id="{{$postSaver->id}}"></div>
#endforeach
<input type="hidden" name="space-id" value="">
<input type="hidden" multiple="multiple" name="commenters" value="#foreach($selectedChats as $selectedChat){{$selectedChat->id}}, #endforeach ">
#foreach ($selectedChats as $selectedChat)
<div style="border-top: 1px solid #eee;padding: 10px 10px 10px 10px;">
<p><img src="/assets/avatars/{{$selectedChat->avatar}}" height:"75" width="75" style="border-radius:50px;"> <input type="hidden" name="user_id" value="{{$selectedChat->id}}">{{$selectedChat->name}} : <input type="hidden" name="comment" value="{{$selectedChat->body}}">{{$selectedChat->body}}</p>
#endforeach
</div>
<div class="modal-footer">
{!! Form::submit('post', ['id'=> 'post-button']) !!}
{!! Form::close() !!}
</div>
Controller
public function storeSelectedChat() {
$input = Request::all();
$userId = Auth::user()->id;
$commentorIds = array();
$createPost = new Post;
$createPost->space_id = 8;
$createPost->user_id = $userId;
// $createPost->content = $input['content'];
$createPost->linkPhoto = "/img/icons/icon-chat.png";
$createPost->save();
//needs to be a foreach loop here for each comment/chat segment.
foreach(Input::get('commenters') as $commenter) {
$createComments = new Comment();
$createComments->post_id = $createPost->id;
$createComments->comment = $input['comment'];
$createComments->user_id = $commenter;
$createComments->save();
}
}
Any help would be greatly appreciated. I have done this before but nothing seems to work in this instance for some reason. Thanks.
Your <input type="hidden" multiple="multiple" name="commenters" value="#foreach($selectedChats as $selectedChat){{$selectedChat->id}}, #endforeach "> should not have multiple attribute.
The multiple attribute works with the following input types: email,
and file.
According to http://www.w3schools.com/tags/att_input_multiple.asp. Even though the multiple attribute logically makes sense to you because logically you have multiple commentors, semantically it is incorrect. You still have one <input> attribute and what it contains logically is up to you interpret. You should use regex to separate your comma delimited input and then use foreach on that resulting array.

Laravel form binding

Hi I am using laravel form binding along with
jqBootstrapValidation . In order to successfuly have the validate the input fields, I must pass something like "required" (without quotes) in the tag . Can you please let me know how can I achieve this ?
FYI .. the minlength works fine but the required does not work.
For example one of input elements currently looks as such
{{Form::text('username', null, array('class'=> 'form-control tip', 'data-toggle'=> 'tooltip', 'data-placement'=> 'bottom', 'title'=>'Enter your username that you have been using till now. This is a compulsory field.','placeholder'=>'Username ( must be filled )','minlength'=>'2'))}}
Thanks
You can't, take a look at the source code that builds the attributes:
protected function attributeElement($key, $value)
{
if (is_numeric($key)) $key = $value;
if ( ! is_null($value)) return $key.'="'.e($value).'"';
}
You'll always get a <attribute>=<name>, what you can test is to use it this way:
{{ Form::text('username',
null,
array( 'class'=> 'form-control tip',
'data-toggle'=> 'tooltip',
'data-placement'=> 'bottom',
'title'=>'Enter your username that you have been using till now. This is a compulsory field.',
'placeholder'=>'Username ( must be filled )',
'minlength'=>'2',
0 => 'required'
)
)
}}
It will build a tag
<... required="required" ...>
And it might work for jqBootstrapValidation.
Otherwise you'll have to create those inputs manually.
I've used this with the HTML attributes required="required" and also required="" works too. Changing the example they provide and adding in the Laravel Blade tags gives
<form class="form-horizontal" novalidate>
<div class="control-group">
<label class="control-label">Type something</label>
<div class="controls">
{{ Form::text('name', null , array('required' => '')) }}
<p class="help-block"></p>
</div>
</div>
{{ Form::submit('submit')}}
</form>
This worked fine and produced the error "This is required". I swapped in your form field and added in the
'required' => ''
to the end of your attribute array and that too worked just fine. Alternatively you could instead add in
'required' => 'required'
as jqBootstrapValidation picks up either. Good luck.

Resources