Gabotronix

Gabotronix

Member Since 7 Months Ago

Experience Points 11,010
Experience
Level
Lessons Completed 45
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

13 Nov
16 hours ago

Gabotronix started a new conversation Registering Vue Filters In A Js File And Using Them In My App

So I want to have a file where I store various vue filters wich I may or not use in my app but I'm having problems on how to do this since I'm fairly new to vue and import/exports.

I made a filters.js file where I have this:

import Vue from 'vue'


Vue.filter('truncate', function (text, length, suffix) {
    return text.substring(0, length) + suffix;
});

The I have app.js in my laravel project, I bootstrap my client-side in this file.

It lookis like this:

window.Vue = require('vue');
Vue.config.productionTip = false;

Vue.component('admin-panel', require('./components/admin/AdminPanel.vue'));

import store from './store'
import filters from './filters'

const app = new Vue({

    el: '#vueapp',
    store,
    filters,

    created () {
        console.info('VUE INSTANCE MOUNTED');
    },

});

I'm getting the following error message:

 "export 'default' (imported as 'filters') was not found in './filters'

Gabotronix left a reply on Issue With Vue's Dinamic Component

afaik components need to be camelcased so I can't use

Gabotronix left a reply on Issue With Vue's Dinamic Component

Oh yeah thanks for that, however I'm still getting the same error:

[Vue warn]: Unknown custom element: <PostPanel> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

found in

---> <AdminPanel> at resources/js/components/admin/AdminPanel.vue
       <Root>

Gabotronix left a reply on Laravel Not Redirecting Me To Homepage After Axios Login

Since I'm using javascript to send the login request I went with a pure javascript redirect, like this:

login ({ commit }, credentials) {
        console.log( credentials );
        commit( 'SET_LOAD_STATUS', 1);
        axios.post('/login', credentials)
        .then((response) => {
            /*I added this*/
            window.location.href = '/';
            commit( 'SET_LOAD_STATUS', 2 );
        }, 
        (error) => {
            console.log(errors);
            commit( 'SET_LOAD_STATUS', 3 );
            commit( 'RECORD_ERRORS', errors.data.message );
        })
    },

Gabotronix started a new conversation Issue With Vue's Dinamic Component

Hi everybody, I'm making an admin panel for my application using vue, since there are lots of modals and logic in the admin panel I decided to go for vuex and dinamic components.

However I'm getting the following message error when trying to display default dinamic component:

[Vue warn]: Unknown custom element: <PostPanel> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

found in

---> <AdminPanel> at resources/js/components/admin/AdminPanel.vue
       <Root>

This is pretty rare as I registered the component inside app.js imports.

window.Vue = require('vue');
Vue.config.productionTip = false;

Vue.component('admin-panel', require('./components/admin/AdminPanel.vue'));
Vue.component('post-panel', require('./components/admin/PostPanel.vue'));

import store from './store'

const app = new Vue({

    el: '#vueapp',
    store,

    created () {
        console.log('VUE INSTANCE MOUNTED');
    },

});

This is my admin panel where I have the dinamic component:

<template>
<section>
    <div class="body_maincontainer">
        <div class="sidebar_entries_container" :class="{ sidebar_collapsed: sidebarCollapsed === true }">
            <div class="sidebar_entry_container active_entry" title="Contador de visitas">
                <i class="fa far fas fa-chart-line"></i>
                <span>Visitas</span>
            </div>
            <button class="sidebar_entry_container form_show_results" type="button" @click="showPanel('ReviewPanel')" title="Opiniones y reseñas colgadas en la web">
                <i class="fa fas fa-comment"></i>
                <span>Opiniones</span>
            </button>
            <button class="sidebar_entry_container form_show_results" type="button" @click="showPanel('BugPanel')" title="Reporta fallos de la web directamente al autor">
                <i class="fa fas fa-exclamation-triangle"></i>
                <span>Reportar fallos</span>
            </button>
        </div>
        <div class="entries_maincontainer">
            <dinamic-component :is="activePanel"></dinamic-component>
        </div>
    </div>
</section>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default {

name: 'AdminPanel',
  
data: function() {
    return {
            
    };
},

props: {
    allglobals: {required:true}
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
},

computed: {
    ...mapState('AdminPanel', ['activePanel', 'sidebarCollapsed']),
},

methods: {
    ...mapActions('AdminPanel', ['showPanel', 'toggleSidebar']),
}
};
</script>
<!--STYLES-->
<style scoped>
.sidebar_collapsed{}
</style>

And this is my vuex AdminPanel module, inside here I have an activePanel property wich is the name of the component I want to selectively render:


//STATE
const state = {
    activePanel: 'PostPanel',
    sidebarCollapsed: false
}

//GETTERS
const getters = {

}

//ACTIONS
const actions = {


    showPanel({ commit }, panel) {
        
        commit( 'SHOW_PANEL', {panel: panel} );
    },

    toggleSidebar({ commit }) {
        
        commit( 'TOGGLE_SIDEBAR' );
    },


}

//MUTATIONS
const mutations = {

    SHOW_PANEL (state, panel) {
        state.activePanel = panel;
    },

    TOGGLE_SIDEBAR (state) {
        state.sidebarCollapsed = !state.sidebarCollapsed;
    },

}

export default {
  namespaced: true, state, getters, actions, mutations
}

Any help appreciated!

12 Nov
1 day ago

Gabotronix started a new conversation Laravel Not Redirecting Me To Homepage After Axios Login

Hi everybody, I'm using laravel's auth system for my laravel-vue application (via auth:make cli).

How I login works is via post axios call to laravel's login route, and this works wel (I get logged in) but I don't get redirected back to homepage after login in.

This is my vue component:

<template>
<form class="auth_modal_maincontainer">
    <h1 class="auth_modal_title">INICIAR SESIÓN</h1>
    <span class="horizontal_centered_gradient_line"></span>
    <div class="auth_modal_inputs_maincontainer">
        <div class="auth_modal_inputs_column_container">
            <div class="auth_modal_inputs_container">
                <div class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fa fa-user"></i>
                </div>
                <input class="auth_modal_inputs_input" id="email" name="email" v-model="credentials.email" type="email" placeholder="EMAIL" required autofocus>
            </div>
        </div>
        <div class="auth_modal_inputs_column_container">
            <div class="auth_modal_inputs_container">
                <div class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fa fa-lock"></i>
                </div>
                <input class="auth_modal_inputs_input" id="password" name="password" v-model="credentials.password" type="password" placeholder="CONTRASEÑA" required>
            </div>
        </div>
        <div class="auth_modal_row_container">
            <input class="auth_modal_row_checkbox" name="remember" v-model="credentials.remember" type="checkbox">
            <span class="auth_modal_row_text">Recordarme</span>
        </div>
        <div class="auth_modal_errors_container">
            <div class="auth_modal_errors_error_container" v-for="(error, index) in errors" :key="index">
                <i class="auth_modal_errors_error_icon fa fa-exclamation"></i>
                <span class="auth_modal_errors_error_message">Hay errores:</span>
            </div>
        </div>
    </div>
    <span class="horizontal_centered_gradient_line"></span>
    <div class="auth_modal_buttons_container">
        <button class="auth_modal_buttons_button boot_green" @click="onGetLoginData()" type="button"><i class="auth_modal_buttons_button_icon fas fa-sign-in-alt"></i>INICIAR</button>
        <a class="auth_modal_buttons_button boot_red" href="/"><i class="auth_modal_buttons_button_icon fas fa-times"></i>CANCELAR</a>
    </div>
</form>
</template>
<style scoped>
</style>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default
{

name: 'LoginForm',
data: function () {
    return {
        credentials: {
            email: '',
            password: '',
            remember: '',
      },
    }
},

computed: {
    ...mapState('Auth', ['errors']),
},

mounted () {
    console.log(this.$options.name+' component successfully mounted');
},

methods:{
    ...mapActions('Auth', ['login']),

    onGetLoginData() {

        this.login(this.credentials);
    },
    
      
}
}
</script>
<!--STYLES-->


And my auth module form where I post to the route:

import axios from 'axios' //STATE const state = { errors: [], loadingStatus:0, }

//GETTERS const getters = {

}

//ACTIONS const actions = {

login ({ commit }, credentials) {
    console.log( credentials );
    commit( 'SET_LOAD_STATUS', 1);
    axios.post('/login', credentials)
    .then((response) => {
        commit( 'SET_LOAD_STATUS', 2 );
    }, 
    (error) => {
        console.log(errors);
        commit( 'SET_LOAD_STATUS', 3 );
        commit( 'RECORD_ERRORS', errors.data.message );
    })
},


logout ({ commit }) {

    commit( 'SET_LOAD_STATUS', 1);
    axios.post('/logout')
    .then((response) => {
        commit( 'SET_LOAD_STATUS', 2 );
    }, 
    (error) => {
        console.log(error);
        commit( 'SET_LOAD_STATUS', 3 );
    })
},


register ({ commit }, email, password, password_confirmation, remember) {

    commit( 'SET_LOAD_STATUS', 1);
    axios.post('/register', { email:email, password:password, password_confirmation:password_confirmation })
    .then((response) => {
        commit( 'SET_LOAD_STATUS', 2 );
    }, 
    (error) => {
        console.log(error);
        commit( 'SET_LOAD_STATUS', 3 );
    })
},

}

//MUTATIONS const mutations = {

SET_LOAD_STATUS (state, status) {
    state.loadingStatus = status;
},

RECORD_ERRORS (state, errors) {
    state.errors.length = 0;
    state.errors.push(errors);
},

CLEAR_ERRORS (state) {
    state.errors.length = 0;
},

}

export default { namespaced: true, state, getters, actions, mutations }


