I want to send email for more than one user to Mailtrap - laravel

I tried to send an email to a user and arrived at Miltrap
Now I put all the users on my system (table users in database) and introduced them to checkboxs and I want to send one email to more than one user or to all users and I did not see the result on the mailtrap
This is the code
MailboxController.php
public function form(Request $request)
{
$users = User::where('id', '!=', auth()->user()->id)->get();
return view('MailBox.form',compact('users'));
}
public function contact(Request $request)
{
//$emails = [];
$this->validate($request, [
'email' => 'required|email',
'subject' => 'min:3',
'message' => 'min:10']);
$data = array(
'email' => $request->email,
'subject' => $request->subject,
'bodyMessage' => $request->message
);
Mail::send('MailBox.contact', $data, function($message) use ($data){
$message->from('info#dev-any.com');
$message->to($data['email']);
$message->subject($data['subject']);
});
Session::flash('success', 'Your Email was Sent!');
return redirect('/dashboard/mailbox');
}
Web.php
Route::get('/mailbox', 'MailboxController#form')->name('mailbox.form');
Route::post('/mailbox/contact', 'MailboxController#contact')->name('contact');
form.blade.php
<form action="{{ route('contact') }}" method="POST">
{{ csrf_field() }}
<div class='form-group col-md-6'><strong>Select User :</strong><br>
<input type="checkbox" id = "chckHead" name="chk_all" value="" onchange="checkall()" id='allcb' /><strong> Check All </strong> </br>
#foreach ($users as $user)
<tr>
<td><input type="checkbox" class = "chcktbl" onchange="check()" name="email" id="email" value={{ $user->id }}></td>
<td>{{ $user->name }}</td></br>
</tr>
#endforeach
</div>
<div class="form-group col-md-6">
<label name="subject">Subject:</label>
<input id="subject" name="subject" class="form-control">
</div>
<div class="form-group col-md-6">
<label name="message">Message:</label>
<textarea id="message" name="message" class="form-control">Type your message here...</textarea>
</div>
<input type="submit" value="Send Message" class="btn btn-success col-md-6">
</form>
</div>
</div>
<script type="text/javascript">
$('.chcktbl').click(function () {
var length = $('.chcktbl:checked').length;
if (length > 3) {
// alert(length);
$('.chcktbl:not(:checked)').attr('enable', true);
}
else {
$('.chcktbl:not(:checked)').attr('enable', false);
}
});
</script>
<script type="text/javascript">
$('#chckHead').click(function () {
if (this.checked == false) {
$('.chcktbl:checked').attr('checked', false);
}
else {
$('.chcktbl:not(:checked)').attr('checked', true);
}
});
$('#chckHead').click(function () {
});

Simply change the email checkbox, and modify the validation
<input type="checkbox" class="chcktbl" onchange="check()" name="email[]" id="email" value={{ $user->id }}>

Related

Laravel multi select options ajax request

