Impossible to upload file with buefy upload - laravel

I'm creating a website and now I try to use my upload file system. I test it with postman and it works perfectly. But when I try to use with my website page, it not works.
Backend : I use Lumen
Frontend : I use Buefy
The upload function into UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function uploadImageIntoUser(Request $request, $id){
//try{
$user = User::findOrFail($id);
if ($user->id == Auth::id()) {
$url = json_decode($this->uploadImage($request, $id)->getContent(), true);
$newRequest = new Request();
$newRequest->replace(['picture' => $url['data']['image'] ]);
return $this->update($id, $newRequest);
}
return response()->json(['message' => 'You not have the right to do this'], 412);
/*}catch (\Exception $e){
return response()->json(['message' => 'User not found'], 404);
}*/
}
}
The upload function into my Controller.php
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Galerie;
use Illuminate\Support\Str;
class Controller extends BaseController
{
//Upload image
public function uploadImage(Request $request, $id)
{
try{
$this->validate($request, [
'folder' => array(
'required',
'alpha')
]);
$folder = $request->input('folder');
if(strcmp($folder, "user") !== 0 && strcmp($folder, "article") !== 0 && strcmp($folder, "galerie") !== 0){
return response()->json(['message' => 'Incorrect folder name : choose between user, article and galerie'], 409);
}
} catch (\Exception $e) {
return response()->json(['message' => 'Incorrect folder name : only in lowercase'], 409);
}
$response = null;
$user = (object) ['image' => ""];
if ($request->hasFile('image')) {
$original_filename = $request->file('image')->getClientOriginalName();
$original_filename_arr = explode('.', $original_filename);
$file_ext = end($original_filename_arr);
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
$image = time() . '.' . $file_ext;
if ($request->file('image')->move($destination_path, $image)) {
if ($folder == 'user') {
$user->image = '/upload/user/' . $image;
}else if($folder == 'article'){
$user->image = 'upload/article/' . $image;
}else if($folder == 'galerie'){
$user->image = 'upload/galerie/' . $image;
$galerie = new Galerie;
$galerie->id = Str::uuid();
$galerie->url = $user->image;
$galerie->save();
}
return $this->responseRequestSuccess($user);
} else {
return $this->responseRequestError('Cannot upload file');
}
} else {
return $this->responseRequestError('File not found');
}
}
protected function responseRequestSuccess($ret)
{
return response()->json(['status' => 'success', 'data' => $ret], 200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
protected function responseRequestError($message = 'Bad request', $statusCode = 200)
{
return response()->json(['status' => 'error', 'error' => $message], $statusCode)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Call my upload system from my profile page (called connexion.vue)
<template>
<section class="section">
<div class="container">
<p id="center-text" class="title">Informations Personnelles</p><br>
<b-notification v-if="error" type="is-warning">
{{ error }}
</b-notification>
<div class="columns">
<div class="column">
<img :src='baseURL + loggedInUser.picture'>
<b-field label="Modifier la photo de profil">
<b-field class="file is-secondary" :class="{'has-name': !!file2}">
<b-upload v-model="file2" class="file-label" rounded>
<span class="file-cta">
<b-icon class="file-icon" icon="upload"></b-icon>
<span class="file-label"><strong>Sélectionner un fichier à envoyer</strong></span>
</span>
<span class="file-name" v-if="file2">
{{ file2.name }}
</span>
</b-upload>
</b-field>
</b-field>
<b-button v-if="file2" type="is-secondary" #click="upload">Envoyer</b-button>
</div>
<div class="column">
<p class="title">{{ loggedInUser.pseudo }} <b-button #click="modifyPseudo" icon-right="pencil"/> </p><br v-if="!isModifyPseudo">
<form v-if="isModifyPseudo" method="post" #submit.prevent="sendModification">
<b-field label="Nouveau nom d'utilisateur" label-for="newPseudo">
<b-input id="newPseudo" v-model="newPseudo"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Adresse mail : {{ loggedInUser.email }} <b-button #click="modifyMail" icon-right="pencil"/> </p>
<form v-if="isModifyMail" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle adresse mail" label-for="newMail">
<b-input id="newMail" v-model="newMail" type="email"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Nationalité : {{ loggedInUser.nationality }} <b-button #click="modifyNation" icon-right="pencil"/> </p>
<form v-if="isModifyNation" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle nationalité" label-for="newNation">
<b-select expanded v-model="newNation" icon="earth">
<option
v-for="nation in nationalities"
:value="nation.code"
:key="nation.id">
{{ nation.name }}
</option>
</b-select>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
</div>
</div>
</div>
</section>
</template>
<script>
import { mapGetters } from 'vuex'
import countries from '#/assets/countries.json';
export default {
middleware: 'auth',
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser'])
},
data (){
return {
baseURL: 'http://localhost:8000/',
isModifyPseudo: false,
isModifyMail: false,
isModifyNation: false,
newPseudo: '',
newMail: '',
newNation: '',
nationalities: {},
error: '',
file2 : null,
}
},
methods: {
modifyPseudo() {
if(!this.isModifyPseudo){
this.newPseudo='';
}
this.isModifyPseudo = !this.isModifyPseudo;
},
modifyMail() {
if(!this.isModifyMail){
this.newMail='';
}
this.isModifyMail = !this.isModifyMail;
},
modifyNation() {
if(!this.isModifyNation){
this.newNation='';
}
this.isModifyNation = !this.isModifyNation;
},
async upload(){
try{
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
const newPicture = await this.$axios.post('users/' + this.loggedInUser.id + '/picture', formData, {
headers: {'Content-Type': 'multipart/form-data'}
});
console.log(newPicture);
const updatedUser = {...this.$auth.user}
updatedUser.picture = newPicture.data.picture;
this.$auth.setUser(updatedUser)
this.file2 = null;
}catch (error){
//this.error = error.response.data.message;
console.log(error.response);
}
},
async sendModification(){
try{
if(this.isModifyPseudo){
const newPseudo = await this.$axios.put('users/' + this.loggedInUser.id, {
pseudo: this.newPseudo
});
const updatedUser = {...this.$auth.user}
updatedUser.pseudo = newPseudo.data.pseudo;
this.$auth.setUser(updatedUser)
this.newPseudo = '';
this.isModifyPseudo = false;
}
if(this.isModifyMail){
const newMail = await this.$axios.put('users/' + this.loggedInUser.id, {
email: this.newMail
});
const updatedUser = {...this.$auth.user}
updatedUser.email = newMail.data.email;
this.$auth.setUser(updatedUser)
this.newMail = '';
this.isModifyMail = false;
}
if(this.isModifyNation){
const newNation = await this.$axios.put('users/' + this.loggedInUser.id, {
nationality: this.newNation
});
const updatedUser = {...this.$auth.user}
updatedUser.nationality = newNation.data.nationality;
this.$auth.setUser(updatedUser)
this.newNation = '';
this.isModifyNation = false;
}
}catch(error){
this.error = error.response.data.message;
}
}
},
async mounted() {
try {
this.nationalities = countries;
} catch (err) {
throw err;
}
},
}
</script>
<style scoped>
img {
border-radius: 50%;
object-fit: cover;
height: 10em;
width: 10em;
}
.container #center-text {
text-align: center;
}
.file-label strong{
color: white;
}
</style>
And when I click on the send button, because I don't catch the error, it sends the error 500.
EDIT :
So into my upload function into my profile page (called connexion.vue) :
I replace that
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
by this
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
formData.append('folder', 'user');
and into my Controller.php file I replace this :
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
by this
if($folder == 'user'){
$destination_path = storage_path('../public/upload/user/');
//$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = storage_path('../public/upload/article/');
//$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = storage_path('../public/upload/galerie/');
//$destination_path = './upload/galerie/';
}

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> ```

Laravel 8 filter data with ajax

I want to filter the data in my table. I have seen many tutorials online but do not understand. I found a tutorial that seemed very complicated to me. I just want to use a controller and view. Constants are used in that tutorial and the filter data is static but I don't want to use it and my filter data is dynamic. Help me out as a newbie.
The code of the tutorial is given here
app/Constants/GlobalConstants
<?php
namespace App\Constants;
class GlobalConstants {
const USER_TYPE_FRONTEND = "frontend";
const USER_TYPE_BACKEND = "backend";
const ALL = 'All';
const LIST_TYPE = [self::USER_TYPE_FRONTEND, self::USER_TYPE_BACKEND];
const LIST_COUNTRIES = ["Canada", "Uganda", "Malaysia", "Finland", "Spain", "Norway"];
const SALARY_RANGE = ['401762', '85295', '287072', '456969', '354165'];
}
App/User
public static function getUsers($search_keyword, $country, $sort_by, $range) {
$users = DB::table('users');
if($search_keyword && !empty($search_keyword)) {
$users->where(function($q) use ($search_keyword) {
$q->where('users.fname', 'like', "%{$search_keyword}%")
->orWhere('users.lname', 'like', "%{$search_keyword}%");
});
}
// Filter By Country
if($country && $country!= GlobalConstants::ALL) {
$users = $users->where('users.country', $country);
}
// Filter By Type
if($sort_by) {
$sort_by = lcfirst($sort_by);
if($sort_by == GlobalConstants::USER_TYPE_FRONTEND) {
$users = $users->where('users.type', $sort_by);
} else if($sort_by == GlobalConstants::USER_TYPE_BACKEND) {
$users = $users->where('users.type', $sort_by);
}
}
// Filter By Salaries
if ($range && $range != GlobalConstants::ALL) {
$users = $users->where('users.salary', $range);
}
return $users->paginate(PER_PAGE_LIMIT);
}
App/Http/Controllers/HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Constants\GlobalConstants;
class HomeController extends Controller
{
public function index() {
$users = User::getUsers('', GlobalConstants::ALL, GlobalConstants::ALL, GlobalConstants::ALL);
return view('home')->with('users', $users);
}
public function getMoreUsers(Request $request) {
$query = $request->search_query;
$country = $request->country;
$sort_by = $request->sort_by;
$range = $request->range;
if($request->ajax()) {
$users = User::getUsers($query, $country, $sort_by, $range);
return view('pages.user_data', compact('users'))->render();
}
}
}
view code
#foreach($users as $key)
<div class="card">
<div class="card-header">
<img src="{{ asset('assets/images/dev.png') }}" alt="" />
</div>
<div class="card-body">
<span class="tag tag-pink">{{ $key->type }}</span>
<hr>
<span class="tag tag-salary">Salary: {{ $key->salary }}</span>
<h4>{{ $key->email }}</h4>
<p>
{{ $key->address }}
</p>
<h4>Country: {{ $key->country }}</h4>
<div class="user">
#php
$user=App\User::find($key->id)
#endphp
<img src="{{ asset('assets/images/user-3.jpg') }}" alt="" />
<div class="key-info">
<h5>{{ $user['fullname'] }}</h5>
<small>{{ date('d.m.Y H:i:s', strtotime($key->created_at)) }}</small>
</div>
</div>
</div>
</div>
#endforeach
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
getMoreUsers(page);
});
$('#search').on('keyup', function() {
$value = $(this).val();
getMoreUsers(1);
});
$('#country').on('change', function() {
getMoreUsers();
});
$('#sort_by').on('change', function (e) {
getMoreUsers();
});
$('#salary_range').on('change', function (e) {
getMoreUsers();
});
});
function getMoreUsers(page) {
var search = $('#search').val();
// Search on based of country
var selectedCountry = $("#country option:selected").val();
// Search on based of type
var selectedType = $("#sort_by option:selected").val();
// Search on based of salary
var selectedRange = $("#salary_range option:selected").val();
$.ajax({
type: "GET",
data: {
'search_query':search,
'country': selectedCountry,
'sort_by': selectedType,
'range': selectedRange
},
url: "{{ route('users.get-more-users') }}" + "?page=" + page,
success:function(data) {
$('#user_data').html(data);
}
});
}
</script>
public function create(Request $request)
{
$doctors = Doctors::all();
$query = doctors_slots::query();
'services.','consultation.')
// ->get();
if($request->ajax()){
$doctors_slots = $query->where(['doc_id'=>$request->doctors])->get();
return response()->json(compact('doctors_slot'));
}
$doctors_slots = $query->get();
return view('Admin.booking.add_booking',compact('doctors','doctors_slots'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#doctors").on('change', function() {
var doctors = $(this).val();
$.ajax({
url: "{{ route('booking') }}",
type: "GET",
data: {
'doctors': doctors
},
success: function(data) {
var doctors_slots = data.doctors_slots;
var html = '';
if (doctors_slots.length > 0) {
for (let i = 0; i < doctors_slots.length; i++) {
html += '<option value="' + doctors_slots[i][
'available_time_start'
] + '' + doctors_slots[i]['available_time_end'] + '">\
' + doctors_slots[i]['available_time_start'] + ' To\
' + doctors_slots[i]['available_time_end'] + '\
</option>';
}
} else {
html += '<option>No Data Found</option>';
}
$('#option').html(html);
}
});
});
});
</script>

Vue, Laravel Pagination doesn't work well

This is my post page:
<template>
<br/>
<pagination
#pageClicked="getPage($event)"
v-if="this.getdArray.data != null"
:links="this.getdArray.links"
/>
<a
:href="route('create',{region1:this.region})"
class="list-group-item list-group-item-action w-25 float-right text-gray-200 align-text-bottom"
style="background-color: rgb(00, 00, 00)"
>
글작성
<!-- {{ this.getdArray }} -->
</a>
<div v-for="post in this.getdArray.data" :key="post.id">
<a
:href="route('show',{'id': post.id},{region1:this.region})"
class="list-group-item list-group-item-action w-100 float-right text-gray-200 "
style="background-color: rgb(50, 60, 60)"
>
{{post.title}}
</a>
</div>
</template>
<script>
import {InertiaLink} from "#inertiajs/inertia-vue3";
import Pagination from "./Pagination.vue";
export default {
data(){
return{
postdata: []
}
},
methods: {
check(){
console.log(this.postRegion);
},
getPage(url) {
axios
.get(url)
.then((res) => {
this.getdArray = res.data;
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
},
},
props: [
'regionN', 'posts','dArray'
],
data() {
return {region: "", getposts: [],getdArray:[]}
},
beforeMount() {
this.region = this.regionN;
this.getposts = this.posts;
this.getdArray=this.dArray;
// console.log(this.getposts);
console.log(this.region);
console.log(this.getposts);
console.log(this.getdArray);
},
components: {
InertiaLink,
Pagination
},
computed: {
postRegion: function () {
return this
.getposts
.filter((post) => {
if (post.region == this.region) {
return post
}
});
}
//computed 로 필요한 데이터만 반환
//.filter 함수는 배열에 적용가능하며 배열내 각 원소에 적용
}
}
</script>
And this is my pagination page:
<template>
<div v-if="links.length > 3">
<div class="flex flex-wrap -mb-1">
<template v-for="(link, key) in links">
<div
v-if="link.url === null"
:key="key"
class="px-4 py-3 mb-1 mr-1 text-sm leading-4 text-gray-400 border rounded"
v-html="link.label"
/>
<div
v-else
#click="pageClicked(link.url)"
:key="link.url"
class="px-4 py-3 mb-1 mr-1 text-sm leading-4 border rounded hover:bg-white focus:border-indigo-500 focus:text-indigo-500"
:class="{ 'bg-white': link.active }"
:href="link.url"
v-html="link.label"
></div>
</template>
</div>
</div>
</template>
<script>
export default {
props: {
links: Array,
},
methods: {
pageClicked(url) {
this.$emit("pageClicked", url);
},
},
};
</script>
When I push list button,
something like
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title inertia>Laravel</title>
This kind of thing send by res.data
How can I fix it? On other people's code, res.data has data and link,
but on my res.data, HTML code send back.
this is my controller
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Symfony\Component\Console\Input\Input;
class PostController extends Controller
{
// public function index()
// {
// //
// }
public function create(Request $request)
{
$region1 = $request->region1;
return Inertia::render('Create', ["region1" => $region1]);
}
public function store(Request $request)
{
$request->validate([
'title' => 'required|min:3',
'content' => 'required|min:3',
'image' => 'image',
// 'region1' => 'required'
]);
// $user_id = Auth::user()->id;
// $region =
// $request->region1;
$post = new Post();
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->content = $request->content;
//inertia 에서의 post요청
//function storePost() {
//form.post('/post/store')
//}
//와 같이.
$path = $request->file('image')->store('image', 'public');
$imgpath = "/storage/" . $path;
$post->image = $imgpath;
$post->region = $request->region;
$post->save();
// $validated = array_merge($validated, ['image' => $imgpath]);
// $validated = array_merge($validated, ['user_id' => $user_id]);
// $validated = array_merge($validated, ['region' => $region]);
// Post::create($validated);
// if ($request->hasFile('image')) {
// $image_path = $request->file('image')->store('image', 'public');
// }
// $post = new Post();
// $post->title = $request->title;
// $post->content = $request->content;
// $post->user_id = Auth::user()->id;
// $post->region = $request->region;
// $post->image = "/storage/" . $image_path;
// $posts = Post::all();
// $b2018 = DB::table('crimes')->get();
// $t2018 = json_decode(json_encode($b2018), true);
// $region1 = $request->region1;
// $posts = Post::find($post->id);
return Redirect::route('main');
}
public function show($id)
{
$posts = Post::find($id);
return Inertia::render('Show', ["posts" => $posts]);
}
public function edit($id)
{
$post = Post::find($id);
return Inertia::render('Edit', ["post" => $post]);
}
public function update(Request $request, $id)
{
$post = Post::find($id);
$post->title = $request->title;
$post->content = $request->content;
$post->user_id = Auth::user()->id;
if ($request->hasFile('image')) {
$fileName = time() . '_' . $request->file('image')->getClientOriginalName();
$request->file('image')->storeAs('public/images', $fileName);
if ($fileName) {
$input = array_merge($input, ['image' => $fileName]);
}
}
$post->save();
$posts = Post::find($id);
return Inertia::render('Show', ["posts" => $posts]);
}
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
if ($post->image) {
Storage::delete('public/images/' . $post->image);
}
return Inertia::render('question');
}
}
i added my controller, and i tried to fix it but it still sent request twice...
I think problem is in your Laravel back-end or bad request in front-end side, sometime laravel return error in HTML format, if you not defined accept application/json in your request headers.
Try to resolve that problem first, and edit your question.

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 :)))

ajax is not able to call the function of codeigniter

This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing

Resources