I have this in my LoginController:
```php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

Interestingly if I use a laravel's blade login page I DO get redirected to homepage

Gabotronix started a new conversation Vuex Persisted State Not Persisted

Hi I'm using vuex plugin along with js-cookie to make a simple cookie consent modal work, since I'm testing it what I do is make the cookiesAccepted cookie expire after 60 seconds, however after I accept cookies I refresh the tab and the cookie consent modal is there again.

What am I doing wrong?

This is my CookieModal component:

<template>
<transition name="cookie-fade">
<section class="cbanner_simp_maincontainer" v-if="cookiesAccepted == false">
    <p class="cbanner_simp_paragraph">Esta página utiliza cookies propias para ofrecer una mejor experiencia en nuestra web.</p>
    <button class="cbanner_simp_button" type="button" @click="acceptCookies()">
        <span class="cbanner_simp_button_text">ACEPTAR</span>
    </button>
</section>
</transition>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default
{

name: 'CookieModal',
data: function () {
    return {
    }
},

computed: {
    ...mapState('CookieModal', ['cookiesAccepted']),
},

mounted () {
    console.log(this.$options.name+' component successfully mounted');
},

methods:{

    ...mapActions('CookieModal', ['acceptCookies']),
 
}
}
</script>

This is my CookieModal vuex store module:


//STATE
const state = {
    cookiesAccepted: false
}

//GETTERS
const getters = {

}

//ACTIONS
const actions = {

    acceptCookies({commit}){
        console.log('cookies_accepted');
        commit('ACCEPT_COOKIES');

    },

}

//MUTATIONS
const mutations = {

    ACCEPT_COOKIES(state,) {
        state.cookiesAccepted = true;
    },

}

export default {
  namespaced: true, state, getters, actions, mutations
}

As you can see, pretty simple.

Now in my index.js file inside store is where I use the vuex-persistedstate plugin along with js-cookie to make acceptedCookies = true.

/*
|-------------------------------------------------------------------------------
| VUEX store.js
|-------------------------------------------------------------------------------
*/

//Builds the data store from all of the modules for the app.
//Adds the promise polyfill for IE 11
//require('es6-promise').polyfill();

//Imports Vue and Vuex
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

//Initializes Vuex on Vue as a plugin
Vue.use( Vuex )

//Imports all of the modules used in the application to build the data store.
import Auth from './modules/Auth.js';
import Reviews from './modules/Reviews.js';
import Globals from './modules/Globals.js';
import Bulletins from './modules/Bulletins.js';
import Contacts from './modules/Contacts.js';
import Bugs from './modules/Bugs.js';
import Schedules from './modules/Schedules.js';
import MainSlider from './modules/MainSlider.js';
import Posts from './modules/posts/Posts.js';
import PostBottombarList from './modules/posts/PostBottombarList.js';
import PostSidebarList from './modules/posts/PostSidebarList.js';
import PopUpModal from './modules/modals/PopUpModal.js';
import PopUpForm from './modules/modals/PopUpForm.js';
import MainModal from './modules/modals/MainModal.js';
import CookieModal from './modules/modals/CookieModal.js';
import AdminPanel from './modules/AdminPanel.js';


//Exports our data store.
export default new Vuex.Store({
    strict: true, //debug
    
    modules: { 
        Auth,
        AdminPanel,
        Globals,
        Posts,
        PostSidebarList,
        PostBottombarList,
        PopUpModal, 
        PopUpForm,
        MainModal, 
        CookieModal,
        Reviews, 
        Bulletins, 
        Contacts, 
        Bugs, 
        Schedules, 
        MainSlider,
        
    },

    plugins: [
        createPersistedState({
            paths: ['CookieModal'],
            storage: {
                getState: (key) => Cookies.getJSON(key), 
                setItem: (key, value) => Cookies.set(key, value, { expires: new Date(new Date().getTime() + 1 * 60 * 1000), secure: false }),
                removeItem: key => Cookies.remove(key),
            },
        }),

        createPersistedState({
            paths: ['PopUpForm'],
            storage: {
                getState: (key) => Cookies.getJSON(key), 
                setItem: (key, value) => Cookies.set(key, value, { expires: new Date(new Date().getTime() + 1 * 60 * 1000), secure: false }),
                removeItem: key => Cookies.remove(key),
            },
        }),
    ],
});

Please help I'm stuck here.

10 Nov
3 days ago

Gabotronix started a new conversation Vue: Vuex Action Not Receiving Login Parameters

Hi everybody, I created a login form vue component, on this component I gather login credentails wich are sent to a login vuex action inside my Auth module, there I make an axios post call to/login ( I'm using laravel's make:auth ).

However there's a problem, my login credentials aren't being sent as arguments to my login action (I think).

My LoginForm component:

<template>
<form class="auth_modal_maincontainer">
    <h1 class="auth_modal_title">INICIAR SESION</h1>
    <span class="horizontal_centered_gradient_line"></span>
    <div class="auth_modal_inputs_maincontainer">
        <div class="auth_modal_inputs_column_container">
            <div class="auth_modal_inputs_container">
                <div class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fa fa-user"></i>
                </div>
                <input class="auth_modal_inputs_input" name="email" type="email" placeholder="EMAIL" required autofocus>
            </div>
        </div>
        <div class="auth_modal_inputs_column_container">
            <div class="auth_modal_inputs_container">
                <div class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fa fa-lock"></i>
                </div>
                <input class="auth_modal_inputs_input" name="password" type="password" placeholder="CONTRASEÑA" required>
            </div>
        </div>
        <div class="auth_modal_row_container">
            <input class="auth_modal_row_checkbox" name="remember" type="checkbox">
            <span class="auth_modal_row_text">Recordarme</span>
        </div>
        <div class="auth_modal_errors_container">
            <div class="auth_modal_errors_error_container" v-for="(error, index) in errors" :key="index">
                <i class="auth_modal_errors_error_icon fa fa-exclamation"></i>
                <span class="auth_modal_errors_error_message">Hay errores:</span>
            </div>
        </div>
    </div>
    <span class="horizontal_centered_gradient_line"></span>
    <div class="auth_modal_buttons_container">
        <button class="auth_modal_buttons_button boot_green" @click="onGetLoginData()" type="button">INICIAR</button>
        <a class="auth_modal_buttons_button boot_red" href="/">CANCELAR</a>
    </div>
</form>
</template>
<style scoped>
</style>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default
{

name: 'LoginForm',
data: function () {
    return {
        email: '',
        password: '',
        remember:''
    }
},

computed: {
    ...mapState('Auth', ['errors']),
},

mounted () {
    console.log(this.$options.name+' component successfully mounted');
},

methods:{
    ...mapActions('Auth', ['login']),

    onGetLoginData() {

        this.login(this.name, this.password, this.remember);
    },
    
    onReset() {

        this.email = '';
        this.password = '';
        this.remember = '';
    }
      
}
}
</script>
<!--STYLES-->


My login action inside Auth vuex module.

login ({ commit }, email, password, remember) {
        console.log(email, password, remember);
        commit( 'SET_LOAD_STATUS', 1);
        axios.post('/login', { email:email, password:password, remember:remember })
        .then((response) => {
            commit( 'SET_LOAD_STATUS', 2 );
        }, 
        (error) => {
            console.log(error);
            commit( 'SET_LOAD_STATUS', 3 );
        })
    },
09 Nov
4 days ago

Gabotronix started a new conversation Vue Component Not Rendering Because Data (via Prop) Is Null

Hi everybody, I have this vue header component wich will render (or not) login leaks if the client is authenticated.

However there's an issue, since loggedUser is null (when no user is logged) the component won't render at all and I get a console warning that loggedUser is "null". If I login the component renders since I can access loggedUser name or email.

I get loggedUser object from laravel backend, then I pass it as a PROP to header component, wich doesn't render when there's no logged user...

<template>
<header class="header_maincontainer">
    <div class="header_small_container">
        <div class="header_small_contact_container" style="">
            <span class="header_small_text1">Llamanos al: </span>
            <i class="header_small_phone_icon fa fa-phone"></i>
            <a class="header_small_phone_number" :href="'tel:+34' + allglobals.globals.bookingPhone">{{ allglobals.globals.bookingPhone }}</a>
        </div>
        <div class="header_small_social_container" style="">
            <a v-if="allglobals.socialLinks.twitter !== ''" :href="allglobals.socialLinks.twitter" target="_blank" class="header_small_social_icon"><i class="fab fa-twitter header_fa"></i></a>
            <a v-if="allglobals.socialLinks.facebook !== ''" :href="allglobals.socialLinks.facebook" target="_blank" class="header_small_social_icon"><i class="fab fa-facebook header_fa"></i></a>
            <a v-if="allglobals.socialLinks.instagram !== ''" :href="allglobals.socialLinks.instagram" target="_blank" class="header_small_social_icon"><i class="fab fa-instagram header_fa"></i></a>
        </div>
        <a class="header_small_auth_container" href="/login" v-if="allglobals.loggedUser.email == ''">
            <div class="header_small_login_icon"><i class="fa fa-user header_fa"></i></div>
            <span class="header_small_login_text" title="Iniciar sesión">Iniciar</span>
        </a>
        <div class="header_small_auth_container" v-if="allglobals.loggedUser.email !== ''">
            <a v-if="allglobals.loggedUser.isAdmin" href="/panel-administrador" class="header_small_mail_icon"><i class="fa fa-cog header_fa"></i></a>
            <a href="" class="header_small_login_icon"><i class="fa fa-sign-out header_fa"></i></a>
            <a v-if="allglobals.loggedUser.email !== ''" href="/logout" class="header_small_login_text" title="Cerrar sesión">Salir</a>
        </div>
    </div>
    <div class="header_big_container">
        <div class="header_big_logo_container">
            <a class="header_big_logo_link_wrapper" href="/" :title="'Página de inicio de ' + allglobals.globals.appName" style="background-image:url('/img/logo_yellow.png');"></a>
        </div>
        <div class="header_big_texts_container">
            <span class="header_big_texts_3">Adiestramiento Canino a Domicilio en Málaga, Costa de Málaga e Interiores</span>
            <span class="header_big_texts_2">Tus especialistas en comportamiento canino</span>
            <a class="header_big_texts_phone" :href="'tel:+34' + allglobals.globals.bookingPhone">{{ allglobals.globals.bookingPhone }}</a>
        </div>
    </div>
</header>
</template>
<!--SCRIPTS-->
<script>
export default {
name: 'MainHeader',

props: {
    allglobals: {required:true}
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
},

};
</script>
<!--STYLES-->
<style scoped>

</style>

I load loggedUser with a view composer in laravel backend:

public function compose(View $view)
    {

        $globals = Globals::all()->pluck('value', 'name'); 

        $socialLinks = [
            
            'twitter' => config('globals.twitter'),
            'facebook' => config('globals.facebook'),
            'instagram' => config('globals.instagram'),

        ];

        $layoutLinks = [
            
            'classPosts' => Post::withCategory('Clases')->take(10)->get(),
            'behaviourPosts' => Post::withCategory('Conducta canina')->take(10)->get(),
            'trainingPosts' => Post::withCategory('Formación')->take(10)->get(),

        ];

        $loggedUser = Auth::user();

        $allGlobals = compact('globals', 'socialLinks', 'layoutLinks', 'loggedUser');
        //dd($allGlobals);

        $view->with('allGlobals', $allGlobals);
    }

Any idea how to fix this...

08 Nov
5 days ago

Gabotronix started a new conversation Vue: <transition-group> Children Must Be Keyed

So I'm making a custom vue info slider and I'm getting the following error in the console:

[Vue warn]: <transition-group> children must be keyed: <div>

This is my component:

<template>
<section class="slider_maincontainer">
    <transition-group name="slider-fade">
        <div class="slider_item" v-show="activeSlider===1" style="background-color:red;">
            <!--slider content-->
        </div>
        <div class="slider_item" v-show="activeSlider===2" style="background-color:blue;">
            <!--slider varied content-->
        </div>
        <div class="slider_item" v-show="activeSlider===3" style="background-color:green;">
            <!--another slider-->
        </div>
    </transition-group>
    <button class="slider_buttom_prev" @click="prevSlider()">
        <i class="slider_buttom_icon fas fa-angle-left"></i>
    </button>
    <button class="slider_buttom_next" @click="nextSlider()">
        <i class="slider_buttom_icon fas fa-angle-right"></i>
    </button>
    <div class="slider_dots_container">
        <span class="slider_dots_dot" :class="{'activeDotClass':index === activeSlider-1}" v-for="(slider, index) in slidersCount" :key="index" @click="goToSlider(index+1)"></span>
    </div>
</section>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'MainSlider',

computed:{
    ...mapState('Slider', ['activeSlider', 'slidersCount']),
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
    this.startSlider();
    console.log('slider_started');
},

methods:{
    ...mapActions('Slider', ['nextSlider', 'prevSlider', 'startSlider', 'goToSlider']),
}
};
</script>
<!--STYLES-->
<style scoped>

</style>

Why am I getting this error? the children inside my transition group are not from a v-for list.

Gabotronix started a new conversation Babel Dinamic Import Plugin Not Working?

Hi, I installed babel's dinamic import plugin in order to async load components, afaik this will avoid loading vue components that are not needed .

After installing the dinamic imports plugin I created a babelrc file in my laravel's root folder and added this:

{
  "presets": [
    "env"
  ],
  "plugins": [
    "dynamic-import-node"
  ]
}

Then in my app.js file I put this :

const MainHeader = () => import('./components/headers/MainHeader.vue');

however my header component is not rendering, any idea what I'm doing wrong?

Gabotronix left a reply on Vue: Add Css Class On Click To Non-dinamic Navbar

Awesome, JQuery can really be amazing

07 Nov
6 days ago

Gabotronix started a new conversation Vue: Add Css Class On Click To Non-dinamic Navbar

I have a vue navbar component, when a node with nav_link is clicked I want to give that node the active class and remove it from the previous active link.

I'm scratching my head as to how to do this with vue without plaguing my component with @clicks wich doesn't seem very DRY

Here is my component:

<template>
<nav class="nav_maincontainer" style="">
    <div class="nav_menu_toggle" onclick="">
        <span class="nav_menu_text">Menu</span>
        <i class="fa fa-bars"></i>
    </div>
    <a class="nav_link" href="/" title="Página de inicio" style="margin-righ:auto;">Inicio</a>
    <div class="nav_dropdown" style="">
        <div class="nav_link" href="/clases" title="">Clases 
            <i class="fa fa-caret-down" style=""></i>
        </div>
        <div class="nav_dropdown_contents" style="">
            <a class="nav_dropdown_link" v-for="classPost in allglobals.layoutLinks.classPosts" :key="classPost.id" :href="'/clases/' + classPost.slug">{{ classPost.title }}</a>
            <a class="nav_dropdown_link" href="/clases/clases-adiestramiento-canino-por-skype">Clases por Skype<i class="nav_dropdown_link_icon fab fa-skype" style=""></i></a>
        </div>
    </div>
    <div class="nav_dropdown" style="">
        <div class="nav_link" href="/clases" title="">Conducta canina 
            <i class="fa fa-caret-down" style=""></i>
        </div>
        <div class="nav_dropdown_contents" style=""> 
            <a class="nav_dropdown_link" v-for="behaviourPost in allglobals.layoutLinks.behaviourPosts" :key="behaviourPost.id" :href="'/conducta-canina/' + behaviourPost.slug">{{ behaviourPost.title }}</a>
        </div>
    </div>
    <a class="nav_link" href="/quienes-somos">Quienes somos</a>
    <div class="nav_dropdown" style="">
        <div class="nav_link" href="/formate-con-nosotros">Formación 
            <i class="fa fa-caret-down" style=""></i>
        </div>
        <div class="nav_dropdown_contents" style="">
            <a class="nav_dropdown_link" v-for="trainingPost in allglobals.layoutLinks.trainingPosts" :key="trainingPost.id" :href="'/formate-con-nosotros/' + trainingPost.slug">{{ trainingPost.title }}</a>
        </div>
    </div>
    <a class="nav_link" href="/contactar" style="">Contactar</a>
    <a class="nav_link" href="/testimonios-de-nuestros-clientes" style="">Testimonios</a>
    <a class="nav_link" href="/preguntas-y-respuestas" style="">FAQ</a>
</nav>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default
{

name: 'MainNav',

props: {
    allglobals: {required:true}
},

data: function () {
    return {

    }
},

computed: {
    
},

mounted () {
    console.log(this.$options.name+' component successfully mounted');
},

methods:{

    
    
    
}
}
</script>
<!--STYLES-->
<style scoped>
</style>

Any suggestions?

Gabotronix started a new conversation Applying Css Class If Condition Is Met

Hi everybody, I'm making a custom image slider using vuex, I want to apply a specific class to the dots used for navigating the sliders, so if the dot is active it will be applied a dotActive class. I want to use activeSlider variable for this

This is the slider component:

<template>
<section class="slider_maincontainer">
    <transition-group name="slider-fade">
        <div class="slider_item" v-show="activeSlider===1" style="background-color:red;">
            <!--slider content-->
        </div>
        <div class="slider_item" v-show="activeSlider===2" style="background-color:blue;">
            <!--slider varied content-->
        </div>
        <div class="slider_item" v-show="activeSlider===3" style="background-color:green;">
            <!--another slider-->
        </div>
    </transition-group>
    <button class="slider_buttom_prev" @click="prevSlider()">
        <i class="slider_buttom_icon fas fa-angle-left"></i>
    </button>
    <button class="slider_buttom_next" @click="nextSlider()">
        <i class="slider_buttom_icon fas fa-angle-right"></i>
    </button>
    <div class="slider_dots_container">
    <!--how to apply custom class to this dot depending of activeIndex
        <span class="slider_dots_dot" v-for="slider in slidersCount" :key="slider" @click="goToSlider(slider)"></span>
    </div>
</section>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'MainSlider',

computed:{
    ...mapState('MainSlider', ['activeSlider', 'slidersCount']),
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
    this.startSlider();
},

methods:{
    ...mapActions('MainSlider', ['nextSlider', 'prevSlider']),
}
};
</script>

And my Slider Store:


//STATE
const state = {
  slidersCount: 3,
  sliderInterval: 3000,
  activeSlider: 1,

}

//GETTERS
const getters = {

}

//ACTIONS
const actions = {


    prevSlider ({ commit, state }) {
        if(state.activeSlider == 1){
            commit( 'TO_LAST_SLIDER' );
        }
        else{
            commit( 'PREV_SLIDER' );
        }
    },


    nextSlider ({ commit, state }) {
        if(state.activeSlider == state.slidersCount){
            commit( 'TO_FIRST_SLIDER' );
        }
        else{
            commit( 'NEXT_SLIDER' );
        }
    },


    goToSlider ({ commit, sliderIndex }) {
        commit('GO_TO_SLIDER', sliderIndex)
        
    },



}

//MUTATIONS
const mutations = {


    PREV_SLIDER (state) {
        state.activeSlider--;
    },

    NEXT_SLIDER (state) {
        state.activeSlider++;
    },

    GO_TO_SLIDER (state, sliderIndex) {
        state.activeSlider = sliderIndex;
    },

    TO_FIRST_SLIDER (state) {
        state.activeSlider = 1;
    },

    TO_LAST_SLIDER (state) {
        state.activeSlider = state.slidersCount;
    },


}

export default {
    namespaced: true, state, getters, actions, mutations
  }

I know this could be made easier if each dom slider where associated with an object along with using a v-for but afaik I can't do that with raw dom element, I'm not getting the slider images from backend or anything.

06 Nov
1 week ago

Gabotronix started a new conversation View Composer:sharing Data With All Views Like

Hi, so I was wondering about this.

If I have two folders inside views like this:

auth --login --register --logout

posts --best posts --by categories

Is there a better syntax to share $data with all auth views , instead of going one by one like this

View::composer(
    ['auth.login', 'auth.register', 'auth.logout'],
    'App\Http\ViewComposers\MyViewComposer'
);

Would something like this even work?

View::composer(
    ['auth.*'],
    'App\Http\ViewComposers\MyViewComposer'
);

Gabotronix left a reply on Axios GET Call Returning 200 Status But No Response

So I just got this working by changing the axios get call to a post call, same with the route, any idea why did this work???

from:

axios.get('/globals/get-logged-user')

and

Route::get('/globals/get-logged-user','[email protected]');

to:

axios.post('/globals/get-logged-user')

and

Route::post('/globals/get-logged-user','[email protected]');

Gabotronix left a reply on Axios GET Call Returning 200 Status But No Response

uhmmm, could you provide a simple example of what you are suggesting me?

Gabotronix started a new conversation Axios GET Call Returning 200 Status But No Response

I'm trying to get current authenticated user (if exists) for my Header vue component, I'm also using vuex store modules to keep my code organized and decoupled.

The proccess goes like this:

When the header component is mounted() I dispatch the action getLoggedUser.

Now inside the Globals store I make axios get call to route /globals/get-logged-user

If the call is succesfull I update the state, now my Header component should be able to access thelogged user data with the help of mapState vuex helper.

Now what actually happens:

The axios get call is done, it returns a positive 200 status code but the response is blank, nothing gets sent back from the backend.

This is my network tab:

https://i.imgur.com/hlD9bAY.png

As you can see the other ajax requests return actual data but the get call returns nothing, I also noticed the type of the GET call is html, could it be this?

Now for my component:

<template>
<header class="header_maincontainer">
    <div class="header_small_container">
         <span>{{ loggedUser.email }}</span>   
    </div>
</header>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'MainHeader',
computed: {
    
    //...mapState('Globals', ['allGlobals', 'loggedUser', 'globals']),
    ...mapState('Globals', [ 'loggedUser']),
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
    this.getLoggedUser();
},

methods:{
    //component actions declaration
    ...mapActions('Globals', ['getLoggedUser']),
  
}
};
</script>
<!--STYLES-->
<style scoped>

</style>

My Globals store:

import axios from 'axios'

//STATE
const state = {
    
    loggedUser:'',
    
    loadingStatus:0
}

//GETTERS
const getters = {




}

//ACTIONS
const actions = {

    

    
    getLoggedUser ({ commit }) {

        commit( 'SET_LOAD_STATUS', {status: 1} );
        axios.get('/globals/get-logged-user')
        .then((response) => {
            commit('GET_LOGGED_USER', { loggedUser: response.data.loggedUser })
            console.log(response.data.loggedUser);
            commit( 'SET_LOAD_STATUS', {status: 2} );
        },
        (error) => {
            console.log(error);
            commit( 'SET_LOAD_STATUS', {status: 3} );
        })
    },


    

}

//MUTATIONS
const mutations = {

    
    GET_LOGGED_USER (state, loggedUser) {
        state.loggedUser = loggedUser;
    },

  

}

export default {
  namespaced: true, state, getters, actions, mutations
}

And my laravel backend:

<?php

namespace App\Http\Controllers;

use App\Models\Globals;
use Illuminate\Http\Request;

class GlobalsController extends Controller
{
    
    


    public function getLoggedUser(){

        $loggedUser = Auth::user();

        dd($loggedUser);
    
        return response()->json([
        
            'loggedUser' => $loggedUser

        ]);

    }


   
}

Please help me, I'm still stuck with this after all these days.

03 Nov
1 week ago

Gabotronix left a reply on Laravel & Vue: Getting Blank Response From Axios Call

So I added some more console loging to the getAllGlobals action, like this:

getAllGlobals ({ commit }) {

        commit( 'SET_LOAD_STATUS', {status: 1} );
        console.log('fetching_all_globals');
        axios.get('/globals/get-all-globals')
        .then((response) => {
            commit('GET_ALL_GLOBALS', { allGlobals: response.data.allGlobals })
            console.log('fetching_done');
            console.log(response.data.allGlobals);
            commit( 'SET_LOAD_STATUS', {status: 2} );
        }, 
        (error) => {
            console.log(error);
            commit( 'SET_LOAD_STATUS', {status: 3} );
        })
    },

and I get "undefined" after "done fetching" log...

Gabotronix started a new conversation Laravel & Vue: Getting Blank Response From Axios Call

I'm trying to grab some global variables for my Header vue component, I'm also using vuex store modules to keep my code organized and decoupled.

The proccess goes like this:

  1. When the header component is mounted() I dispatch the action getAllGlobals.

  2. Now inside the Globals store I make axios get call to route /globals/get-all-globals

  3. If the call is succesfull I update the state, now my Header component should be able to access the globals variables with the help of mapState vuex helper.

NOW WHAT ACTUALLY HAPPENS:

In my console I get vm.globals is undefined, I also inspect network tab and see that while I get 200 status the response is blank, nothing gets sent back.

Now for my code, here is my header component:

<template>
<header class="header_maincontainer">
    <div class="header_small_container">
        <div class="header_small_contact_container" style="">
            <span class="header_small_text1">Llamanos al: </span>
            <i class="header_small_phone_icon fa fa-phone"></i>
            <a class="header_small_phone_number" href="" >{{ globals.bookingPhone }}</a>
        </div>
    </div>
</header>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'MainHeader',
computed: {
    
    ...mapState('Globals', ['allGlobals', 'loggedUser', 'globals']),
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
    this.getAllGlobals();
},

methods:{
    //component actions declaration
    ...mapActions('Globals', ['getAllGlobals']),
  
}
};
</script>

Now this is my Globals module in my vuex store:

import axios from 'axios'

//STATE
const state = {
    allGlobals: [],
    globals: [],
    loggedUser:'',
    layoutLinks: [],
    socialLinks: [],
    loadingStatus:0
}

//GETTERS
const getters = {




}

//ACTIONS
const actions = {

    getAllGlobals ({ commit }) {

        commit( 'SET_LOAD_STATUS', {status: 1} );
        console.log('fetching_all_globals');
        axios.get('/globals/get-all-globals')
        .then((response) => {
            commit('GET_ALL_GLOBALS', { allGlobals: response.data.allGlobals })
            commit( 'SET_LOAD_STATUS', {status: 2} );
        }, 
        (error) => {
            console.log(error);
            commit( 'SET_LOAD_STATUS', {status: 3} );
        })
    },


}

//MUTATIONS
const mutations = {

    GET_ALL_GLOBALS (state, allGlobals) {
        state.allGlobals = allGlobals;
        state.globals = allGlobals.globals;
        state.loggedUser = allGlobals.loggedUser;
        state.layoutLinks = allGlobals.layoutLinks;
        state.socialLinks = allGlobals.socialLinks;
    },


}

export default {
  namespaced: true, state, getters, actions, mutations
}

And this is my GlobalsController in Laravel backend, this function gets called from the /globals/get-all-globals route.

public function getAllGlobals(){

        $globals = Globals::all()->pluck('name', 'value', 'intValue'); 

        $socialLinks = [
            
            'twitter' => config('globals.twitter'),
            'facebook' => config('globals.facebook'),
            'instagram' => config('globals.instagram'),

        ];

        $layoutLinks = [
            
            'classPosts' => Post::withCategory('Clases')->take(10)->get(),
            'behaviourPosts' => Post::withCategory('Conducta canina')->take(10)->get(),
            'trainingPosts' => Post::withCategory('Formación')->take(10)->get(),

        ];

        $loggedUser = Auth::user();

        $allGlobals = compact('globals', 'socialLinks', 'layoutLinks', 'loggedUser');

        //return dd($allGlobals);

        return response()->json([
        
            'allGlobals' => $allGlobals

        ]);


    }

I have been stuck with this issue for 3 days please someone help me.

01 Nov
1 week ago

Gabotronix started a new conversation Issue When Retrieving Global Variables With Axios And Vuex

Hi everybody, my header component makes an ajax call on mounted hook, then in my laravel's GlobalsController I retrieve all the info and send it back to vue component, I'm using vuex to keep my code more organized.

Currently my globals, loggedUser and socialLinks variables appear all undefined!

So this is my Header component:

<template>
<header class="header_maincontainer">
    <div class="header_small_container">
        <div class="header_small_contact_container" style="">
            <span class="header_small_text1">Llamanos al: </span>
            <i class="header_small_phone_icon fa fa-phone"></i>
            <a class="header_small_phone_number" href="" >{{ globals.bookingPhone }}</a>
            <div class="header_small_social_container" style="">
                <a v-if="socialLinks.twitter != ''" :href="'${socialLinks.twitter}'" target="_blank" class="header_small_social_icon"><i class="fa fa-twitter header_fa"></i></a>
                <a v-if="socialLinks.facebook != ''" :href="'${socialLinks.facebook}'" target="_blank" class="header_small_social_icon"><i class="fa fa-facebook header_fa"></i></a>
                <a v-if="socialLinks.instagram != ''" :href="'${socialLinks.instagram}'" target="_blank" class="header_small_social_icon"><i class="fa fa-instagram header_fa"></i></a>
            </div>
            <a class="header_small_auth_container" href="/login" v-if="loggedUser == ''">
                <div class="header_small_login_icon"><i class="fa fa-user header_fa"></i></div>
                <span class="header_small_login_text" title="Iniciar sesión">Iniciar</span>
            </a>
            <div class="header_small_auth_container" v-if="loggedUser != ''">
                <a href="/panel-administrador" class="header_small_mail_icon"><i class="fa fa-cog header_fa"></i></a>
                <a href="" class="header_small_login_icon"><i class="fa fa-sign-out header_fa"></i></a>
                <a href="/logout" class="header_small_login_text" title="Cerrar sesión">Salir</a>
            </div>
        </div>
    </div>
    <div class="header_big_container">
        <div class="header_big_logo_container">
            <a class="header_big_logo_link_wrapper" href="/" title="'Página de inicio de ${globals.bookingPhone}'" style="background-image:url('/img/logo_yellow.png');"></a>
        </div>
        <div class="header_big_texts_container">
            <span class="header_big_texts_3">Adiestramiento Canino a Domicilio en Málaga, Costa de Málaga e Interiores</span>
            <span class="header_big_texts_2">Tus especialistas en comportamiento canino</span>
            <a class="header_big_texts_phone" :href="'tel:${globals.bookingPhone}'">{{ globals.bookingPhone }}</a>
        </div>
    </div>
</header>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'MainHeader',
computed: {
    
    ...mapState('Globals', ['socialLinks', 'loggedUser', 'globals']),
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
    this.getAllGlobals();
},

methods:{
    //component actions declaration
    ...mapActions('Globals', ['getAllGlobals']),
  
}
};
</script>
<!--STYLES-->
<style scoped>

</style>

when mounted, the action getAllGlobals is dispatched to the vuex store Globals module:

import axios from 'axios'

//STATE
const state = {
    allGlobals: [],
    globals: [],
    loggedUser:'',
    layoutLinks: [],
    socialLinks: [],
    loadingStatus:0
}

//GETTERS
const getters = {




}

//ACTIONS
const actions = {

    getAllGlobals ({ commit }) {

        commit( 'SET_LOAD_STATUS', {status: 1} );
        console.log('fetching_all_globals');
        axios.get('/globals/all')
        .then((response) => {
            commit('GET_ALL_GLOBALS', { allGlobals: response.data.allGlobals })
            commit( 'SET_LOAD_STATUS', {status: 2} );
        }, 
        (error) => {
            console.log(error);
            commit( 'SET_LOAD_STATUS', {status: 3} );
        })
    },
}

const mutations = {

    GET_ALL_GLOBALS (state, allGlobals) {
        state.allGlobals = allGlobals;
        state.globals = allGlobals.globals;
        state.loggedUser = allGlobals.loggedUser;
        state.layoutLinks = allGlobals.layoutLinks;
        state.socialLinks = allGlobals.socialLinks;
    },


}

export default {
  namespaced: true, state, getters, actions, mutations
}

Now this is my GlobalsController where I retrieve all global variables and compact them into a single array:

```php
public function getAllGlobals(){

        $globals = Globals::all()->pluck('name', 'value', 'intValue'); 

        $socialLinks = [
            
            'twitter' => config('globals.twitter'),
            'facebook' => config('globals.facebook'),
            'instagram' => config('globals.instagram'),

        ];

        $layoutLinks = [
            
            'classPosts' => Post::withCategory('Clases')->take(10)->get(),
            'behaviourPosts' => Post::withCategory('Conducta canina')->take(10)->get(),
            'trainingPosts' => Post::withCategory('Formación')->take(10)->get(),

        ];

        $loggedUser = Auth::user();

        $allGlobals = compact('globals', 'socialLinks', 'layoutLinks', 'loggedUser');

        return response()->json([
        
            'allGlobals' => $allGlobals

        ]);


    }