I'm trying to add multiple courses for a user using ajax. When I click on submit button, everything else updated but the courses. I don't know what I did wrong. Please help me...
This is my blade:
<input type="hidden" name="user_id" id="user_id" value="{{$user_details->id}}">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{$user_details->name}}">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="{{$user_details->email}}">
</div>
<div class="form-group">
<label for="courses_id">Courses</label>
#php
$all_courses = $user_details->courses_id;
#endphp
<select name="courses_id[]" multiple id="course" class="form-control nice-select wide">
#foreach($courses as $data)
#if($all_courses)
<option #if(in_array($data->id,$all_courses)) selected #endif value="{{$data->id}}">{{$data->title}}</option>
#else
<option value="{{$data->id}}">{{$data->title}}</option>
#endif
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary mt-4 pr-4 pl-4">{{__('Update User')}}</button>
</form>
<script>
$(document).ready(function() {
if($('.nice-select').length > 0){
$('.nice-select').niceSelect();
}
$(document).on('change','select[name="courses_id[]"]',function (e) {
e.preventDefault();
var selectedId = $(this).val();
$.ajax({
url : "{{route('admin.user.course.by.slug')}}",
type: "POST",
data: {
_token : "{{csrf_token()}}",
id: selectedId
},
success:function (data) {
$('#course').html('');
$.each(data,function (index,value) {
$('#course').append('<option '+selected+' value="'+value.id+'">'+value.title+'</option>');
$('.nice-select').niceSelect('update');
});
}
});
});
} );
</script>
My controller:
namespace App\Http\Controllers;
use App\Courses;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function edit($id)
{
$user_details = User::find($id);
$courses = Courses::where(['status'=> 'publish'])->get();
return view('backend.user.edit-user')->with([ 'user_details' => $user_details, 'courses' => $courses]);
}
public function user_update(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:191',
'email' => 'required|string|max:191',
'courses_id' => 'nullable',
],[
'name.required' => __('Name is required'),
'email.required' => __('Email is required'),
]);
User::find($request->user_id)->update([
'name' => $request->name,
'email' => $request->email,
'courses_id' => serialize($request->courses_id),
]);
return redirect()->back()->with(['msg' => __('User Profile Updated Successfully..'), 'type' => 'success']);
}
public function course_by_slug(Request $request){
$all_courses = Courses::where(['status' => 'publish'])->get();
return response()->json($all_courses);
}
}
My route:
Route::prefix(user')->middleware(['adminPermissionCheck:Users Manage'])->group(function () {
Route::get('/edit/{id}', 'UserController#edit')->name('admin.user.edit');
Route::post('/update', 'UserController#user_update')->name('admin.user.update');
Route::post('/course-by-slug', 'UserController#course_by_slug')->name('admin.user.course.by.slug');
});

Ajax script to update record does not work, Laravel

I wrote a small script that updates the information on the page when editing. Everything basically works as it should, but I just can’t update the image. I don’t understand what the matter is. Without a script, with a page reload, everything works as it should.
Ajax script
<script type="text/javascript">
$("document").ready(function() {
$("#editPostButton{{$post->id}}").click(function() {
var formData = $("#EditPostForm{{$post->id}}").serialize();
$.ajax({
url: "{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}",
type: "POST",
data: formData,
success: function(data) {
$("#textpostdata{{$post->id}}").html($(data).find("#textpostdata{{$post->id}}").html());
$("#closeButton{{$post->id}}").click();
}
});
});
});
</script>
My Controller
public function editPost(Request $request, $id, $postId) {
$validator = $this->validate($request,[
'title' => 'max:100',
'message' => 'max:5000',
'img' => 'mimes:jpeg,png,gif,jpg|max:5000',
'videoPost' => 'max:100'
]);
if($validator) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/'.Auth::user()->id.'/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
return redirect()->back();
}
}
And update form
<form action="{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}" method="post" enctype="multipart/form-data" id="EditPostForm{{$post->id}}" name="postForm">
#csrf #method('PATCH')
<div class="form-group">
<textarea maxlength="100" name="title" class="form-control" rows="1">{{$post->title}}</textarea>
</div>
<div class="form-group">
<textarea id="message" maxlength="5000" name="message" class="form-control" rows="10">{{$post->message}}</textarea>
</div>
<div class="form-group">
<textarea maxlength="100" class="form-control mt-1" id="videoPost" name="videoPost" cols="100" rows="1">{{$post->videoPost}}</textarea>
</div>
<h6>Current image</h6>
<img src="{{$post->img}}" class="img-fluid mb-2" width="230">
<div class="form-group">
<input type="file" id="img" name="img" accept="image/*">
</div>
<button type="button" class="btn btn-sm btn-primary" id="editPostButton{{$post->id}}">Edit</button>
</form>

Laravel - How to update checkbox field value

