How to validate Dynamic input in vuejs / Laravel - laravel

I'm catching errors via interceptors and a Toast for UI. Usually the error is caught by the interceptor and displayed via the toast for one-time inputs, i'm trying to catch errors for an uncertain number of inputs. So far looping through the input array and setting rules does not work.
Component.vue
<template>
<div>
<div class="form-group" v-for="(input,k) in inputs" :key="k">
<input type="text" id="name" placeholder="Name" v-model="input.name" />
<span>
<i class="fas fa-minus" #click="remove(k)" v-show="k || ( !k && inputs.length > 1)"></i>
<i class="fas fa-plus" #click="add(k)" v-show="k == inputs.length-1"></i>
</span>
</div>
<button #click="addName">Create</button>
</div>
</template>
<script>
export default {
data() {
return {
inputs: [{name: ''}]
}
},
methods: {
add(index) {
this.inputs.push({ name: ''});
console.log( this.inputs);
},
remove(index) {
this.inputs.splice(index, 1);
},
addName() {
axios.post('/user', {userinputs:this.inputs}).then(response => {})
.catch(error => {
console.log(error);
});
}
}
}
</script>
Controller:
public function store(Request $request)
{
$rules = [
'userinputs' => 'required|max:255',
];
foreach ($request->input('userinputs') as $key => $my_object_in_array) {
$rules[$my_object_in_array['name']] = 'required|max:10';
}
return $rules;
}

I hope this is what you wanted to achieve.
public function store(Request $request)
{
$rules = [
'userinputs.*.name' => 'required|max:255',
];
$validator = \Illuminate\Support\Facades\Validator::make($request->all(), $rules);
if ($validator->fails()) {
//Return the errors as JSON
return response()->json(['success' => 'false', 'errors' => $validator->errors()], 400);
}
//Do something
return ['success' => 'true'];
}

Related

I'm trying in laravel to log in with my phone number but it doesn't work