Help me I'm stuck here

31 Oct
1 week ago

Gabotronix left a reply on Accessing Collection Values Inside Blade Template

This is what I get after doing: {{ dd($globals) }}

https://i.imgur.com/IK4IsX4.png

It appears they are backwards? how can I fix this?

Gabotronix started a new conversation Accessing Collection Values Inside Blade Template

So I did just like suggested me and replaced the multiple queries with a single one in order to improve performance, problem is now I'm getting the following message error:

 ErrorException (E_NOTICE)
Undefined index: appName

First my migration so you can see data structure:

Schema::create('globals', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('displayName');
            $table->string('value')->nullable();
            $table->integer('intValue')->nullable()->default(0);
            $table->timestamps();
        });
        
        DB::table('globals')->insert([
            'name' => 'appName',
            'displayName' => 'Nombre de la aplicación',
            'value' => config('globals.appName'),
        ]);

This is how I gather the globals:

$globals = Globals::all()->pluck('name', 'value', 'intValue'); 
$view->with('globals', $globals);

I want to access the data in my blade template by 'name' and their corresponding value, like this:

{{ $globals['appBio']['value'] }}

But that way I get undefined index error, how can I do it?

Gabotronix left a reply on Global Variables Form Laravel To Vue, Is This Good Practice?