Using Laravel-5.8, I have been able to save the data into the database including the check box field.
protected $fillable = [
'appraisal_name',
'is_current',
'appraisal_start',
'appraisal_end',
];
public function rules()
{
return [
'appraisal_name' => 'required|min:5|max:100',
'appraisal_start' => 'required',
'appraisal_end' => 'required|after_or_equal:appraisal_start',
'is_current' => 'nullable|boolean',
];
}
public function create()
{
return view('appraisal.appraisal_identities.create');
}
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
public function edit($id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$identity = AppraisalIdentity::where('id', $id)->first();
return view('appraisal.appraisal_identities.edit')->with('identity', $identity);
}
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
create.blade
<form action="{{route('appraisal.appraisal_identities.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
edit.blade
<form action="{{route('appraisal.appraisal_identities.update', ['id'=>$identity->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
I have these issues while trying to update the data?
The edit checkbox field (is_current) did not pick the value from the database when loaded. It remains unchecked.
is_current is either 0 or 1. The goal is that, there can only be one is_current field that is set to 1 in the table. From the checkbox, when is_current is checked to 1, it should set any other is_current that is 1 to 0 in the table.
How do I resolve these issues?
Thank you.
In edit blade update your checkbox code as this:
<input type="checkbox" class="form-control" name="is_current" #if($identity->is_current == 1) checked #endif value="{{old('is_current')}}">
In your update function change this:
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
In your store function change this:
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
$id = $identity->id;
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
try this in the edit blade
<
is_current == 1 ? checked : value="{{old('is_current')}}">

Laravel get a empty variable from axios.post from vuie.js module