I changed the login by mail to login with phone number in a laravel system, but it does not log in in any way. either it doesn't find it in the database or I'm doing something wrong. I asked chatgpt and searched many forums but still no success. where am i doing wrong?
LoginController
namespace App\Http\Controllers;
use Exception;
use App\Models\User;
use App\Helper\Reply;
use App\Models\Social;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;
use App\Events\TwoFactorCodeEvent;
use App\Traits\SocialAuthSettings;
use Froiden\Envato\Traits\AppBoot;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use \Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
use AppBoot, SocialAuthSettings;
protected $redirectTo = 'account/dashboard';
public function checkEmail(LoginRequest $request)
{
exit ;
$user = User::where('mobile', $request->mobile)
->select('id')
->where('status', 'active')
->where('login', 'enable')
->first();
if (is_null($user)) {
throw ValidationException::withMessages([
Fortify::username() => __('messages.invalidOrInactiveAccount'),
]);
}
return response([
'status' => 'success'
]);
}
public function checkCode(Request $request)
{
$request->validate([
'code' => 'required',
]);
$user = User::find($request->user_id);
if($request->code == $user->two_factor_code) {
// Reset codes and expire_at after verification
$user->resetTwoFactorCode();
// Attempt login
Auth::login($user);
return redirect()->route('dashboard');
}
// Reset codes and expire_at after failure
$user->resetTwoFactorCode();
return redirect()->back()->withErrors(['two_factor_code' => __('messages.codeNotMatch')]);
}
public function resendCode(Request $request)
{
$user = User::find($request->user_id);
$user->generateTwoFactorCode();
event(new TwoFactorCodeEvent($user));
return Reply::success(__('messages.codeSent'));
}
public function redirect($provider)
{
$this->setSocailAuthConfigs();
return Socialite::driver($provider)->redirect();
}
public function callback(Request $request, $provider)
{
$this->setSocailAuthConfigs();
try {
try {
if ($provider != 'twitter') {
$data = Socialite::driver($provider)->stateless()->user();
}
else {
$data = Socialite::driver($provider)->user();
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
return redirect()->route('login')->with('message', $errorMessage);
}
$user = User::where(['email' => $data->email, 'status' => 'active', 'login' => 'enable'])->first();
if ($user) {
// User found
DB::beginTransaction();
Social::updateOrCreate(['user_id' => $user->id], [
'social_id' => $data->id,
'social_service' => $provider,
]);
DB::commit();
Auth::login($user, true);
return redirect()->intended($this->redirectPath());
}
else {
return redirect()->route('login')->with(['message' => __('messages.unAuthorisedUser')]);
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
return redirect()->route('login')->with(['message' => $errorMessage]);
}
}
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/login';
}
public function username()
{
return 'mobile';
}
}
Here blade code;
<label for="mobile">#lang('auth.mobile')</label>
<input tabindex="1" type="text" name="mobile"
class="form-control height-50 f-15 light_text" autofocus
placeholder="#lang('auth.mobile')" id="mobile">
<input type="hidden" id="g_recaptcha" name="g_recaptcha">
</div>
#if ($socialAuthSettings->social_auth_enable)
<button type="submit" id="submit-next"
class="btn-primary f-w-500 rounded w-100 height-50 f-18 ">#lang('auth.next') <i
class="fa fa-arrow-right pl-1"></i></button>
#endif
<div id="password-section"
#if ($socialAuthSettings->social_auth_enable) class="d-none" #endif>
<div class="form-group text-left">
<label for="password">#lang('app.password')</label>
<x-forms.input-group>
<input type="password" name="password" id="password"
placeholder="#lang('placeholders.password')" tabindex="3"
class="form-control height-50 f-15 light_text">
<x-slot name="append">
<button type="button" data-toggle="tooltip"
data-original-title="#lang('app.viewPassword')"
class="btn btn-outline-secondary border-grey height-50 toggle-password"><i
class="fa fa-eye"></i></button>
</x-slot>
</x-forms.input-group>
</div>
<div class="forgot_pswd mb-3">
#lang('app.forgotPassword')
</div>
<div class="form-group text-left">
<input id="checkbox-signup" type="checkbox" name="remember">
<label for="checkbox-signup">#lang('app.rememberMe')</label>
</div>
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v2_status == 'active')
<div class="form-group" id="captcha_container"></div>
#endif
#if ($errors->has('g-recaptcha-response'))
<div class="help-block with-errors">{{ $errors->first('g-recaptcha-response') }}
</div>
#endif
<button type="submit" id="submit-login"
class="btn-primary f-w-500 rounded w-100 height-50 f-18">
#lang('app.login') <i class="fa fa-arrow-right pl-1"></i>
</button>
#if ($setting->allow_client_signup)
<a href="{{ route('register') }}"
class="btn-secondary f-w-500 rounded w-100 height-50 f-15 mt-3">
#lang('app.signUpAsClient')
</a>
#endif
</div>
</div>
</div>
</div>
</div>
</section>
</form>
<x-slot name="scripts">
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v2_status == 'active')
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async
defer></script>
<script>
var gcv3;
var onloadCallback = function () {
// Renders the HTML element with id 'captcha_container' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'gcv3'.
gcv3 = grecaptcha.render('captcha_container', {
'sitekey': '{{ $setting->google_recaptcha_v2_site_key }}',
'theme': 'light',
'callback': function (response) {
if (response) {
$('#g_recaptcha').val(response);
}
},
});
};
</script>
#endif
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v3_status == 'active')
<script
src="https://www.google.com/recaptcha/api.js?render={{ $setting->google_recaptcha_v3_site_key }}"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('{{ $setting->google_recaptcha_v3_site_key }}').then(function (token) {
// Add your logic to submit to your backend server here.
$('#g_recaptcha').val(token);
});
});
</script>
#endif
<script>
$(document).ready(function () {
$('#submit-next').click(function () {
const url = "{{ route('check_email') }}";
$.easyAjax({
url: url,
container: '#login-form',
disableButton: true,
buttonSelector: "#submit-next",
type: "POST",
data: $('#login-form').serialize(),
success: function (response) {
if (response.status === 'success') {
$('#submit-next').remove();
$('#password-section').removeClass('d-none');
$("#password").focus();
}
}
})
});
$('#submit-login').click(function () {
const url = "{{ route('login') }}";
$.easyAjax({
url: url,
container: '.login_box',
disableButton: true,
buttonSelector: "#submit-login",
type: "POST",
blockUI: true,
data: $('#login-form').serialize(),
success: function (response) {
if (response.two_factor == false) {
window.location.href = "{{ session()->has('url.intended') ? session()->get('url.intended') : route('dashboard') }}";
} else if (response.two_factor == true) {
window.location.href = "{{ url('two-factor-challenge') }}";
}
}
})
});
#if (session('message'))
Swal.fire({
icon: 'error',
text: '{{ session('message') }}',
showConfirmButton: true,
customClass: {
confirmButton: 'btn btn-primary',
},
showClass: {
popup: 'swal2-noanimation',
backdrop: 'swal2-noanimation'
},
})
#endif
});
</script>
</x-slot>
</x-auth> ```

Ajax image upload to database not working

I am trying to upload image to database using Ajax but It store image into public/images directory only,never store image into database,I had grabbed from itsolution for test purpose but never work,Could any one tell where am I wrong?
Route
Route::get('ajaxImageUpload', ['uses'=>'AjaxImageUploadController#ajaxImageUpload']);
Route::post('ajaxImageUpload', ['as'=>'ajaxImageUpload','uses'=>'AjaxImageUploadController#ajaxImageUploadPost']);
Controller
public function ajaxImageUploadPost(Request $request) {
$validator = Validator::make($request->all(), [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($validator->passes()) {
$input = $request->all();
$input['image'] = time() . '.' . $request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $input['image']);
AjaxImage::create($input);
return response()->json(['success' => 'done']);
}
return response()->json(['error' => $validator->errors()->all()]);
}
View
<form action="{{ route('ajaxImageUpload') }}" enctype="multipart/form-data" method="POST">
<input type="text" name="title" class="form-control" placeholder="Add Title">
<input type="file" name="image" class="form-control">
<button class="btn btn-success upload-image" type="submit">Upload Image</button>
</form>
<script>
$("body").on("click", ".upload-image", function (e) {
$(this).parents("form").ajaxForm(options);
});
var options = {
complete: function (response) {
if ($.isEmptyObject(response.responseJSON.error)) {
$("input[name='title']").val('');
alert('Image Upload Successfully.');
} else {
printErrorMsg(response.responseJSON.error);
}
}};
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function (key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
</script>
Save Image Location To The Database
use intervention;
public function ajaxImageUploadPost(Request $request){
$validator = Validator::make($request->all(), ['title' => 'required','image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
if ($validator->passes()) {
$image = new AjaxImage();
$image->title = $request->title;
if ($request->hasFile('image')) {
$img=$request->file('resim');
$filename=time().".".$img->getClientOriginalExtension();
$location=public_path('img/'.$filename);
Image::make($img)->save($location);
$image->image=$filename;
}
$image->save();
return response()->json(['success'=>'done']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}

Sending messages to a specific user with Laravel-Websockets (One to One chat)

I have a websocket group chat in my app which broadcasts user's message to all the other users. I want to make a one on one chat also which will broadcast messages to two sides only. How can I tell the websocket to broadcast the message to a specific user?
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
use Auth;
class ChatsController extends Controller
{
public function index()
{
if (Auth::check() === false) {
return view('login');
}
else
{
return view('chats');
}
}
public function fetchMessages()
{
return Message::with('user')->get();
}
public function sendMessage(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' => 'success'];
}
}
My Vue file:
<template>
<div class="row">
<div class="col-8">
<div class="card card-default">
<div class="card-header">Messages</div>
<div class="card-body p-0">
<ul class="list-unstyled" style="height:300px; overflow-y:scroll" v-chat-scroll>
<li class="p-2" v-for="(message, index) in messages" :key="index" >
<div style="background: #009afb; padding: 8px; color: white; border-radius: 15px;">
<img v-if="message.user.image == 'img'" src="https://www.stickpng.com/assets/images/585e4bf3cb11b227491c339a.png" style="width: 35px; height: 35px;">
<img v-else v-bind:src="'../images/' + message.user.image"
style="width: 35px; height: 35px;border-radius: 50%;">
<strong>{{ message.user.name }} {{ message.user.surname }} :</strong>
{{ message.message }}
<p style="color:lightgray;">
{{ message.created_at }}
</p>
</div>
</li>
</ul>
</div>
<input
#keydown="sendTypingEvent"
#keyup.enter="sendMessage"
v-model="newMessage"
type="text"
name="message"
placeholder="Enter your message..."
class="form-control">
</div>
<span class="text-muted" v-if="activeUser" >{{ activeUser.name }} is typing...</span>
</div>
<div class="col-4">
<div class="card card-default">
<div class="card-header">Active Users</div>
<div class="card-body">
<ul>
<li class="py-2" v-for="(user, index) in users" :key="index">
{{ user.name }}
</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:['user'],
data() {
return {
messages: [],
newMessage: '',
users:[],
activeUser: false,
typingTimer: false,
}
},
created() {
this.fetchMessages();
Echo.join('chat')
.here(user => {
this.users = user;
})
.joining(user => {
this.users.push(user);
})
.leaving(user => {
this.users = this.users.filter(u => u.id != user.id);
})
.listen('MessageSent',(event) => {
this.messages.push(event.message);
})
.listenForWhisper('typing', user => {
this.activeUser = user;
if(this.typingTimer) {
clearTimeout(this.typingTimer);
}
this.typingTimer = setTimeout(() => {
this.activeUser = false;
}, 3000);
})
},
methods: {
fetchMessages() {
axios.get('messages').then(response => {
this.messages = response.data;
})
},
sendMessage() {
this.messages.push({
user: this.user,
message: this.newMessage
});
axios.post('messages', {message: this.newMessage});
this.newMessage = '';
},
sendTypingEvent() {
Echo.join('chat')
.whisper('typing', this.user);
}
}
}
</script>
My table has fields of id,user_id and message.
Hello I have the same problem and fixed it like this
But Notice that I have the extra logic for it
1- in channels.php
Broadcast::channel('chat.{ticketId}', function ($user, $ticketId) {
$ticket = \App\Models\Ticket::find($ticketId);
return $user->id == $ticket->asked_user_id || $user->id == $ticket->responded_user_id;
});
2- I just allow users to chat with each other that one of them is asked the support ticket or the admin that responded the user
and in my event I have this code
class MessageSentEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public $ticket;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(TicketMEssage $message, Ticket $ticket)
{
$this->message = $message;
$this->ticket = $ticket;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('chat.' . $this->ticket->id);
}
public function toBroadcast()
{
return new MessageSentEvent($this->message);
}
}
3- I get message and the ticket like this
$ticket = Ticket::find($id);
$messages = $ticket->messages;
$messages->load('user');
return response()->json([
'messages' => $messages,
'ticket' => $ticket,
'user' => auth()->user()
]);
4- and I store and broadcast Message like below
$ticket = Ticket::find($request->ticket_id);
$message = $ticket->messages()->create([
'message' => $request->message,
'for' => auth()->id() == $ticket->asked_user_id ? TicketMessage::FOR_USER['asked'] : TicketMessage::FOR_USER['responded'],
'user_id' => auth()->id(),
]);
$message->load('user');
broadcast(new MessageSentEvent($message, $ticket));
return ['status' => 'success', 'message' => $message];
5- and the important part in js file (React Or Vue Or ...)
window.Echo.join(`chat.${props.ticketId}`)
.listen('MessageSentEvent', (message) => {
setMessages((prevState) => [...prevState, message.message]);
});
I listen just to channel that is with the ticket id that I get from props(you should pass it in any way)
and the key parts are 1 and 4 and 5
Hope This Help You :)))

I can not save values using POST method - laravel vue

I'm trying to save the data I send from the Event view. in the storeEvent method of the EventController driver but it gives me error 422 and I can not find the problem so far.
The Event model has a many-to-many relationship with the Categories model, and Event also has a many-to-many relationship with the Coins model, which is why I occupy vue-multiselect since the user can select several categories or several coins for the same event
Event.vue
<template>
<form v-on:submit.prevent="createdEvent" class="form-horizontal">
<div class="form-group row">
<label>Titulo</label>
<input type="text" name="title" maxlength="25" v-model="title">
</div>
<div class="form-group row">
<label>*Cryptodivisas</label>
<multiselect v-model="coinvalue" :options="coins"
:multiple="true" label="name"
track-by="id" placeholder="Seleccione">
</multiselect>
</div>
<div class="form-group row">
<label>*Categoría</label>
<multiselect v-model="categoryvalue" :options="categories"
:multiple="true" label="name"
track-by="id" placeholder="Seleccione">
</multiselect>
</div>
<div class="col-sm-12">
<button class="btn" type="submit">Crear evento</button>
</div>
</form>
<script>
import Multiselect from 'vue-multiselect';
export default {
components: {
Multiselect,
},
props: ['auth'],
data () {
return {
user: {},
title: '',
coins: [],
coinvalue: [],
categories: [],
categoryvalue: [],
}
},
created() {
this.getCoins();
this.getCategories();
},
mounted() {
this.user = JSON.parse(this.auth);
},
methods: {
getCoins(){
let urlCoin = '/dashboard/coins';
axios.get(urlCoin)
.then((response) => {
this.coins = response.data;
})
.catch((err) => {
})
},
getCategories(){
let urlCategories = '/dashboard/categories';
axios.get(urlCategories)
.then((response) => {
this.categories = response.data;
})
.catch((err) => {
})
},
createdEvent(){
let urlEvent = '/dashboard/newEvent';
const eventData = {
'id' : this.user.id,
'title' : this.title,
'coin' : this.coinvalue,
'category' : this.categoryvalue,
}
console.log(eventData);
axios.post(urlEvent, eventData)
.then((response) => {
console.log(ok);
})
.catch((err) => {
console.log(err.response.data);
})
}
</script>
storeEvent (EventController)
public function storeEvent(Request $request)
{
$this->validate($request, [
'title' => 'required|max:25',
'coin' => 'required',
'category' => 'required',
]);
$userAuth = Auth::user()->id;
$userEvent = $request->id;
if($userAuth === $userEvent){
$event = new Event;
$event->user_id = $userEvent;
$event->title = $request->title;
if($event->save()){
$event->coins()->attach($request->coin);
$event->categories()->attach($request->category);
return response()->json([
'status' => 'Muy bien!',
'msg' => 'Tu evento ya fue creado con éxito.',
], 200);
}
else {
return response()->json([
'status' => 'Error!',
'msg' => 'No pudimos crear tu evento.',
], 401);
}
}
}
I think the problem may be when I assign the values to the coin () -> attach () and category () -> attach () section, but I have no idea how to solve it due to my inexperience in the tool.
The system was made entirely in Laravel and it worked without problems, now that it is being updated with Vue it began to give inconveniences.
Any ideas? I occupy Laravel 5,6, Vuejs 2, Axios and Vue-multiselect 2
Try sending form data
Here is the example for you.
var urlEvent = '/dashboard/newEvent';
var form_data = new FormData();
form_data.append('id',this.user.id);
form_data.append('title',this.title);
for(let coin of this.coinvalue)
form_data.append('coin[]', coin);
for(let category of this.categoryvalue)
form_data.append('category[]', category);
axios(urlEvent,{
method: "post",
data: form_data
})
.then(res => {
console.log(ok);
})
.catch(err => {
console.log(err.response.data);
});
If this stills gives you a 422 status code (Unprocessable entities). Then try returning $request in you controller. And check what data are actually send to the controller and what your validation is.
422 means validation error so do a console.log or inspect the element on axios call and check that :
'title' : this.title,
'coin' : this.coinvalue,
'category' : this.categoryvalue,
Are not empty, cause right now some data from above is missing since its a 422 validation exception.

methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php laravel 5.0

I want to login as I submit the form but I am getting an error.
The form code is as follows:
{!! Form::open() !!}
{{ $errors->first("parentPassword") }}<br />
<div>
<legend>Parent</legend>
Email<br>
<input type="email" id="email" name="parentEmail" required>
<br>
Password<br>
<input type="password" name="parentPassword">
<br><br>
</div>
{!!Form::submit('Submit',array('class' => 'btn btn-outline btn-primary')) !!} </fieldset>
{!! Form::close() !!}
The controller code is as follows:
App\Http\Controllers;
use Illuminate\Support\Facades\Redirect;
class loka extends Controller
{
public function login()
{
if ($this->isPostRequest()) {
$validator = $this->getLoginValidator();
if ($validator->passes()) {
$credentials = $this->getLoginCredentials();
if (Auth::attempt($credentials)) {
return redirect()->intended('/');
}
return Redirect::back()->withErrors([
"parentPassword" => ["Credentials invalid."]
]);
} else {
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return view("signup.index");
}
protected function isPostRequest()
{
// return Request::isMethod('post');
}
protected function getLoginValidator()
{
return Validator::make(Request::all(), [
"parentEmail" => "required",
"parentPassword" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"parentEmail" => Request::input("parentEmail"),
"parentPassword" => Request::input("parentPassword")
];
}
}
The route is as follows:
Route::patch("/index", [
"as" => "login/index",
"uses" => "loka#login"
]);

Resources