Wow thanks a lot for all the tips!

Gabotronix started a new conversation Global Variables Form Laravel To Vue, Is This Good Practice?

Hi everybody, I'm new to vue and I was scratching my head about this, so I have a few global variables wich some of my components like header, nav and footer want access to, the way I have been passing this data from laravel to vue is with my laravel's AppServiceProvider, this way:

View::composer('*', function ($view) {

            $globals = [
                'appName' => Globals::where('name', 'Nombre de la aplicación')->pluck('value')->first(),
                'appDescription' => Globals::where('name', 'Descripcion de la aplicación')->pluck('value')->first(),
                'appBio' => Globals::where('name', 'Biografia de la aplicacion')->pluck('value')->first(),
                'appBookingPhone' => Globals::where('name', 'Télefono de contacto')->pluck('value')->first(),
                'appPrefixBookingPhone' => Globals::where('name', 'Teléfono para mostrar')->pluck('value')->first(),
                'appMail' => Globals::where('name', 'Email de contacto')->pluck('value')->first(),
                'appFullAddress' => Globals::where('name', 'Dirección completa')->pluck('value')->first(),
                'appZipAddress' => Globals::where('name', 'Contador de visitas')->pluck('int_value')->first(),
                'appSchedules' => $schedules = Schedule::all(),
                'appTwitter' => config('globals.twitter'),
                'appFacebook' => config('globals.facebook'),
                'appInstagram' => config('globals.instagram'),
                'appShowNewsletterModal' => Modal::checkIfShowModal(),
                //'appShowConsentModal' => Modal::checkIfShowConsentModal(),
                'appAllClassesPosts' => Post::withCategory('Clases')->take(10)->get(),
                'appAllBehaviourPosts' => Post::withCategory('Conducta canina')->take(10)->get(),
                'appAllTrainingPosts' => Post::withCategory('Formación')->take(10)->get(),
                'appLoggedUser' => Auth::user(),
                'appSchedules' => $schedules = Schedule::all(),
                'appViewsCounter' => Globals::where('name', 'Contador de visitas')->pluck('int_value')->first()
            ];
            //dd($globals['appShowNewsletterModal']);
            $view->with('globals', $globals);
        });