partners from stackOverflow im making a module using laravel like backend, and vue.js by frontend, i have a form to create a new entity, but the controller dont get the values¡, plz help me to find the error. I'm going to share the code.
the routes.web
//new event from API
Route::resource('/api/events', 'EventsController', ['except' => 'show','create']);
The function in the controller EventsController.php
<?php
namespace soColfecar\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use soColfecar\Http\Requests\CreateEventRequest;
use soColfecar\Http\Requests\UpdateEventRequest;
use soColfecar\User;
use soColfecar\Change;
use soColfecar\Event;
use soColfecar\Event_type;
use Auth;
public function store(Request $request)
{
$exploded = explode(',', $request->banner);
$decoded = base64_decode($exploded[1]);
if(str_contains($exploded[0],'jpeg'))
$extension = 'jpg';
else
$extension = 'png';
$fileName = str_random().'.'.$extension;
$path = public_path().'/storage/banner/'.$fileName;
file_put_contents($path, $decoded);
Event::create([
'event' => strtoupper($request['event']),
'id_event_type' => $request['id_event_type'],
'date_init' => $request['date_init'],
'date_end' => $request['date_end'],
//'banner' => $fileName,
]);
Change::create([
'description' => 'Creo el de evento:'.$request['event'].' correctamente.',
'id_item' => 10,
'id_user' => Auth::user()->id,
]);
return redirect()->route('events.index')
->with('info', 'evento guardado con exito');
}
the method:
<form method="POST" v-on:submit.prevent="storeNewEvent">
<div class="form-group m-form__group">
<label for="eventTypeInput">Tipo de vento:</label>
<v-select :options="eventTypes" v-model="newEvent.id_event_type" id="eventTypeInput">
<template slot="option" slot-scope="option">
{{ option.label }}
</template>
</v-select>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.city_id }}</span>
</div>
<div class="form-group m-form__group">
<label for="inputHotelName">Nombre del Evento</label>
<input type="text" class="form-control" name="inputHotelName" v-model="newEvent.event" placeholder="Nombre del Evento">
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.hotel_name }}</span>
</div>
<div class="form-group m-form__group">
<label for="date_init_imput">Fecha de inicio</label>
<input class="form-control" type="date" v-model="newEvent.date_init" value="" id="date_init_imput">
</div>
<div class="form-group m-form__group">
<label for="date_end_imput">Fecha de finalizacion</label>
<input class="form-control" type="date" v-model="newEvent.date_end" value="" id="date_end_imput">
</div>
<div class="form-group m-form__group">
<label for="customFile">Banner del Evento</label>
<div></div>
<div class="custom-file">
<input type="file" class="custom-file-input" #change="getLogo" id="customFile">
<label class="custom-file-label" for="customFile">Seleccione archivo</label>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.logo }}</span>
</div>
</div>
<hr>
<button type="submit" class="btn btn-info waves-effect text-left">Guardar</button>
</form>
data() {
return {
changes: [],
eventTypes: [],
errors: [],
newEvent: {
event: '',
id_event_type: '',
date_init: '',
date_end: '',
banner: '',
}
}
},
storeNewEvent : function() {
var url = 'api/events';
var newEvent = this.newEvent
axios.post(url, {event: this.newEvent}).then(response => {
this.newEvent = {}
this.errors = [];
$('#new_event_modal').modal('hide');
$('.modal-backdrop').remove();
toastr.success('Se ha creado el evento con exito!')
}).catch(error => {
this.errors = error.response.data
});
},
And the error
"Too few arguments to function soColfecar\Http\Controllers\EventsController::store(), 0 passed and exactly 1 expected"
enter image description here
You need to type hint the $request so Laravel knows to fill it in ("dependency injection").
At the top of your file:
use Illuminate\Http\Request;
Then, for your function:
public function store(Request $request) {

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code?

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code? I got it all for a default presentation but i still get an Undefined Variable request with this code - please your answer will be appreciated:
UserController:
public function account(&$data, $request){
User::get_user(self::$data,$request);
self::$data['title'] = self::$data['title'] . 'Edit Account';
return view('forms.account', self::$data);
}
public function postAccount(AccountRequest $request){
User::edit_user($request);
return redirect('');
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
Model:
static public function get_user(&$data,$request){
$sql = "SELECT * FROM users WHERE id = ". Session::get('user_id');
$data['users'] = DB::select($sql);
}
static public function edit_user(&$data,$request) {
$id = $data['id'];
$sql = "SELECT * FROM users WHERE id = ".$id;
$getVal = DB::select($sql);
if($data['name'] || $data['password'] || $data['email']){
if($data['name']){
DB::update("UPDATE users SET name = ? WHERE id = ?",[$data['name'],$id]);
session(['user_name' => $data['name']]);
}
if($data['password']){
DB::update("UPDATE users SET password = ? WHERE id = ?",[bcrypt($data['password']),$id]);
}
if($data['email']){
DB::update("UPDATE users SET email = ? WHERE id = ?",[$data['email'],$id]);
}
}
Session::flash('sm',$request['name'] . '`s Has Been Updated');
}
Web:
Route::get('user/account', 'UserController#account');
Route::post('user/account', 'UserController#postAccount');
HTML:
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>Edit Your Account -</h1>
</div>
<div class="row" style="margin-left:30%;">
<div class="col-md-6">
<form action="" method="post">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $user['id'] }}">
<div class="form-group">
<label for="name"></label>
<input value="{{ $user['name'] }}" type="text" name="name"
class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email"></label>
<input value="{{ $user['email'] }}" type="text" name="email"
class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="editpassword"></label>
<input type="password" name="password" class="form-control"
id="editpassword" placeholder="Edit Password">
</div>
<div class="form-group">
<label for="editpasswordconf"></label>
<input type="password" name="password_confirmation" class="form-
control" id="editpasswordconf" placeholder="Confirm New Password">
</div>
<div class="form-group text-center">
<input type="submit" name="submit" value="Update Details" class="btn
btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Your AccountController should look like this:
public function edit($request, Account $account){
return view('forms.account', [
'account' => $account,
'title' => 'Edit Account'
]);
}
public function update(AccountRequest $request, Account $account){
$account->update($request->all());
Session::flash('sm', $account->name . ' Has Been Updated');
return redirect()->back();
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
That is about as much code as you need for this process... please read the documentation for Eloquent https://laravel.com/docs/5.4/eloquent

Resources