Then in my master layout I pass this data to vue via an inline script:

<script>
window.APP = @json( ["pageInfo" => $pageInfo, "globals" => $globals] );
</script>

And then in my compoents I access this info via a computed property:

<template>
<header class="header_maincontainer">
    <div class="header_small_container">
        <div class="header_small_contact_container" style="">
            <span class="header_small_text1">Llamanos al: </span>
            <i class="header_small_phone_icon fa fa-phone"></i>
            <a class="header_small_phone_number" href="" >{{ APP.globals.appBookingPhone }}</a><!--ADD PREFIXED-->
            <div class="header_small_social_container" style="">
                <a v-if="APP.globals.twitter != ''" :href="'${APP.globals.twitter}'" target="_blank" class="header_small_social_icon"><i class="fa fa-twitter header_fa"></i></a>
                <a v-if="APP.globals.facebook != ''" :href="'${APP.globals.facebook}'" target="_blank" class="header_small_social_icon"><i class="fa fa-facebook header_fa"></i></a>
                <a v-if="APP.globals.instagram != ''" :href="'${APP.globals.instagram}'" target="_blank" class="header_small_social_icon"><i class="fa fa-instagram header_fa"></i></a>
            </div>
            <a class="header_small_auth_container" href="/login" v-if="APP.globals.appLoggedUser == undefined">
                <div class="header_small_login_icon"><i class="fa fa-user header_fa"></i></div>
                <span class="header_small_login_text" title="Iniciar sesión">Iniciar</span>
            </a>
            <div class="header_small_auth_container" v-if="APP.globals.appLoggedUser != undefined">
                <a href="/panel-administrador" class="header_small_mail_icon"><i class="fa fa-cog header_fa"></i></a>
                <a href="" class="header_small_login_icon"><i class="fa fa-sign-out header_fa"></i></a>
                <a href="/logout" class="header_small_login_text" title="Cerrar sesión">Salir</a>
            </div>
        </div>
    </div>
    <div class="header_big_container">
        <div class="header_big_logo_container">
            <a class="header_big_logo_link_wrapper" href="/" title="'Página de inicio de ${APP.globals.appBookingPhone}'" style="background-image:url('/img/logo_yellow.png');"></a>
        </div>
        <div class="header_big_texts_container">
            <span class="header_big_texts_3">Adiestramiento Canino a Domicilio en Málaga, Costa de Málaga e Interiores</span>
            <span class="header_big_texts_2">Tus especialistas en comportamiento canino</span>
            <a class="header_big_texts_phone" :href="'tel:${APP.globals.appPrefixedBookingPhone}'">{{ APP.globals.appBookingPhone }}</a>
        </div>
    </div>
</header>
</template>
<!--SCRIPTS-->
<script>
export default {
name: 'MainHeader',
computed: {
    APP() { return window.APP;}
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
    //console.log(APP.globals.appLoggedUser);
}
};
</script>
<!--STYLES-->
<style scoped>

</style>

However I just noticed that having data like this on the client might suppose a security breach (now this data is not compromised info but you get me).

So is this bad practice? what other ways are there to share global data with components? I guess I could perform an ajax request to get this into the component mounted() hook but I'm not sure if that's good practice either!

30 Oct
2 weeks ago

Gabotronix left a reply on Adding Phone Prefix To Phone Number Variable In My Component

Yes that was my fault, so now Visual Studio is showing me a syntax error:

https://i.imgur.com/0aIiGb3.png

why is this happening?

Gabotronix left a reply on Adding Phone Prefix To Phone Number Variable In My Component

I just tried yours:

<a class="header_small_phone_number" :href="tel:+34{{ APP.globals.appBookingPhone }}">{{ APP.globals.appBookingPhone }}</a>

but I'm still getting a compilling error

Gabotronix left a reply on Adding Phone Prefix To Phone Number Variable In My Component

So I decided to make a vue filter like this:

Vue.filter('phonePrefix', function (value) {
    return value ? '+34${value}' : null;
})

And added this to my template:

<a class="header_small_phone_number" :href="tel:{{ APP.globals.appBookingPhone | phonePrefix}} ">{{ APP.globals.appBookingPhone }}</a>

However when I compile I get this error:

 - invalid expression: Unexpected token : in

    tel: +34{{ APP.globals.appBookingPhone | phonePrefix}}

  Raw expression: :href="tel: +34{{ APP.globals.appBookingPhone | phonePrefix}} "

Gabotronix started a new conversation Adding Phone Prefix To Phone Number Variable In My Component

Hi everybody! I'm new to vue and was wondering what would be the best way to add a prefix to my phone number variable.

Say I in my template I have curly braces interpolation like this:

<span> {{ globals.phoneNumber }}</span>

but want to add the prefix: +34 to the value of globals.phoneNumber variable, what would be the best way to do it? I don't want to create ANOTHER variable just for this and concatenate the strings!

28 Oct
2 weeks ago

Gabotronix started a new conversation Laravel Mail: Attach File If Not Null

Hi everybody I have a mail where the file field is nullable (not required) however because of this when I try to attach a null uploadFile I get the following error:

message Undefined index: uploadFile

My question is is there a nice laravel way to only attach the file to mail if it exists?

This is my mail build method:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class ClientContactMail extends Mailable
{
    use Queueable, SerializesModels;
    
    public $mailData;

    public function __construct($mailData)
    {
        $this->mailData = $mailData;
    }

    
    
    
    public function build()

    {
        return $this->markdown('emails.client-contact')
        ->from($this->mailData['sender'], $this->mailData['appName'])
        ->subject($this->mailData['subject'])
        ->attach($this->mailData['uploadFile'], ['as' => $this->mailData['fileName'], 'mime' => $this->mailData['mimeType']]);
    }
}

Gabotronix started a new conversation Issue While Sending Contact Mail "Class App\Http\Controllers\SendClientContactMail Does Not Exist"

Hi everybody, so I'm trying to send a mail via a contact form using vue however I'm getting the following error message:

message Class App\Http\Controllers\SendClientContactMail does not exist
exception   ReflectionException
file    C:\xampp\htdocs\Costadog4\vendor\laravel\framework\src\Illuminate\Routing\RouteSignatureParameters.php

This makes it pretty obvious that the error resides in the backend however I don't understand why I'm getting this error since I'm including all dependencies on top of my ContactController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mail\BulletinMail;
use App\Mail\ClientContactMail;
use App\Mail\BugReportMail;
use Mail;
use Config;
use Validator;
use Log;
use App\Models\Globals;
use App\Models\Bug;
use App\Models\Review;

class ContactController extends Controller
{
   

    public function sendClientContactMail( SendClientContactMail $request)
    {
        
        $uploadFile = $filename = $mimetype = null; 
        
        if ($request->hasFile('file')) {
            $uploadFile = $request->file('file');
            $mimetype = $uploadFile->getMimeType();
            $filename = str_random(6).'.'.$uploadFile->extension();
            $uploadFile->storeAs('uploads', $filename);
        }

        $mailData = array(

            'appName' => Globals::where('name' , 'Nombre de la aplicacion')->pluck('value')->first(),
            'sender'=> config('globals.admin_mail'),
            'recipent'=> config('globals.clientMail'),
            'subject'=> "Nuevo reporte de bug de $name",
            'name'=> config('globals.clientName'),
            'phone'=> config('globals.clientPhone'),
            'title'=>$request->title,
            'body'=>$request->body,
            'filename'=> $filename,
            'fileMime'=> $mimetype
        );
    
        Mail::to( $mailData[recipent] )->send(new ClientContactMail( $mailData ));
        
        return response()->json([
        
            'success' => 'Reporte de bug enviado',
            'bug' => $bug,

        ]);
    }
    
}

This is my form request SendClientContactMail wich I use to validate all values before proceeding to send the actual mail.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SendClientContactMail extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            
            'name' => 'nullable|string|min:5',
            'city' => 'nullable',
            'phone' => 'required|string|min:9',
            'email' => 'required|email|min:10',
            'body' => 'required|string|min:10',
            'file' => 'nullable|mimes:doc,pdf,docx,zip,odt,jpeg,bmp,png,jpg,svg|max:2000'
        ];
    }
}

Maybe someone can shed some light on me

25 Oct
2 weeks ago

Gabotronix left a reply on Undefined Variable: Request

Yass, it works now!

Gabotronix left a reply on Undefined Variable: Request

Request parameters are:

category    Clases
id  1

Basically I want to take the posts with same category as request->category and with different id to $request->id

Gabotronix left a reply on Undefined Variable: Request

It works now but I'm getting an empty array instead, I should be getting two rows back as json.

Here are my migrations:

//CREATE CATEGORIES TABLE
        Schema::create('postcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL CATEGORIES TABLE WITH CATEGORIES
        DB::table('postcategories')->insert([
            'name' => 'Clases',
        ]);




        //CREATE POSTS TABLE
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('postcategory_id')->index();
            $table->foreign('postcategory_id')->references('id')->on('postcategories')->onDelete('cascade');
            $table->string('slug')->nullable();
            $table->string('title')->unique();
            $table->longText('body');
            $table->string('image')->nullable();
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL POSTS TABLE WITH DUMMY POSTS
        DB::table('posts')->insert([
            'postcategory_id' => 1,
            'slug' => 'Titulo de Posts 1',
            'title' => 'Titulo de Posts 1',
            'body' => config('globals.post_body_1'),
            'image' => config('globals.post_image_1'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        DB::table('posts')->insert([
            'postcategory_id' => 1,
            'slug' => 'Titulo de Posts 2',
            'title' => 'Titulo de Posts 2',
            'body' => config('globals.post_body_2'),
            'image' => config('globals.post_image_2'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        DB::table('posts')->insert([
            'postcategory_id' => 1,
            'slug' => 'Titulo de Posts 3',
            'title' => 'Titulo de Posts 3',
            'body' => config('globals.post_body_3'),
            'image' => config('globals.post_image_3'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);

I think my query might be wrong but I'm stuck

Gabotronix started a new conversation Undefined Variable: Request

So I'm getting the following error message in my PostController, this is pretty strange since I added Request $request into my function parameters:

status:500, message:    Undefined variable: request
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\StorePost;
use Str;

class PostController extends Controller
{


    public function getRelatedPosts(Request $request)
    {

        $relatedPosts = Post::whereHas("postcategory", function($q){
            $q->where("name","=", $request->category)->where("id","!=", $request->id);
            })->with('postcategory')->active()->inRandomOrder()->take(5)->get();
        
        return response()->json([

                'relatedPosts' => $relatedPosts
        ]);
        
        
    }

My ajax call:

mounted () {

    console.log(this.$options.name+' component successfully mounted');

    axios.post("/posts/related", {id: this.id, category: this.category})
        .then(response => (this.relatedPosts = response.data.relatedPosts))
        .catch(error => console.log(error));
},

How can I fix this?

Gabotronix left a reply on Vue Component Not Displaying Properly

Changed it but nothing changed :(

Gabotronix started a new conversation Vue Component Not Displaying Properly

Hi everyone, I'm new to vue and having some difficulties, I created a component wich receives a post variable as a prop, when the component mounts it fetches via axios POST request other posts related to that post (same category but different id to the received prop).

However my component is being rendered in a wonky way AND the related posts are not showing, this is what I see in my browser:

https://i.imgur.com/K1xCvqX.png

And in browser's surce code viewer:

https://i.imgur.com/Ynw3uMU.png

This is my component in my blade template (notice how I pass the prop using @json directive):

<div class="sidebar_container" style="">
        <div class="sidebar_stripe_white" style=""></div>
        <related-post-list :post="@json($classPost)"></related-post-list>
    </div>

This is my RelatedPostList.vue component

<template>
<div class="sidebar_related_container" style="">
    <span class="sidebar_related_title" style="">Temas Relacionados</span>
    <div class="sidebar_related_content_container" v-for="post in relatedPosts" :key="post.id" style="">
        <a class="sidebar_related_content_image" :href="'/conducta-canina/${post.slug}'"  :style="'background-image:url(${post.slug});'">
            <div class="black_gradient" style=""></div>
        </a>
        <div class="sidebar_related_content_text_container" style="">
            <span class="sidebar_related_content_text_title" style="">{{ post.postcategory.name }}</span>
            <span class="sidebar_related_content_text_description" style="">{{ post.title }}</span>
        </div>
    </div>
</div>
</template>
<!--SCRIPTS-->
<script>
export default
{
name: 'RelatedPostList',
    
props: {
    post: {required:true}
},

data: function () {
    return {

        relatedPosts: null,
        id: this.post.id,
        category : this.post.postcategory.name

    }
},

mounted () {

    console.log(this.$options.name+' component successfully mounted');

    axios.post("/posts/related", this.id, this.category)
        .then(response => (this.relatedPosts = response.data.relatedPosts))
        .catch(error => console.log(error));
},

methods: {

},


}
</script>
<!--STYLES-->
<style scoped>


Gabotronix left a reply on Console Log Vue's Component Name

That worked perfectly, thanks!

Gabotronix started a new conversation Vue: Property Or Method "APP" Is Not Defined On The Instance But Referenced During Render.

Hi, I'm tinkering with my first laravel-vue application and ran into a problem, first some context.

In order to share my global app data from laravel to view I use an inline script like this: I use laravel's AppServiceProvider to share global data with my view, afaik on each request this data will be refetched:

public function boot()
    {
        View::composer('*', function ($view) {

            $globals = [
                'appName' => Globals::where('name', 'Nombre de la aplicación')->pluck('value')->first(),
                'appDescription' => Globals::where('name', 'Descripcion de la aplicación')->pluck('value')->first(),
                'appBio' => Globals::where('name', 'Biografia de la aplicacion')->pluck('value')->first(),
                'appBookingPhone' => Globals::where('name', 'Télefono de contacto')->pluck('value')->first(),
                'appPrefixBookingPhone' => Globals::where('name', 'Teléfono para mostrar')->pluck('value')->first(),
                'appMail' => Globals::where('name', 'Email de contacto')->pluck('value')->first(),
                'appFullAddress' => Globals::where('name', 'Dirección completa')->pluck('value')->first(),
                'appZipAddress' => Globals::where('name', 'Contador de visitas')->pluck('int_value')->first(),
                'appSchedules' => $schedules = Schedule::all(),
                'appTwitter' => config('globals.twitter'),
                'appFacebook' => config('globals.facebook'),
                'appInstagram' => config('globals.instagram'),
                'appShowNewsletterModal' => Modal::checkIfShowModal(),
                'appAllClassesPosts' => Post::withCategory('Clases')->take(10)->get(),
                'appAllBehaviourPosts' => Post::withCategory('Conducta canina')->take(10)->get(),
                'appAllTrainingPosts' => Post::withCategory('Formación')->take(10)->get(),
                'appLoggedUser' => Auth::user(),
                'appSchedules' => $schedules = Schedule::all()
            ];
            //dd($globals['appAllBehaviourPosts']);
            $view->with('globals', $globals);
        });
    }

Then I use an inline script in my blade template to share the data with vue's instance:

<script>
window.APP = @json( ["pageInfo" => $pageInfo, "globals" => $globals] );
</script>

Then inside my MainHeader component I try to access APP variable but I get the following error:

[Vue warn]: Property or method "APP" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <MainHeader> at resources/assets/js/components/headers/MainHeader.vue
       <Root>

This is my MainHeader component:

<template>
<header class="header_maincontainer">
    <div class="header_small_container">
        <div class="header_small_contact_container" style="">
            <span class="header_small_text1">Llamanos al: </span>
            <i class="header_small_phone_icon fa fa-phone"></i>
            <a class="header_small_phone_number" :href="'tel:${APP.globals.appPrefixedBookingPhone}'">{{ APP.globals.appBookingPhone }}</a>
        </div>
        <div class="header_small_social_container" style="">
            <a v-if="APP.globals.twitter != ''" :href="'${APP.globals.twitter}'" target="_blank" class="header_small_social_icon"><i class="fa fa-twitter header_fa"></i></a>
            <a v-if="APP.globals.facebook != ''" :href="'${APP.globals.facebook}'" target="_blank" class="header_small_social_icon"><i class="fa fa-facebook header_fa"></i></a>
            <a v-if="APP.globals.instagram != ''" :href="'${APP.globals.instagram}'" target="_blank" class="header_small_social_icon"><i class="fa fa-instagram header_fa"></i></a>
        </div>
        <a class="header_small_auth_container" href="/login" v-if="APP.globals.user == ''">
            <div class="header_small_login_icon"><i class="fa fa-user header_fa"></i></div>
            <span class="header_small_login_text" title="Iniciar sesión">Iniciar</span>
        </a>
        <div class="header_small_auth_container" v-if="APP.globals.user != ''">
            <a href="/panel-administrador" class="header_small_mail_icon"><i class="fa fa-cog header_fa"></i></a>
            <a href="" class="header_small_login_icon"><i class="fa fa-sign-out header_fa"></i></a>
            <a href="/logout" class="header_small_login_text" title="Cerrar sesión">Salir</a>
        </div>
    </div>
    <div class="header_big_container">
        <div class="header_big_logo_container">
            <a class="header_big_logo_link_wrapper" href="/" title="'Página de inicio de ${APP.globals.appBookingPhone}'" style="background-image:url('/img/logo_yellow.png');"></a>
        </div>
        <div class="header_big_texts_container">
            <span class="header_big_texts_3">Adiestramiento Canino a Domicilio en Málaga, Costa de Málaga e Interiores</span>
            <span class="header_big_texts_2">Tus especialistas en comportamiento canino</span>
            <a class="header_big_texts_phone" :href="'tel:${APP.globals.appPrefixedBookingPhone}'">{{ APP.globals.appBookingPhone }}</a>
        </div>
    </div>
</header>
</template>

I'm stuck here

Gabotronix started a new conversation Console Log Vue's Component Name

Hi I'm trying to log my component's name on mounted hook, this is how I'm doing it:

<script>
export default
{
name: 'RelatedPostList',

mounted () {

    console.log("'${this.$options.name} component succesfully mounted'");

},

methods: {

},


}
</script>
<!--STYLES-->
<style scoped>

</style>

The result I get is:

'${this.name} component succesfully mounted'

what am I doing wrong? how can I access name property?

24 Oct
2 weeks ago

Gabotronix started a new conversation Vue Component Not Showing Up With Laravel And Webpack

So I'm trying to migrate my jquery to vue framework instead, I'm using laravel 5.6 with webpack to build my project but my vue components are not showing up.

when I run command npm run dev I succesfully build the project:

https://i.imgur.com/20OdT95.png

After that I use php artisan serve to show the web in my browser wich it does but NONE of the components show up.

When I check source code this is what the component renders :

https://i.imgur.com/rtrIjuk.png

but for some reason I can't see the component?

This is my app.js file:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

/*
require('./bootstrap');
*/

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('related-post-list', require('./components/RelatedPostList.vue'));
Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
    el: '#app'
});

My webpack file:

let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

Bootstrap file

window._ = require('lodash');
window.Popper = require('popper.js').default;

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

let ajaxEncoding = 'multipart/form-data';
console.log("'Ajax encoding is ${ajaxEncoding}'");

axios.defaults.headers.post['Content-Type'] = ajaxEncoding;

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
    console.log('CSRF token found');
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo'

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     encrypted: true
// });

My component:

Temas Relacionados {{ post.postcategory.name }} {{ post.title }} export default { name: 'RelatedPostList',

props: { post: {required:true} },

data: function () { return {

    relatedPosts: null,
    id: this.post.id,
    category : this.post.postcategory.name

}

},

mounted () {

console.log("'${this.$options.name} component succesfully mounted'");

axios.post("/posts/related", this.id, this.category)
    .then(response => (this.relatedPosts = response.data.relatedPosts))
    .catch(error => console.log(error));

},

methods: {

},

}

.sidebar_related_container{width:100%; height:auto; display:flex; flex-direction:column;} .sidebar_related_title{width:100%; height:75px; font-size:16px; color:#454545; font-weight:600; display:flex; align-items:center;} .sidebar_related_content_container{width:100%; height:auto; display:flex; flex-direction:column; margin:15px 0px;} .sidebar_related_content_image{width:100%; height:180px; box-shadow:2px 2px 2px rgba(0,0,0,0.2); position:relative; background-size:cover; margin-bottom:3px;} .sidebar_related_content_text_container{width:100%; height:30%; display:flex; flex-direction:column;} .sidebar_related_content_text_title{font-size:15px; color:var(--main_color); font-weight:900; margin:5px 0px;} .sidebar_related_content_text_description{font-size:13px; color:rgba(0,0,0,0.7); font-weight:500; margin:5px 0px; line-height:20px;} @media only screen and (max-width: 736px) { .sidebar_container{width:100%; height:auto; padding-left:0px; padding-bottom:0px; padding-top:20px; position:relative;} .sidebar_stripe_white{width:15px; height:40px; background-color:white; position:absolute; top:0px; left:-10px; display:none;} .sidebar_related_container{width:100%; height:auto; display:flex; flex-direction:column; } .sidebar_related_title{width:100%; height:auto; font-size:16px; color:#454545; font-weight:600; display:flex; align-items:center; margin:15px 0px;} .sidebar_related_content_container{width:100%; height:auto; display:flex; flex-direction:column; align-items:center; margin:15px 0px;} .sidebar_related_content_image{width:100%; height:155px; box-shadow:2px 2px 2px rgba(0,0,0,0.2); position:relative; background-size:cover; margin-bottom:3px;} .sidebar_related_content_text_container{width:100%; height:20%; display:flex; flex-direction:column;} .sidebar_related_content_text_title{font-size:15px; color:var(--main_color); font-weight:900; margin:5px 0px;} .sidebar_related_content_text_description{font-size:13px; color:rgba(0,0,0,0.7); font-weight:500; margin:5px 0px; line-height:20px;} } ```

And my blade templates:

<div class="sidebar_container" style="">
        <div class="sidebar_stripe_white" style=""></div>
        <related-post-list :post="@json($classPost)"></related-post-list>
        <!--<example-component></example-component>-->
        <[email protected]('partials/sidebar/contact_form')-->
    </div>

this file is inside my master layout where the body tag has "app" identifier:

<body id="app" class="">
  //sidebar
</body>

Please help me, I'm stuck here!

22 Oct
3 weeks ago

Gabotronix started a new conversation Dispatch Action With FormData To Proccess Into The Store?

Hi everyone, I'm making an admin panel for my web, for state management I'm using this library:

https://francescosaveriozuppichini.github.io/Flue/index.html

It's similar to vuex but with much less bolierplate andoverhead, it also lets me use javascript classes to keep everything object oriented and also reactive!

Now one of my inputs is for uploading a file via axios but I was wondering how could I pass formData object directly to the store, I want to separate my component from business logic.

This is my component:

//STATE///////////////////////////////////////////////////////////////////////////
    constructor() {
        super()
        this.state.post =  '',
        this.state.posts =  [],
        this.state.inputPost = ''
    }


    //STORE EXPONE HIS ACTIONS////////////////////////////////////////////////////////
    actions(ctx) {
        return {
            createPost() {ctx.dispatchAction('CREATE_POST', { post: post } )},
            readAllPosts() {ctx.dispatchAction('READ_ALL_POSTS', { posts: posts })},
            updatePost() {ctx.dispatchAction('UPDATE_POST', { post: post } )},
            deletePost() {ctx.dispatchAction('DELETE_POST', { post: post } )},
            togglePostVisibility() {ctx.dispatchAction('TOGGLE_POST_VISIBILITY', { post: post })}
            
        }
    }


    //STORE ACTIONS REDUCER////////////////////////////////////////////////////////////
    reduce(action) {
        this.reduceMap(action, {
            CREATE_POST: this.createPost,
            READ_ALL_POSTS: this.readAllPosts,
            UPDATE_POST: this.updatePost,
            DELETE_POST: this.deletePost,
            TOGGLE_POST_VISIBILITY: this.togglePostVisibility
        })
    }


    //ACTION FUNCTIONS//////////////////////////////////////////////////////////////////

    createPost(post) {
        console.log('saving_post');
                
        let formData = new FormData();
        formData.append('category', post.category);
        formData.append('title', post.title);
        formData.append('post', post.body);
        formData.append('isVisible', post.isVisible);
        formData.append('image', post.isVisible);

        axios.post('/posts', formData)
        .then(response => (this.post = response.data.post))
        .catch(error => console.log(error));
    }

And my component:

<template>
<form id="new_posts_form" class="modal_container">
    <i class="modal_close fa fa-times-circle" title="Cerrar" @click="$store.actions.closeModal()"></i>
    <h2 class="modal_title">Nueva publicación</h2>
    <div class="horizontal_gradient_line" style="align-self:center; margin:10px 0px;"></div>
    <div class="modal_inputs_container">
        <div class="modal_row_container">
            <span class="modal_label">Visible</span>
            <input class="modal_body_check" type="checkbox" v-model="isVisible" title="La publicación será visible automáticamente en la web">
        </div>
        <div class="modal_row_container">
            <span class="modal_label">Imagen</span>
            <input type="file" name="file" required>
        </div>
        <div class="modal_row_container">
            <span class="modal_label">Categoría</span>
            <select class="modal_input_select" v-model="category" required>
                <option :value="'${postcategory.id'">{{ postcategory.name }}</option>
            </select>
        </div>
        <input class="modal_input_text" type="text" v-model="title" placeholder="Titulo de la publicación" required>
        <textarea class="modal_input_textarea summernote" v-model="body" placeholder="Contenido de la publicación" required></textarea>
        <div class="form_valid_container"></div>
        <div class="form_error_container"></div>
    </div>
    <div class="horizontal_gradient_line" style="align-self:center; margin:10px 0px;"></div>
    <div class="modal_buttons_container">
        <button class="modal_button boot_blue form_store_button" type="button" @click="$store.actions.createPost()" title="Guardar la nueva publicación">Guardar</button>
        <button class="modal_button boot_grey form_reset_button" type="button" @click="$store.actions.resetInputs()" title="Resetear los campos">Reset</button>
    </div>
</form>
</template>
<!--SCRIPTS-->
<script>
export default {

    name: 'CreatePostModal',
   
    mounted() {
        console.log("'${this.$options.name} component succesfully mounted'");
    },

    computed: {
        message: { get() { return $store.state.title }, set(value) { $store.actions.setTitle(value) } },
    }

}
</script>
<!--STYLES-->
<style scoped>
</style>

Gabotronix started a new conversation Trying To Show A Modal With Cookies

Hi everybody, I'm trying to display (or not) a newsletter modal according to if a cookie is set or not, for some reason $show_modal always returns false.

Main Page Controller:

public function inicio()
    {

        $show_modal = Modal::checkIfShowModal();

        //dd($show_modal);
        
        return view('inicio.index', compact( 'show_modal'));
    }

This is my method for checking if the modal should be shown or not:

Modal.php

public static function checkIfShowModal(){


        $modal = Modal::first();
        
        if($modal->isActive && Cookie::get('cookie_modal_1') !== false)
        {
            //cookie is set, don't show modal
            return false;
        }
        else if($modal->isActive && Cookie::get('cookie_modal_1') == true){
            //cookie isn't set, show modal then
            Cookie::queue( Cookie::make('cookie_modal_1', true, 60*24*7));
            return true;
        }



    }

Inside my blade template I use conditional to show render modal

@if($show_modal == true)
    @include('partials/modals/modal_fir')
@endif

Modals migration:

Schema::create('modals', function (Blueprint $table) {
            $table->increments('id');
            $table->longText('body');
            $table->boolean('isActive')->default(false);
            $table->timestamps();
        });
        //FILL MODALS TABLE WITH ONE MODAL
        DB::table('modals')->insert([
            'body' => 'Subscribete a nuestro boletín noticiario, recibe ofertas, noticias, eventos y articulos de nosotros',
            'isActive' => true,
        ]);

Any idea why the modal never shows up

19 Oct
3 weeks ago

Gabotronix started a new conversation Using Axios, Lodash With Vue In Laravel

Hi, this will be my first laravel app using vue instead of jquery, I want to use axios and lodash libraries inside my laravel application using vue, my app is a laravel app with many components.

Looking at my bootstrap.js file it looks like laravel uses window global object to access this libraries however this is apparently a bad practice for server rendered apps:

https://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/

so I'd like to use these libraries as plugins instead! this way I could use axios.post(blah blah) instead of window.axios.post(...) right?

How can I do this??

this is my bootstrap.js file:


window._ = require('lodash');
window.Popper = require('popper.js').default;

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo'

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     encrypted: true
// });

package.json

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.18",
        "bootstrap": "^4.0.0",
        "popper.js": "^1.12",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^2.0",
        "lodash": "^4.17.4",
        "vue": "^2.5.7"
    }
}

app.js


/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
    el: '#app'
});

Please help a noob out

Gabotronix started a new conversation Creating Global Helper Queryscopes In Laravel

Hi, I noticed I'm repeating the same queries on my PageController once and again so I thought I could abstract those to keep my code cleaner, I also want to be able to use these query scopes on ALL my models, that'd be GREAT!

These are my queryscopes:

public function scopeActive($query)
    {
        return $query->where('isActive', 1);
    }

    public function scopeVisible($query)
    {
        return $query->where('isVisible', 1);
    }

    public function scopeRandomOrder($query)
    {
        return $query->orderBy(DB::raw('RAND()'));
    }

So question, are query scopes the go to for this functionality? I'm still a noob, where would I place this methods so I can use them on all my Controllers and Models??

Thanks in advance and happy coding!

Gabotronix started a new conversation Vue/eslint: The Template Root Disallows V-for Directives

So this are my first steps with vue framework, I'm trying to make a simple post list component where I use v-for directive, however I'm getting the following message:

eslint-eslint: the template root disallows v-for directives

Then how am I supposed to loop and render each post?

I'm passing the allBehaviourPosts to the component from laravel backend as a prop, like this:

<related-post-list :relatedBehaviourPost= {{ $relatedBehaviourPosts }}></>
<template>
<div class="sidebar_related_content_container" v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id" style="">
    <a class="sidebar_related_content_image" href="/conducta-canina/{{ relatedBehaviour.slug }}"  style="background-image:url('{{ behaviour.image }}');">
        <div class="black_gradient" style=""></div>
    </a>
    <div class="sidebar_related_content_text_container" style="">
        <span class="sidebar_related_content_text_title" style="">{{ behaviour.postcategory.name }}</span>
        <span class="sidebar_related_content_text_description" style="">{{ behaviour.title }}</span>
    </div>
</div>
</template>
<!--SCRIPTS-->
<script>
    export default {

        props: ['relatedBehaviourPosts'],

        data: function () {
            return {
                //data
            }
        },

        mounted() {
            console.log('Footer mounted.')
        }
    }
</script>
<!--STYLES-->
<style scoped>

</style>

17 Oct
3 weeks ago

Gabotronix started a new conversation Issue Retrieving Posts With A Category Name Using WhereHas

So I'm getting the following error, I think it has to be something with my migrations or the relationship of my tables

 Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column '5' in 'order clause' (SQL: select * from `posts` where exists (select * from `postcategories` where `posts`.`postcategory_id` = `postcategories`.`id` and `name` = Clases) order by `5` desc)

This is where the code fails:

$footerClassesPosts = Post::whereHas("postcategory", function($q){
                $q->where("name","=","Clases");
                })->latest(5)->get();
                dd(footerClassesPosts);

This is my migration where I create posts and postcategories table:

//CREATE CATEGORIES TABLE
        Schema::create('postcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL CATEGORIES TABLE WITH CATEGORIES
        DB::table('postcategories')->insert([
            'name' => 'Clases',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Conducta canina',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Evento',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Notícia',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Artículo',
        ]);




        //CREATE POSTS TABLE
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('postcategory_id')->index();
            $table->foreign('postcategory_id')->references('id')->on('postcategories')->onDelete('cascade');
            $table->string('slug')->nullable();
            $table->string('title')->unique();
            $table->longText('body');
            $table->string('image')->nullable();
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL POSTS TABLE WITH DUMMY POSTS
        DB::table('posts')->insert([
            'postcategory_id' => 2,
            'title' => config('globals.post_title_1'),
            'body' => config('globals.post_body_1'),
            'image' => config('globals.post_image_1'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        DB::table('posts')->insert([
            'postcategory_id' => 1,
            'title' => config('globals.post_title_2'),
            'body' => config('globals.post_body_2'),
            'image' => config('globals.post_image_2'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        DB::table('posts')->insert([
            'postcategory_id' => 2,
            'title' => config('globals.post_title_3'),
            'body' => config('globals.post_body_3'),
            'image' => config('globals.post_image_3'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);

My Post and PostCategory models, I stablish relationships here:

Post.php

public function postcategory()
    {
        return $this->belongsTo('App\PostCategory');
    }

PostCategory.php

public function posts()
    {
        return $this->hasMany('App\Post');
    }

Please help me out, can't find where the issue is

16 Oct
4 weeks ago

Gabotronix started a new conversation Issue While Using WhereHas

So I'm trying to retrieve all the post wich have a postcategory equal to "Clases", however I'm gettting the following error message, I can't seem to find where I messed up in the migration.First, here is the error message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.postcategories_id' in 'where clause' (SQL: select * from `posts` where exists (select * from `postcategories` where `posts`.`postcategories_id` = `postcategories`.`id` and `name` = Clases))

This is the query I'm doing:

$allClasses = Post::whereHas("postcategories", function($q){
                $q->where("name","=","Clases");
                })->get();

My migration file where I stablish the relationship between posts and categories:

//CREATE CATEGORIES TABLE
        Schema::create('postcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL CATEGORIES TABLE WITH CATEGORIES
        DB::table('postcategories')->insert([
            'name' => 'Clases',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Conducta canina',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Evento',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Notícia',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Artículo',
        ]);




        //CREATE POSTS TABLE
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('postcategory_id')->index();
            $table->foreign('postcategory_id')->references('id')->on('postcategories')->onDelete('cascade');
            $table->string('slug')->nullable();
            $table->string('title')->unique();
            $table->longText('body');
            $table->string('image')->nullable();
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL POSTS TABLE WITH DUMMY POSTS
        DB::table('posts')->insert([
            'postcategory_id' => 2,
            'title' => config('globals.post_title_1'),
            'body' => config('globals.post_body_1'),
            'image' => config('globals.post_image_1'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        DB::table('posts')->insert([
            'postcategory_id' => 1,
            'title' => config('globals.post_title_2'),
            'body' => config('globals.post_body_2'),
            'image' => config('globals.post_image_2'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        DB::table('posts')->insert([
            'postcategory_id' => 2,
            'title' => config('globals.post_title_3'),
            'body' => config('globals.post_body_3'),
            'image' => config('globals.post_image_3'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);

Relationships:

Post:

public function postcategories()
    {
        return $this->belongsTo('App\PostCategory');
    }

Category:

public function posts()
    {
        return $this->hasMany('App\Post');
    }