Gabotronix

Gabotronix

Member Since 9 Months Ago

Experience Points 14,150
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.

17 Jan
17 hours ago

Gabotronix started a new conversation Attaching Relationship Data To Model Before Saving It?

Hi, I have a model discount with a discountcodes relationship, a discount can have many discount codes and codes belong to a discount, when creating it is it possible to also attach discount code data to the model before saving it?

Currently what I'm doing is creating discount, save it, then generate discount codes and attach them to my newly created id, then save again, this looks a little silly to me at first.

This is my controller code:

public function create(Create $request)
    {
        $discount = new Discount();
        $discount->title = $request->input('title');
        $discount->body = $request->input('body');
        $discount->image = '/img/misc/default.jpg';
        if($request->hasFile('image')){ $discount->image = $this->uploadImage('image'); }
        $discount->originalPrice = $request->input('originalPrice');
        $discount->finalPrice = $request->input('finalPrice');
        $discount->codesToGenerate = $request->input('codesToGenerate');
        $discount->discountPercent = $this->getPercentageChange($request->input('originalPrice'), $request->input('finalPrice'));
        $discount->isVisible = false;
        $discount->save();
        //IMPORTANT PART IS HERE
        $this->generateCodes($discount, $request->input('codesToGenerate'));
        $discount->save();
        $discount->load('discountcodes');
        
        return response()->json([
            'discount' => $discount,
        ]);
    }


    public function generateCodes($discount, $codesToGenerate)
    {
        for ($i = 0; $i < $codesToGenerate; $i++) {
            $code = new DiscountCode();
            $code->discount_id = $discount->id;
            $code->unicode = $this->generateRandomToken();
            $code->expireDate = Carbon::now()->addDays(365);
            $code->save();
        }
    }

Gabotronix started a new conversation Getting Common Methods Outside Controller

Hi everybody, I have a PostContrller, I use this one to perform CRUD operatins and more with the Post Model, inside this controller I call to the method slugify() which I placed in the controller itself, now this method is also used in other controllers like Discount, Events, Pages controllers...

What would be the best way to implement my slugify method without copying and pasting it inside each of my controllers,, I'm still a newby but afaik you can only extend one class at a time so this option is out of the question since my controller already extends Controller.

Here is an excerpt of my PostController:

public function slugify($title){
        return $slugifiedTitle = Str::lower( Str::slug($title, '-') );
    }

    
    public function create(Create $request)
    {
        $post = new Post();
        $postCategory = PostCategory::findOrFail($request->input('category'));

        $post->postcategory_id = $postCategory->id;
        $post->user_id = Auth::user()->id;

        $post->url = $postCategory->url.'/'.$this->slugify($request->input('title'));
        $post->title = $request->input('title');
        $post->description = $request->input('description');
        $post->body = $request->input('body');
        $post->image = '/img/misc/default.jpg';
        $post->video = $request->input('video');
        
        if($request->hasFile('image')){
            $uploadFile = $request->file('image');
            $filename = str_random(6).'.'.$uploadFile->extension();
            $uploadFile->storeAs('uploads', $filename);
            $post->image = '/uploads/'.$filename;
        }

        $post->save();
        
        return response()->json([
            'post' => $post,
        ]);
        
    }

Thanks in advance

Gabotronix started a new conversation Remove Exception Clutter From My Controller Methods

Hi everybody, I'm tinkering with stripe to make payments through my app, currently I'm using try catch blocks and Stripe own Exception methods to get notified when something goes wrong, sadly the catch blocks are huge as hell and I was wondering if there's a way to move this code outside my controller since the catch blocks all have the same, repeated code over and over, any idea?

This is one of my methods, I have lots of these in my controller so you can guess how cluttered my controller is getting.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;
use Stripe\Customer;
use Stripe\Error\Card;
use Stripe\Error\ApiConnection;
use Stripe\Error\InvalidRequest;
use Stripe\Error\Api;
use Stripe\Error\Base;

class StripeController extends Controller
{
    
    public function customerCheck(Request $request){
        $user = Auth::user();

        if($user->stripeCustomerId){

            try{
                Stripe::setApiKey(config('services.stripe.secret'));
            
                $customerId = Auth::user()->stripeCustomerId;
    
                $customerSources = Customer::retrieve($customerId)->sources->all(array("object" => "card"));
    
                return response()->json([
                    'customerSources' => $customerSources,
                    'message' => 'Elije la forma de pago segura'
                ], 201);
            }
            catch (ApiConnection $e) {//Network problem, perhaps try again.
                return response()->json([
                    'message' => 'Sorry, Network is having trouble. Please try again later.',
                ]);
            } 
            catch (InvalidRequest $e) {//You screwed up in your programming. Shouldn't happen!
                return response()->json([
                    'message' => 'Sorry. One of our programmer forgot to drink their caffein.',
                ]);
            }
            catch (Api $e) {//Stripe's servers are down!
                return response()->json([
                    'message' => 'Sorry our payment processor is down at the moment.',
                ]);
            } 
            catch (Card $e) {//Card was declined.
                return response()->json([
                    'message' => 'Your card is declined. Please try with a different card.',
                ]);
            } 
            catch (\Stripe\Error\Base $e) {// Display a very generic error to the user, maybe send yourself an email
                return response()->json([
                    'message' => 'Algo salio mal, prueba más tarde.',
                ]);   
            }
            catch (Exception $e) {// Something else happened, completely unrelated to Stripe
                return response()->json([
                    'message' => 'Algo salio mal, prueba más tarde',
                ]);
            }

        }
        else if(!$user->customerId){
            return response()->json([
                'user' => $user,
                'message' => 'No hay tarjetas registradas a este nombre'
            ]);
        }
        else if(!$user){
            return response()->json([
                'user' => $user,
                'message' => 'Registrate para poder realizar la compra'
            ]);

        }

        return response()->json([
            'user' => 'It worked!',
        ]);

    }
15 Jan
2 days ago

Gabotronix left a reply on Nuxt(SSR) For Frontend And AdonisJs For Backend/API Only Template

Also how could I deploy two aplcations (nuxt and adonis (API only) in a shared hosting?

14 Jan
3 days ago

Gabotronix started a new conversation Nuxt(SSR) For Frontend And AdonisJs For Backend/API Only Template

Hi everybody, I come from a vue + laravel background so I'd like to have a try at stack which would be Nuxt for the frontend + SSR and adonisjs for the backend as an API, afaik adonis come with lots of features out of the box so I can skip express conf and packages instalation.

Also imo frontend and backend should not be coupled, that's why I will skip adonuxt template.

My question is, where can I find a template where nuxt and adonis are separated to get started, I don't have experience building full stack templates on my own.

Ideally I would have the nuxt files folder and then inside the folder a server/api/backend folder where adonis resides.

Thanks in advance.

08 Jan
1 week ago

Gabotronix started a new conversation Migration Refresh: Cannot Delete Or Update A Parent Row: A Foreign Key Constraint Fails

Hi everybody, I'm trying to refresh all my migrations, that is rollback and repopulate all my tables, when I use command "php artisan migrate:refresh" I get the following error:

Rolling back: 2018_10_06_162333_post_and_categories

   Illuminate\Database\QueryException  : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table if exists `postcategories`)

  at C:\xampp\htdocs\Costadog6\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails")
      C:\xampp\htdocs\Costadog6\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      C:\xampp\htdocs\Costadog6\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  Please use the argument -v to see more details.

This is my migration file for both post and postcategories:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Carbon\Carbon;

class PostAndCategories extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {



        //CREATE CATEGORIES TABLE
        Schema::create('postcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->boolean('isVisible')->default(true);
            $table->boolean('isSinglePage')->default(false);
            $table->timestamps();
        });
        //FILL CATEGORIES TABLE WITH CATEGORIES
        DB::table('postcategories')->insert([
            'name' => 'Clases',
            'slug' => 'clases',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Conducta canina',
            'slug' => 'conducta-canina',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Formación',
            'slug' => 'formate-con-nosotros',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Notícia',
            'slug' => 'noticias',
        ]);
        DB::table('postcategories')->insert([
            'name' => 'Blog',
            'slug' => 'blog',
        ]);




        //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->unsignedInteger('user_id')->index();
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('slug')->unique();
            $table->string('url')->unique();
            $table->string('title')->unique();
            $table->longText('body');
            $table->string('image')->nullable();
            $table->text('imageDescription')->nullable();
            $table->string('video')->nullable();
            $table->text('videoDescription')->nullable();
            $table->boolean('isVisible')->default(false);
            $table->boolean('isFeatured')->default(false);
            $table->boolean('beenPublished')->default(false);
            $table->timestamps();
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('postcategories');
        Schema::dropIfExists('posts');
    }
}

06 Jan
1 week ago

Gabotronix started a new conversation Vue: Hover Custom Directive Not Working

Hi everybody, I want to create a vue directive which accomplishes the following, when I do on hover I want the background image to scale up a bit, I do this with a custom vue directive where I apply transform scale to an image with overflow set to hidden, this creates a nice transition effect.

Hoever it's not activating when I hover over the image, any help would be appreciated!

This is my code:

<template>
<section class="posts2_maincontainer">
    <div class="posts2_big_container">
        <main-slider :slidercount="3" :sliderinterval="5000" :slideritems="slideritems"></main-slider>
        <a class="posts2_image_container" href="/clases">
            <div class="posts2_image" style="background-image:url('/img/photos/dogs19.jpg');"></div>
            <span class="posts2_text">CLASES A DOMICILIO</span>
        </a>
        <a class="posts2_image_container" href="/conducta-canina">
            <div class="posts2_image" style="background-image:url('/img/photos/dogs20.jpg');"></div>
            <span class="posts2_text">CLASES EN GRUPO</span>
        </a>
    </div>
    <a class="posts2_small_container" href="/formate-con-nosotros" style="outline:1px solid red;">
        <div class="posts2_image" v-on-hover-zoom style="background-image:url('img/photos/dogs14.jpg'); background-position-x:55%;"></div>
        <span class="posts2_text">FORMATE CON NOSOTROS</span>
    </a>
</section>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex';
export default{
name: 'PostsHub2',

computed: {
    
},

props: {
    slideritems: { required:true }
},

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

methods:{
     
}

}
</script>
<!--STYLES-->
<style scoped>
.posts2_maincontainer{width:100%; height:600px; display:flex; justify-content:space-between;}
.posts2_big_container{width:66%; height:100%; display:flex; justify-content:space-between; position:relative;}
.posts2_small_container{width:33%; height:100%; position:relative; box-shadow:2px 2px 4px rgba(0,0,0,0.3); overflow:hidden; }
.posts2_image_container{width:49%; height:42%; margin-top:auto; position:relative; box-shadow:2px 2px 4px rgba(0,0,0,0.3);}
.posts2_image{width:100%; height:100%; background-size:cover; background-position:center;}
.posts2_text{width:100%; height:50px; position:absolute; bottom:25px; left:0px; display:flex; justify-content:center; align-items:center; color:white; font-size:25px; background-color:rgba(0,0,0,0.7);}
</style>


My vue directive:

Vue.directive('on-hover-zoom', {
    isLiteral: true,
    inserted: (el, binding, vnode) => {
        let f = () => {
            el.style.transform = 'scale(1.5, 1.5)';
            console.log('hovered');
        }

        el.addEventListener('hover', f);
    }
});
05 Jan
1 week ago

Gabotronix left a reply on Where Relationship Has More Than One Where Field Is True

where the count of isUsed == false is more than zero, afail that query will return only discountcodes which met that condition.

Gabotronix started a new conversation Where Relationship Has More Than One Where Field Is True

Hi everybody, I have a discount Model with a relationship discountcodes, that is one discount can have many discount codes. Each of the discount codes has a boolean field named isUsed, false by default.

Now I want to retrieve all discounts where their respective disocuntcodes with 'isUsed' field set to false is bigger than zero.

How can I do this?

$allDiscounts = Discount::where('isVisible', true)->with('discountcodes')->get();
04 Jan
1 week ago

Gabotronix left a reply on Catching Errors With Stripe?

@SHEZ1983 - How can I get exception error message into my message variable?

Gabotronix started a new conversation Catching Errors With Stripe?

Hi everybody, I'm playing with Stripe in laravel, I have my controller function where I create a customer and a source, now I was wondering how could I catch any error that occurs when trying to create customer/source, I would like to return back an error message telling the user what went wrong.

I added a try catch block but tbh I have never used try catch before, is it the best way to do this? How can I get error message?

This is my controller function:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;
use Stripe\Customer;

class StripeController extends Controller
{
    public function createCustomerAndSource(Request $request){

        try
        {
            Stripe::setApiKey(config('services.stripe.secret'));

            $customer = Customer::create([
                "email" => $request->input('email'),
                "source" => $request->input('sourceId'),
            ]);

            $user = new User;
            $user->name = $request->input('name');
            $user->password = bcrypt($request->input('password'));
            $user->stripeCustomerId = $customer->id;
            $user->save();

            Auth::login($user);

            return response()->json([
                'message' => 'It worked!',
            ]);

        }
        catch(Exception $e)
        {
            return response()->json([
                'message' => 'Oops, something went wrong!',
            ]);

        }
   
    }
30 Dec
2 weeks ago

Gabotronix started a new conversation Laravel: Select Item Where Date Is Previous To Today

Hi, imagine I have a model in my database wich has a filed "date", this file is a Carbon timestamp.

Now, I want to retrieve all instances of that model where date field has not yet come, that is, where the date field is prior to Carbon::now() timestamp.

Any suggestions?

28 Dec
2 weeks ago

Gabotronix started a new conversation Migration Issue: Invalid Default Value For "remaining"

I have a migration where I'm getting the following error, I'm using Carbon to get the remaining days for a date and store it in database.

  Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'remaining' (SQL: create table `events` (`id` int unsigned not null auto_increment primary key, `slug` varchar(255) not null, `url` varchar(255) not null, `date` timestamp not null, `remaining` timestamp not null, `title` varchar(255) not null, `body` longtext not null, `image` varchar(255) null, `imageDescription` text null, `video` varchar(255) null, `videoDescription` text null, `isVisible` tinyint(1) not null default '0', `beenPublished` tinyint(1) not null default '0', `created_at` timestamp null, `updated_at` timestamp null) default character set utf8 collate 'utf8_general_ci')

  at C:\xampp\htdocs\Costadog6\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'remaining'")
      C:\xampp\htdocs\Costadog6\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      C:\xampp\htdocs\Costadog6\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  Please use the argument -v to see more details.

I also have another question, in my migration file where I also seed some dummy data into table, is it possible to reference a column created just above? that is, I want to apply the diffForHumans method to the "date" row...

My migration file:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Carbon\Carbon;

class Events extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //CREATE EVENTS TABLE
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->string('slug')->unique();
            $table->string('url')->unique();
            $table->timestamp('date');
            $table->timestamp('remaining');
            $table->string('title')->unique();
            $table->longText('body');
            $table->string('image')->nullable();
            $table->text('imageDescription')->nullable();
            $table->string('video')->nullable();
            $table->text('videoDescription')->nullable();
            $table->boolean('isVisible')->default(false);
            $table->boolean('beenPublished')->default(false);
            $table->timestamps();
        });
        //FILL EVENTS TABLE WITH DUMMY EVENTS
        DB::table('events')->insert([
            'slug' => 'evento-1',
            'url' => '/eventos/evento-1',
            'date' => Carbon::now()->addDays(50),
            'title' => 'Titulo',
            'body' => 'Contenido',
            'remaining' => Carbon::now()->addDays(50)->diffForHumans(),
        ]);

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('events');
    }
}

Mocking the date with addDays method just feels bad to me

Thanks in advance

26 Dec
3 weeks ago

Gabotronix started a new conversation Vue: Issue With SetInterval Function Inside Component Methods

Hi everybody, I'm making progress on my custom slider component, I can get setInterval to execute a method each X seconds, issue is Im getting the following error:

TypeError: this.nextSlider is not a function

This is my component logic:

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

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

props: {
    slidercount: {required:true, type: Number},
    sliderinterval: {default: 5000, type: Number},
},

data() {
    return {
        sliderTimer: 0,
        activeslider: 1,
    }
},

methods:{


    startSlider() {
        
        this.sliderTimer = setInterval(function(){
        this.nextSlider() }, 5000);
    },


    prevSlider() {
        if(this.activeslider == 1){
            this.activeslider = this.slidercount;
        }
        else{
            this.activeslider = this.activeslider - 1;
        }
    },


    nextSlider() {
        if(this.activeslider == this.slidercount){
            this.activeslider = 1;
        }
        else{
            this.activeslider = this.activeslider + 1;
        }
    },


    goToSlider (sliderIndex) {
        this.activeslider = sliderIndex;
        clearInterval(this.sliderTimer);
        
    },

}
};
</script>
25 Dec
3 weeks ago

Gabotronix left a reply on Issue Pushing Array Into Arrays

I get the following error after adding your suggestion:

Indirect modification of overloaded element of Illuminate\Database\Eloquent\Collection has no effect
public function index()
    {
        
        $productCategory = ProductCategory::all()->mapWithKeys(function ($category) {
            return [ $category->name => [] ];
        });
        
        $products = Product::with('productcategory')->get();

        foreach($products as $product){
            $category = $product->productcategory->name;
            $productCategory[$category] []= $product;
        }
        

        //$products = Product::latest()->with('productcategory')->get();
        
        return response()->json([
            'productCategory' => $productCategory,
        ]);
    }

Gabotronix started a new conversation Issue Pushing Array Into Arrays

Hi everybody, so I have this method controller where I first:

  1. create an array of arrays where each query result name value is the key of an empty array, to do this I use collection method mapWithKeys:

  2. Then after retrieving all products, I loop through each product, check it's productcategory name and push the product into the relevant index, however there's an issue:

ISSUE: I'm only one result added to each empty array sadly, even though there should be atleast TWO results added to each product category.

My method:

public function index()
    {
        $productCategory = ProductCategory::all()->mapWithKeys(function ($category) {
            return [ $category->name => [] ];
        });
        
        $products = Product::with('productcategory')->get();

        foreach($products as $product){
            $category = $product->productcategory->name;
            $productCategory[$category] = $product;
        }
        
        return response()->json([
            'productCategory' => $productCategory,
        ]);
    }

This is the result I'm getting, as you can see only an object is added to each index.

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

Migration file for product and productcategories:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ProductsAndCategories extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //CREATE PRODUCT CATEGORIES TABLE
        Schema::create('productcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->longText('description')->nullable();
            $table->string('image')->nullable();
            $table->timestamps();
        });
        //FILL PRODUCT CATEGORIES TABLE WITH DATA
        DB::table('productcategories')->insert([
            'name' => 'Entrantes',
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Pescados',
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Carnes',
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Sopas',
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Ensaladas',
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Postres',
        ]);


        //  CREATE PRODUCTS TABLE
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('productcategory_id')->index();
            $table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade');
            $table->string('name');
            $table->longtext('description')->nullable();
            $table->string('image')->nullable();
            $table->boolean('isFeatured')->default(false);
            $table->boolean('isVisible')->default(true);
            $table->decimal('halfRationPrice', 5,2)->nullable();
            $table->decimal('fullRationPrice', 5,2)->nullable();
            $table->timestamps();
        });
        DB::table('products')->insert([
            'productcategory_id' => 1,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 1.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 1,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 2.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 2,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 4.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 2,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 5.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 3,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 3.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 3,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 7.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 4,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 6.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 5,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 4.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 5,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 2.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 6,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 2.99,
        ]);
        DB::table('products')->insert([
            'productcategory_id' => 6,
            'name' => 'Nombre del plato',
            'fullRationPrice' => 1.99,
        ]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
        Schema::dropIfExists('productcategories');
    }
}
24 Dec
3 weeks ago

Gabotronix started a new conversation Create An Object Of Arrays From Each Result Of A Query

Hi everybody, I have a query which takes the "name" parameter of all product categories in my backend, what I want to do is create an object of empty arrays where each empty array key is the name of the product category:

public function getProductCategoriesArray()
    {
        $productcategories = ProductCategory::pluck('name')->get();

        return response()->json([
            'productcategories' => $productcategories,
        ]);
    }

As yu can see I'm json encoding the result since I'll be doing some operations on the resulting object/array.

The result would be something like this:

$productCategories = { Category1:[], Category2:[], Category2:[], Category3:[] }

or like this instead? $productCategories = [ Category1:[], Category2:[], Category2:[], Category3:[] ], I'm a bit confused on this one. That is array of arrays or object of arrays, I think the first one is for js objects but may need some clarification on this.

23 Dec
3 weeks ago

Gabotronix started a new conversation Vue: ClearTimer Not Working In My Slider Component

Hi everybody, I'm working in a custom slider component, I have this goToSlider method used to jump to whatever slide rthe user wants by clicking the nav dots, when the method is activated I also clear the interval of the sliders rotation (basically I reset the timer). However this is not working, the timer doesn't reset...

The important method:

goToSlider (sliderIndex) {
        this.activeslider = sliderIndex;
        clearInterval(this.sliderTimer);
    },

Here is my component:

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

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

props: {
    slidercount: {required:true, type: Number},
    sliderinterval: {default: 5000, type: Number},
},

data() {
    return {
        sliderTimer: '',
        activeslider: 1,
    }
},

methods:{


    startSlider() {
        
        this.sliderTimer = setInterval(() => {
            this.nextSlider();
        },  this.sliderinterval)
    },


    prevSlider() {
        if(this.activeslider == 1){
            this.activeslider = this.slidercount;
        }
        else{
            this.activeslider = this.activeslider - 1;
        }
    },


    nextSlider() {
        if(this.activeslider == this.slidercount){
            this.activeslider = 1;
        }
        else{
            this.activeslider = this.activeslider + 1;
        }
    },


    goToSlider (sliderIndex) {
        this.activeslider = sliderIndex;
        clearInterval(this.sliderTimer);
    },

}
};
</script>
22 Dec
3 weeks ago

Gabotronix started a new conversation Declaring A Foreign Key With Single Line On Migrations

Hi everybody, to declare a foreign key in laravel I do it like this:

//  CREATE PRODUCTS TABLE
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('productcategory_id')->index();
            $table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade');
            $table->string('name');
            $table->longtext('description')->nullable();
            $table->string('image')->nullable();
            $table->boolean('isVisible')->default(true);
            $table->decimal('halfRationPrice', 5,2);
            $table->decimal('fullRationPrice', 5,2);
            $table->timestamps();
        });

I was wondering if there's a "cleaner" way to declare it in a single line?

Gabotronix started a new conversation Vue: Child Element Not Animating When Parent "enters"

Hi everybody, I'm making a custom slider where I want the text to float from right to left , the images are working all right but my text never animates, it just stays in its original position, element I want to animate is slider_float_text.

This is my component:

<template>
<section class="slider_maincontainer">
    <transition-group name="slider-fade">
        <div class="slider_item" v-if="activeSlider == 1" :key="1" style="background-image:url('img/photos/dogs35.jpg');">
            <transition name="float-left">
                <span class="slider_float_text" v-if="activeSlider == 1">Locoooo crazy</span>
            </transition>
        </div>
        <div class="slider_item" v-if="activeSlider == 2" :key="2" style="background-image:url('img/photos/dogs31.jpg');">
        </div>
        <div class="slider_item" v-if="activeSlider == 3" :key="3" style="background-image:url('img/photos/dogs30.jpg');">
        </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="{'active_dot_class':index+1 == activeSlider}" 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('MainSlider', ['activeSlider', 'slidersCount']),
},

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

methods:{
    ...mapActions('MainSlider', ['nextSlider', 'prevSlider', 'startSlider', 'goToSlider']),
}
};
</script>
<!--STYLES-->
<style scoped>
.slider-fade-enter { opacity:0;}
.slider-fade-enter-active { transition: opacity 1.5s ease-in-out; }
.slider-fade-enter-to { opacity:1; }
.slider-fade-leave { opacity:1;}
.slider-fade-leave-active { transition: opacity 1.5s ease-in-out; }
.slider-fade-leave-to { opacity:0; }

.slider_float_text{position:absolute; top:40%; left:20%; color:red; font-size:20px;}

.float-left-enter-active {animation: float-left 1.5s;}
.float-left-leave-active {animation: float-left 1.5s reverse;}

@keyframes float-left {
  0% {
    opacity:0;
    transform:translateX(500px);
  }
  75% {
    opacity:0.7;
    transform:translateX(100px);
  }
  100% {
    opacity:1;
    transform:translateX(0px);
  }
}
</style>
21 Dec
3 weeks ago

Gabotronix started a new conversation Getting Call To Undefined Function On Controller

I have a function in my controller I use to generate disocunt tokens, problem is when I hit the store method to create a Discount I get call to undefined method getPercentageChange(), what am I doing wrong in my controller??

<?php

namespace App\Http\Controllers;

use App\Models\Discount;
use App\Models\DiscountCode;
use Illuminate\Http\Request;
use App\Http\Requests\discounts\CreateDiscount;
use App\Http\Requests\discounts\EditDiscount;
use App\Http\Requests\discounts\EditDiscountVisible;
use Carbon\Carbon;

class DiscountController extends Controller
{


    public function index()
    {
        $discounts = Discount::all();
        
        return response()->json([
            'discounts' => $discounts,
        ]);
    }

    
    public function store(CreateDiscount $request)
    {
        $discount = new Discount();
        $discount->title = $request->input('title');
        $discount->body = $request->input('body');
        $discount->originalPrice = $request->input('originalPrice');
        $discount->finalPrice = $request->input('finalPrice');
        $discount->discountPercent = getPercentageChange($request->input('originalPrice'), $request->input('finalPrice'));
        generateCodes($discount, $request->input('codesToGenerate'));
        $discount->save();
        
        return response()->json([
            'discount' => $discount->with('discountcodes'),
        ]);
    }


    public function generateCodes($discount, $codesToGenerate)
    {
        for ($i = 0; $i < $codesToGenerate; $i++) {
            $code = new DiscountCode();
            $code->discount_id = $discount->id;
            $code->unicode = generateRandomToken();
            $code->expireDate = Carbon::now()->addDays(365);
            $code->save();
        }
    }


    public function generateRandomToken()
    {
        do{
            $allCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $character = $allCharacters[rand(0, strlen($allCharacters) - 1)];
            $numbers = mt_rand(0, 999).mt_rand(0, 999);
            $numbers = str_shuffle($numbers);

            $token = $character.$numbers;
            return $token;
        }
        while(!DiscountCode::where('unicode', $token)->get());
    }


    public function getPercentageChange($oldNumber, $newNumber){
        
        $decreaseValue = $oldNumber - $newNumber;
        $percentage = ($decreaseValue / oldNumber) * 100;
    
        return $percentage;
    }
    
    
    public function editVisible(EditDiscountVisible $request)
    {
        $discount = Discount::findOrFail($request->input('id'));
        $discount->isVisible = $request->input('isVisible');
        $discount->save();
        
        return response()->json([
            'discount' => $discount,
            'isVisisble' => $discount->isVisible,
        ]);
    }
    
    
    public function destroy(DeleteDiscount $discount)
    {
        $discount = Discount::findOrFail($request->input('id'));
        $discount->delete();

        return response()->json([
            'discount' => $discount,
        ]);
    }
}

Gabotronix left a reply on Vue: Can't Get Value Of Input Type Number

createDiscount({ commit }, discount) { commit( 'SET_LOAD_STATUS', 1 ); axios.post('/discounts', discount) .then((response) => { commit( 'SET_LOAD_STATUS', 2 ); commit('CREATE_DISCOUNT', response.data.discount); }, (error) => { console.log(error) commit( 'SET_LOAD_STATUS', 3 ); }) },

Gabotronix started a new conversation Vue: Can't Get Value Of Input Type Number

Hi everybody, I have a modal form fr creating a discount model, I send this information to backend with axios, issue is I'm not getting the values of my three inputs with type number.

This is my component (as you can see I send formData object to my backend ):

<template>
<transition name="modal-fade">
<section class="modal_overlay_maincontainer" @click.self="hideModal()">
    <form class="modal_container">
        <i class="modal_close fa fa-times-circle" title="Cerrar" @click="hideModal()"></i>
        <h2 class="modal_title">Nuevo descuento</h2>
        <div class="horizontal_centered_gradient_line"></div>
        <div class="modal_inputs_container">
            <div class="modal_input_column_container">
                <label class="modal_input_label">Imagen:</label>
                <button class="modal_image_container" @click="$refs.image.click()" type="button">
                    <div class="modal_image_button">
                        <i class="modal_image_button_icon fas fa-cog"></i>
                        <span class="modal_image_button_text">Cambiar</span>
                    </div>
                </button>
                <input type="file" ref="image" style="display:none;">
            </div>
            <div class="modal_input_column_container">
                <label class="modal_input_label">Precio original:</label>
                <input class="modal_input_text_small" v-model="originalPrice" type="number" step="0.01" placeholder="0.00">
            </div>
            <div class="modal_input_column_container">
                <label class="modal_input_label">Precio Final:</label>
                <input class="modal_input_text_small" v-model="finalPrice" type="number" step="0.01" placeholder="0.00">
            </div>
            <div class="modal_input_column_container">
                <label class="modal_input_label">Número inicial de códigos:</label>
                <input class="modal_input_text_small" v-model="codesToGenerate" type="number" step="1" placeholder="10" min="1">
            </div>
            <div class="modal_input_column_container">
                <label class="modal_input_label">Titulo:</label>
                <input class="modal_input_text_big" v-model="title" type="text">
            </div>
            <div class="modal_input_column_container">
                <label class="modal_input_label">Contenido:</label>
                <vue-editor class="modal_input_editor" v-model="body" :editorToolbar="customToolbar"></vue-editor>
            </div>
        </div>
        <div class="horizontal_centered_gradient_line"></div>
        <div class="modal_buttons_container">
            <status-loader-lite v-if="loadingStatus > 0" :loadingStatus="loadingStatus"></status-loader-lite>
            <button class="modal_button boot_blue" type="button" @click="getCreateDiscountData()">Guardar</button>
            <button class="modal_button boot_greyer" type="button" @click="hideModal()">Cancelar</button>
        </div>
    </form>
</section>
</transition>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex';
import { VueEditor } from 'vue2-editor';
import { ToolBarConfig } from '../../../config/vue-editor.js';
export default {

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

data() {
    return {
        title: '',
        originalPrice: '',
        finalPrice: '',
        codesToGenerate: '',
        body: '',
        customToolbar: ToolBarConfig
    }
},

computed:{
    ...mapState('Discounts', ['loadingStatus']),
    ...mapState('AdminModal', ['modalPayload'])
},

methods:{

    ...mapActions('Discounts', ['createDiscount']),
    ...mapActions('AdminModal', ['hideModal']),

    getCreateDiscountData() {
                
        let discount = new FormData();
        discount.append('title', this.title);
        discount.append('originalPrice', this.originalPrice);
        discount.append('finalPrice', this.finalPrice);
        discount.append('codesToGenerate', this.codesToGenerate);
        discount.append('body', this.body);
        if( this.$refs.image.files[0] ){ discount.append('image', this.$refs.image.files[0]) };
        this.createDiscount(discount);
    }

}

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

I get a 422 validation error from laravel:

essage  The given data was invalid.
errors  {…}
originalPrice   […]
0   El campo original price es obligatorio.
finalPrice  […]
0   El campo final price es obligatorio.

''the field original price is required"

20 Dec
4 weeks ago

Gabotronix started a new conversation Vue: Adding Classes More Programatically Depending On Index

Hi everybody, I have a component where I display entries from a db using v-for directive, I'm displaying three (3) entries by row inside my flexbox container.

Each of the entries gets a different transitioneffect applied, that is, first, second and third entries get different classes added to them:

For this purpose I use the following logic I came up with:

<div class="reviews_container invisible" v-focus-class:top="'show_invisible'" v-for="(review, index)  in reviews" :key="review.id" :class="{'invisible_slide_first': index == 0, 'invisible_slide_second': index == 1, 'invisible_slide_third': index == 2 }">

This here works perfectly, however I have the feeling this could be done in a better, more "programatically" or automated way, that is, give first class to indexes 0, 3, 6, 9..., give second class to indexes 1,4, 7, 10, 13, 16... you probably see where I'm heading.

I'd appreciate any help in this since I'm still a newbie hehe

This is my full component:

<template>
<section class="reviews_maincontainer">
    <div class="reviews_container invisible" v-focus-class:top="'show_invisible'" v-for="(review, index)  in reviews" :key="review.id" :class="{'invisible_slide_first': index == 0, 'invisible_slide_second': index == 1, 'invisible_slide_third': index == 2 }">
        <span class="reviews_text_small">{{ review.author }}</span>
        <span class="reviews_text_small">{{ review.city }}</span>
        <div class="reviews_image" :style="'background-image:url('+review.image+');'"></div>
        <div class="reviews_text_big" v-html="$options.filters.truncate(review.body, 300)"></div>
        <div class="reviews_ratings_container">
            <i class="reviews_ratings_icon fa fa-star" v-for="(star, index)  in review.rating" :key="index"></i>
        </div>
        <span class="reviews_text_small">{{ review.site }}</span>
    </div>
</section>
</template>
<!--SCRIPTS-->
<script>
export default
{

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

props: ['reviews'],

computed: {
    
},

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

methods:{
 
}
}
</script>
<!--STYLES-->
<style scoped>
.invisible{opacity:0;}
.invisible_left{transform: translateX(-100px);}
.invisible_right{transform: translateX(100px);}
.show_invisible{opacity:1; transform: translate(0, 0) !important; transition: all 1.0s ease-out;}
.invisible_slide_first{transform: translate(0, 150px);}
.invisible_slide_second{transform: translate(0, 100px);}
.invisible_slide_third{transform: translate(0, 50px);}
</style>
19 Dec
4 weeks ago

Gabotronix left a reply on Embedding Image In Laravel Markdown Email

I'm at localhost, maybe it has something to do with it?

18 Dec
4 weeks ago

Gabotronix left a reply on Displaying Unscaped Html In Laravel Markdown Email?

@SNAPEY - Uhmmm, could you elaborate more Snapey, what do yu mean by markdown editor?

{!! $mailData['body'] !!} is working fine

Gabotronix started a new conversation Embedding Image In Laravel Markdown Email

Hi everybody, I'm trying to embed an image into my markdown email but it's not loading correctly.

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

This is my mail template:

@component('mail::message')
# {{ $mailData['title'] }}

![{{ $mailData['appName'] }}]( asset('{{ $mailData['image'] }}'))

{!! $mailData['body'] !!}

Saludos,

{{ $mailData['appName'] }}
@endcomponent

This is the value of $mailData['image']:

'/img/misc/default.jpg'

Any idea how I can do this?

Gabotronix left a reply on Displaying Unscaped Html In Laravel Markdown Email?

Hey I just found the solution, I have to do it like this:

{!! $mailData['body'] !!}

Gabotronix started a new conversation Displaying Unscaped Html In Laravel Markdown Email?

Hi everybody, I have a markdown email with html, this is because I use quill rich text editor to write the mail content down, problem is the html is not applying, that is, if I have soething like this:

<h1><strong>Lorem ipsum</strong></h1>

It should display a bold h1 but instead is displaying the html tags as they are, you can see what I'm talking about here:

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

This html is retrieved from a database.

Here is my email view:

@component('mail::message')
# {{ $mailData['title'] }}

{{ $mailData['body'] }}

Saludos,

{{ $mailData['appName'] }}
@endcomponent

And my mail file justi in case:

<?php

namespace App\Mail;

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

class BulletinMail  extends Mailable
{
    use Queueable, SerializesModels;

    public $mailData;

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

    public function build()
    {
        
        return $this->markdown('emails.bulletin')
            ->from($this->mailData['sender'], $this->mailData['appName'])
            ->subject($this->mailData['subject']);
    }
}

Gabotronix left a reply on Issue With Laravel Mailable And Variables

Oh my god I'm dumb, yeah that was the problem... thank you so much!

Gabotronix left a reply on Issue Sending Markdown Mail

checked with both gmail and hotmail and got the same result

Gabotronix started a new conversation Issue With Laravel Mailable And Variables

Hi everyone, I'm experiencing an issue where my interpolated variables aren't displaying their proper values, instead this is what I see:

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

This is my email view:

<h1>{{ $mailData['title'] }}</h1>
<div>{{ $mailData['body'] }}</div>
<img src="" alt="QR" title="QR" style="display:block; margin-left: auto; margin-right: auto;" width="200" height="200" data-auto-embed="attachment"/>
<span>{{ $mailData['appName'] }}</span>

My mailable file:


<?php

namespace App\Mail;

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

class BulletinMail  extends Mailable
{
    use Queueable, SerializesModels;

    public $mailData;

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

    public function build()
    {
        
        return $this->view('emails.bulletin')
            ->from($this->mailData['sender'], $this->mailData['appName'])
            ->subject($this->mailData['subject']);
    }
}

And my controller where I pass my data:

public function sendBulletinMail(SendBulletinMail $request)
    {
        $bulletin = Bulletin::findOrFail($request->input('id'));
        $emails = Sub::all()->pluck('email');

        $appName = Globals::where('name' , 'appName')->pluck('value')->first();

        $mailData = [
            'appName' => $appName,
            'sender' => config('globals.adminMail'),
            'subject' => $appName.': '.$bulletin->title,
            'title' => $bulletin->title,
            'body' => $bulletin->body,
            'image' => $bulletin->image,
        ];

        foreach ($emails as $email)
        {
            Mail::to( $email )->send(new BulletinMail($mailData));
        };

        //$bulletin->isSent = true;
        //bulletin->sentAt = Carbon::now();
        //$bulletin->save();
        
        return response()->json(['bulletin' => $bulletin]);
    }

Any idea?

17 Dec
1 month ago

Gabotronix started a new conversation Issue Sending Markdown Mail

Hi everybody, so I have a function where I send mails to multiple recipents, the mails are being sent all right but when I check the mail in my inbox markdown doesn't appear to render the mail template properly, this is what I see:

img

This is my mail markdown view:

@component('mail::message')
#{{ $mailData['title'] }}

{{ $mailData['body'] }}

{{ $mailData['appName'] }}
@endcomponent

And my mail file:

<?php

namespace App\Mail;

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

class BulletinMail  extends Mailable
{
    use Queueable, SerializesModels;

    public $mailData;

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

    public function build()
    {
        
        return $this->markdown('emails.bulletin')
               ->from($this->mailData['sender'], $this->mailData['appName'])
               ->subject($this->mailData['subject']);
    }
}

And my controller:

<?php

namespace App\Http\Controllers;

use App\Models\Bulletin;
use Mail;
use App\Models\Sub;
use App\Models\Globals;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests\bulletins\CreateBulletin;
use App\Http\Requests\bulletins\EditBulletin;
use App\Http\Requests\bulletins\DeleteBulletin;
use App\Http\Requests\bulletins\SendBulletinMail;
use App\Mail\BulletinMail;


class BulletinController extends Controller
{

    public function sendBulletinMail(SendBulletinMail $request)
    {
        $bulletin = Bulletin::findOrFail($request->input('id'));
        $emails = Sub::all()->pluck('email');

        $appName = Globals::where('name' , 'appName')->pluck('value')->first();

        $mailData = [
            'appName' => $appName,
            'sender' => config('globals.adminMail'),
            'subject' => $appName.': '.$bulletin->title,
            'title' => $bulletin->title,
            'body' => $bulletin->body,
            'image' => $bulletin->image,
        ];

        foreach ($emails as $email)
        {
            Mail::to( $email )->send(new BulletinMail($mailData));
        };

        //$bulletin->isSent = true;
        //bulletin->sentAt = Carbon::now();
        //$bulletin->save();
        
        return response()->json(['bulletin' => $bulletin]);
    }
16 Dec
1 month ago

Gabotronix started a new conversation Issue Exporting Config Variable Into Vue Component

Hi everyone, I created a config folder in my laravel-vue app, inside config I created globals file where I store following info:

export const globals = {
    responsiveThreshold : '1120px',
};

I then import this file into my vue navbar component, like this:

import { globals } from '../../config/globals.js';

and this is how I use this variable:

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

    
    $(".nav_link").hover(function(){
        let vw = $(window).width();
        if(vw > this.globals.responsiveThreshold){
            $(this).toggleClass("activeLink");
        }
    });
}

Issue is when I hover over the element I get "this.globals is undefined error", any idea?

This is my complete component:

<template>
<nav class="nav_maincontainer">
    <div class="nav_toggle_container">
        <a class="nav_toggle_text" href="/">{{ allglobals.globals.appName }}</a>
        <button class="nav_toggle_button_container" type="button" @click="toggleMenu()">
            <i class="nav_toggle_button_icon fa fa-bars" v-if="!showMenu"></i>
            <i class="nav_toggle_button_icon fas fa-times" v-if="showMenu"></i>
        </button>
    </div>
    <div class="nav_links_container">
        <a class="nav_link nav_head" href="/" title="Página de inicio">
            <span class="nav_link_text">Inicio</span>
        </a>
        <a class="nav_link" href="/quienes-somos">
            <span class="nav_link_text">Quienes somos</span>
        </a>
        <div class="nav_dropdown" style="">
            <a class="nav_link" href="/clases" @click.prevent> 
                <span class="nav_link_text">Clases</span>
                <i class="nav_link_icon fa fa-caret-down"></i>
            </a>
            <div class="nav_dropdown_container">
                <a class="nav_dropdown_link" v-for="classPost in allglobals.layoutLinks.classPosts" :key="classPost.id" :href="'/'+classPost.postcategory.slug+'/'+classPost.slug">
                    <span class="nav_dropdown_link_text">{{ classPost.title }}</span>
                </a>
                <a class="nav_dropdown_link" href="/clases/clases-adiestramiento-canino-por-skype">
                    <span class="nav_dropdown_link_text">Clases por Skype</span>
                    <img class="nav_dropdown_link_skype_icon" src="/img/misc/social/skype.svg">
                </a>
                <a class="nav_dropdown_link activeDropdown" href="/clases" v-bg-color="'#111111'">
                    <span class="nav_dropdown_link_text">Ver todo</span>
                    <i class="nav_dropdown_link_icon far fa-eye"></i>
                </a>
            </div>
        </div>
        <div class="nav_dropdown">
            <a class="nav_link" href="/conducta-canina" @click.prevent>
                <span class="nav_link_text">Problemas de conducta</span>
                <i class="nav_link_icon fa fa-caret-down"></i>
            </a>
            <div class="nav_dropdown_container"> 
                <a class="nav_dropdown_link" v-for="behaviourPost in allglobals.layoutLinks.behaviourPosts" :key="behaviourPost.id" :href="'/'+behaviourPost.postcategory.slug+'/'+behaviourPost.slug">
                    <span class="nav_dropdown_link_text">{{ behaviourPost.title }}</span>
                </a>
                <a class="nav_dropdown_link activeDropdown" href="/conducta-canina" v-bg-color="'#111111'">
                    <span class="nav_dropdown_link_text">Ver todo</span>
                    <i class="nav_dropdown_link_icon far fa-eye"></i>
                </a>
            </div>
        </div>
        <div class="nav_dropdown">
            <a class="nav_link" href="/formate-con-nosotros" @click.prevent>
                <span class="nav_link_text">Formate</span>
                <i class="nav_link_icon fa fa-caret-down"></i>
            </a>
            <div class="nav_dropdown_container">
                <a class="nav_dropdown_link" v-for="trainingPost in allglobals.layoutLinks.trainingPosts" :key="trainingPost.id" :href="'/'+trainingPost.postcategory.slug+'/'+trainingPost.slug">
                    <span class="nav_dropdown_link_text">{{ trainingPost.title }}</span>
                </a>
                <a class="nav_dropdown_link activeDropdown" href="/formate-con-nosotros" v-bg-color="'#111111'">
                    <span class="nav_dropdown_link_text">Ver todo</span>
                    <i class="nav_dropdown_link_icon far fa-eye"></i>
                </a>
            </div>
        </div>
        <div class="nav_dropdown">
            <a class="nav_link" href="/blog" @click.prevent> 
                <span class="nav_link_text">Blog</span>
                <i class="nav_link_icon fa fa-caret-down"></i>
            </a>
            <div class="nav_dropdown_container">
                <a class="nav_dropdown_link" v-for="blogPost in allglobals.layoutLinks.blogPosts" :key="blogPost.id" :href="'/'+blogPost.postcategory.slug+'/'+blogPost.slug">
                    <span class="nav_dropdown_link_text">{{ blogPost.title }}</span>
                </a>
                <a class="nav_dropdown_link" href="/blog" v-bg-color="'#111111'">
                    <span class="nav_dropdown_link_text">Ver todo</span>
                    <i class="nav_dropdown_link_icon far fa-eye"></i>
                </a>
            </div>
        </div>
        <a class="nav_link" href="/ponte-en-contacto">
            <span class="nav_link_text">Contactar</span>
        </a>
        <a class="nav_link" href="/testimonios-de-nuestros-clientes">
            <span class="nav_link_text">Opiniones</span>
        </a>
        <a class="nav_link" href="/preguntas-y-respuestas-frecuentes">
            <span class="nav_link_text">FAQ</span>
        </a>
    </div>
</nav>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex';
import $ from 'jquery';
import { globals } from '../../config/globals.js';
export default
{

name: 'MainNav',

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

data: function () {
    return {
        showMenu: false,
        globals : globals,
    }
},

computed: {
    
},

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

    $.each($('.nav_link'), function( index, link ) {
        if (link.href.split('/')[3] == window.location.href.split('/')[3]) {
            $(link).addClass('activeLink');
        }
    });
    
    $(".nav_link").hover(function(){
        let vw = $(window).width();
        if(vw > this.globals.responsiveThreshold){
            $(this).toggleClass("activeLink");
        }
    });

    $(".nav_dropdown_link").hover(function(){
        let vw = $(window).width();
        if(vw > 1000){
            $(this).toggleClass("activeDropdown");
        }
    });

    $(".nav_dropdown_container").hover(function(){
        let vw = $(window).width();
        if(vw > 1000){
            $(this).parent().children().first('.nav_link').toggleClass('activeLink');
        }
    });
    
    $(".nav_dropdown").hover(function(){
        let vw = $(window).width();
        if(vw > 1000){
            $(this).children('.nav_dropdown_container').first().toggleClass('visible');
        }
    });

    //RESPONSIVE LOGIC

    $(".nav_toggle_button_container").click(function(){
        $('.nav_links_container').toggleClass('visible');
    });

    $(".nav_dropdown").click(function(){
        let vw = $(window).width();
        if(vw < 1000){
            $(this).children('.nav_dropdown_container').first().toggleClass('visible');
            $(this).children('.nav_link').first().toggleClass('activeLink');
        }
    });

},

methods:{

    toggleMenu(){
        this.showMenu = !this.showMenu;
    }
    
}

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

Thanks in advance.

14 Dec
1 month ago

Gabotronix started a new conversation Issue Trying To Show Grouped Array Length

Hi, I have a component where I display all posts grouped by creation date, by months. For each of the twelve months I want to show next to it the total ammount of posts published that month, however I'm getting posts[index] is undefined error.

The posts are being correctly displayed and grouped by month but I can't see the posts by month coun...

This is my component:

<template>
<div class="sidebar_posts_maincontainer">
    <span class="aside_title">Historial 2018</span>
    <div class="sidebar_posts_container" v-for="(posts, month, index) in postsByMonth" :key="index">
        <div class="sidebar_posts_month_container" @click="selectPost(index)">
            <span class="sidebar_posts_month_text">{{ month }}</span>
            <i class="sidebar_posts_month_icon fa fa-angle-down"></i>
            <span class="sidebar_posts_month_count">({{ posts[index].length }})</span>
        </div>
        <div class="sidebar_posts_month_links_container" :class="{'selected_post': activePost === index}">
            <a class="sidebar_posts_month_link" v-for="post in posts" :key="post.id" :href="'/'+post.slug">
                <span class="sidebar_posts_month_link_text">•{{ post.title }}</span>
            </a>
        </div>
    </div>
</div>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapGetters, mapActions } from 'vuex';
import axios from 'axios';
export default
{
name: 'PostsByMonthList',

props: ['category'],

data: function () {
    return {
        activePost: null,
    }
},

computed: {
    ...mapState('Posts', ['posts']),
    ...mapGetters('Posts', ['postsByMonth']),
},

mounted () {
    console.log(this.$options.name+' component successfully mounted');
    if(this.category) this.getPostsByCategory(this.category);
    else this.fetchAllPosts();
},

methods:{
    ...mapActions('Posts', ['fetchAllPosts', 'getPostsByCategory']),
    
    selectPost(index){
        this.activePost = index;
    }
  
}

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

This is my vuex modeule where I group the posts by month:

import axios from 'axios';
import _ from 'lodash';
//STATE
const state = {
    posts: [],
    postcategories: [],
    relatedPosts: [],
    categoryPosts: [],
    loadingStatus:0,
    
}

//GETTERS
const getters = {

    
    postsByMonth: (state) => {
        let months = { Enero:[], Febrero:[], Marzo:[], Abril:[], Mayo:[], Junio:[], Julio:[], Agosto:[], Septiembre:[], Octubre:[], Noviembre:[], Diciembre:[] }
        
        _.forEach(state.posts, function (post) {
            let month = _.upperFirst(Vue.moment(post.created_at).format('MMMM'));

            months[month].push(post);
        });
        
        return months
    },
    
}
12 Dec
1 month ago

Gabotronix left a reply on Issue With Vue Directive And Fixed Navbar

I just tried with this but getting the same effect as before:

Vue.directive('scroll-past-class', {
    isLiteral: true,
    inserted: (el, binding, vnode) => {
        let f = () => {
            let revaluateOffset = true;
            let sticky = null;

            if(revaluateOffset){
                sticky = el.offsetTop;
                revaluateOffset = false;
            }
            
            if (window.pageYOffset > sticky) {
                el.classList.add("sticky");
            }
            else {
                el.classList.remove("sticky");
            }
        }

        window.addEventListener('scroll', f)
        f()
    }
});

Gabotronix left a reply on Issue With Vue Directive And Fixed Navbar

@REALRANDYALLEN - I see, weird that I copied your code but my nav is always sticking to the top now :(

Gabotronix left a reply on Issue With Vue Directive And Fixed Navbar

@REALRANDYALLEN - I fixed the link, thanks for the notice

Gabotronix started a new conversation Issue With Vue Directive And Fixed Navbar

Hi, I decided to give vue directives a go and created one wich checks if the user scrolls past the element and gives it a fixed position on top of viewport, the element gets fixed to the top but when I go back to the element original position it doesn't go back to its relative position, it only does so when I scroll to the top of the page instead, you can see this nasty effect in the gif I attached.

I want to avoid this: blob:https://imgur.com/bc430041-f5ef-42fa-914f-be962d197199

My directive:

Vue.directive('scroll-past-class', { isLiteral: true, inserted: (el, binding, vnode) => { let f = () => {

        let sticky = el.offsetTop;
        
        if (window.pageYOffset > sticky) {
            el.classList.add("sticky");
        }
        else {
            el.classList.remove("sticky");
        }
    }

    window.addEventListener('scroll', f)
    f()
}

});

Sticky class:

.sticky{position:fixed !important; top:0px; box-shadow:3px 3px 6px rgba(0,0,0,0.4);}

11 Dec
1 month ago

Gabotronix left a reply on Javascript Push Removing Previous Item From Array

I decide to make moments a plugin so I can use it everywhere, this is my final code.

postsByMonth: (state) => {
        let months = { Enero:[], Febrero:[], Marzo:[], Abril:[], Mayo:[], Junio:[], Julio:[], Agosto:[], Septiembre:[], Octubre:[], Noviembre:[], Diciembre:[] }
        
        _.forEach(state.posts, function (post) {
            let month = _.upperFirst(Vue.moment(post.created_at).format('MMMM'));
            //alert(month);
            months[month].push(post)
        });
        
        return months
    },

I have a question, in my previous getter I was mutating my state, so in order for getters to work as they should I should return a new variable like I do here right??

Gabotronix started a new conversation Shuffled Objects Of Arrays And Showing Named Keys On V-for Loop

Hi everybody, I have a getter wich takes a collection of posts and groups them by month creation, after some help from the community I got it to work but I found two issues.

  1. First the resulting object was shuffled, that means the original order of the array is no more so the months are displayed with wrong order.
  2. I can't seem to find a way to loop through the collection and display all 12 month names, that is, the named keys of my object. I don't know how to acomplish this honestly.

This is my getter(works but disorders my collection...)

postsByMonth: (state) => {
        let months = { Enero:[], Febrero:[], Marzo:[], Abril:[], Mayo:[], Junio:[], Julio:[], Agosto:[], Septiembre:[], Octubre:[], Noviembre:[], Diciembre:[] }
        
        _.forEach(state.posts, function (post) {
            let month = _.upperFirst(Vue.moment(post.created_at).format('MMMM'));
            //alert(month);
            months[month].push(post);
        });
        
        return months
    },

The loop I'm using (I want to show all 12 month names...)

<ul>
        <li v-for="(month, index) in postsByMonth" :key="index">{{ month }}</li>
    </ul>

This is the shape of my resulting object, notice how the posts were correctly grouped but the order of the months is wrong.

https://i.imgur.com/3nO1s7Z.png

10 Dec
1 month ago

Gabotronix started a new conversation Javascript Push Removing Previous Item From Array

Hi, I have a collection of posts wich I want to group by month of creation (created_at), to do this I'm looping through each post, parsing the date using moments plugin and pushing to the correct array, however there's a problem, I end up with an array of 12 items (months) with only one post per month, I think this is because when I push into array the previous item gets replaced.

My logic:

import axios from 'axios';
import _ from 'lodash';
//STATE
const state = {
    posts: [],
    months : { Enero:[], Febrero:[], Marzo:[], Abril:[], Mayo:[], Junio:[], Julio:[], Agosto:[], Septiembre:[], Octubre:[], Noviembre:[], Diciembre:[] },
    postcategories: [],
    loadingStatus:0,
    
}

//GETTERS
const getters = {

    
    postsByMonth: (state) => {
        return _.forEach(state.posts, function(post) {
            let month = _.upperFirst(Vue.moment(post.created_at).format('MMMM'));
            state.months[month].push(post);
        });
    },

}

I end up with this, as you can see they aren't even properly grouped:

https://i.imgur.com/5CDAfzn.png

Gabotronix left a reply on Issue With Getter

I just tried this way:

postsByMonth: (state) => {
        return _.forEach(state.posts, function(post) {
            //let month = Date.parse(post.created_at).getMonth();
            let date = new Date(post.created_at);
            let month = Date.parse(date).getMonth();
            state.months[month].push(post);
        });
    },

but I'm getting Date.parse(...).getMonth() is not a function error

Gabotronix left a reply on Issue With Getter

I just checked the console and it's giving me an error wich says: "this is undefined", this took me to this debug code:

visiblePosts: function visiblePosts(state) {
        return state.posts.filter(function (post) {
            return post.isVisible === 1;
        }).length;
    },

    postsByMonth: function postsByMonth(state) {
        return __WEBPACK_IMPORTED_MODULE_1_lodash___default.a.forEach(state.posts, function (post) {
            var month = this.moment(post.created_at).format('MMMM');
            state.months[month].push(post);
        });
    }

Gabotronix left a reply on Issue With Getter

@REALRANDYALLEN - Yes, this are all my getters:

//GETTERS
const getters = {

    visiblePosts: state => {
      return state.posts.filter((post) => post.isVisible === 1).length
    },
    
    postsByMonth: (state) => {
        return _.forEach(state.posts, function(post) {
            let month = this.moment(post.created_at).format('MMMM');
            state.months[month].push(post);
        });
    },

}

Gabotronix started a new conversation Issue With Getter

Hi, I tried making a getter that takes a collection of posts , loops through each post and checks for month of creation (created_at), I do this by parsing the date to months with vue-moment plugin.

However the getter is returning empty...

Also does my getter modify my posts arry?

import axios from 'axios';
import _ from 'lodash';
//STATE
const state = {
    posts: [],
    months : { January:[], February:[], March:[], April:[], May:[], June:[], July:[], August:[], September:[], October:[], November:[], December:[] },
    postcategories: [],
    loadingStatus:0,
    
}

//GETTERS
const getters = {

 
    
    postsByMonth: (state) => {
        return _.forEach(state.posts, function(post) {
            let month = this.moment(post.created_at).format('MMMM');
            state.months[month].push(post);
        });
    },

}

09 Dec
1 month ago

Gabotronix started a new conversation Adding More Logic To Laravel Register Method

Hi, I'm using laravel's auth system, waht I do is send a POST axios call to laravel's auth /register route, via form , this has worked pretty well so far.

Problem is now I want to populate my user with more attributes upon creation, however I don't knw how to get this to work, I dug in my RegisterController and changed register method but it's not saving my "word" attribute :(

Inside my RegisterController (notice how I added word field to $data array

/**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'word' => $data['word'],
        ]);
    }

My vuex Auth module, here I send ajax call to register route

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

My compinent:

<template>
<form class="auth_modal_maincontainer">
    <h1 class="auth_modal_title">REGISTRATE</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">
                <label class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fa fa-user"></i>
                </label>
                <input class="auth_modal_inputs_input" v-model="credentials.name" name="name" type="text" placeholder="NOMBRE DE USUARIO" required autofocus>
            </div>
        </div>
        <div class="auth_modal_inputs_column_container">
            <div class="auth_modal_inputs_container">
                <label class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fa fa-at"></i>
                </label>
                <input class="auth_modal_inputs_input" v-model="credentials.email" type="email" placeholder="EMAIL" required>
            </div>
        </div>
        <div class="auth_modal_inputs_column_container">
            <div class="auth_modal_inputs_container">
                <label class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fa fa-lock"></i>
                </label>
                <input class="auth_modal_inputs_input" v-model="credentials.password" type="password" placeholder="CONTRASEÑA" required>
            </div>
        </div>
        <div class="auth_modal_inputs_column_container">
            <div class="auth_modal_inputs_container">
                <label class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fas fa-redo"></i>
                </label>
                <input class="auth_modal_inputs_input" v-model="credentials.password_confirmation" type="password" placeholder="CONFIRMAR CONTRASEÑA" required>
            </div>
        </div>
        <div class="auth_modal_inputs_column_container">
            <div class="auth_modal_inputs_container">
                <label class="auth_modal_inputs_icon_container">
                    <i class="auth_modal_inputs_icon fas fa-redo"></i>
                </label>
                <input class="auth_modal_inputs_input" v-model="credentials.word" type="text" placeholder="PALABRA" required>
            </div>
        </div>
        <div class="auth_modal_row_container">
            <input class="auth_modal_row_checkbox" type="checkbox" v-model="credentials.remember">
            <span class="auth_modal_row_text">Recordarme</span>
        </div>
        <div class="auth_modal_errors_maincontainer">
            <div class="auth_modal_errors_loading_container" v-if="loadingStatus === 1">
                <i class="auth_modal_errors_loading_icon fa fa-spinner fa-spin"></i>
            </div>
            <div class="auth_modal_errors_error_container" v-if="loadingStatus === 3" 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>
        <auth-status-loader :loadingStatus="loadingStatus"></auth-status-loader>
    </div>
    <span class="horizontal_centered_gradient_line"></span>
    <div class="auth_modal_buttons_container">
        <button class="auth_modal_buttons_button boot_green" @click="onGetRegisterData()" type="button"><i class="auth_modal_buttons_button_icon fas fa-sign-in-alt"></i>REGISTRAR</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>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex';
export default
{

name: 'RegisterForm',
data: function () {
    return {
        credentials: {
            name: '',
            email: '',
            password: '',
            word: '',
            password_confirmation: '',
            remember:''
        }
    }
},

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

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

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

    onGetRegisterData() {

        this.register(this.credentials);
    },
      
}
}
</script>
<!--STYLES-->
<style scoped>
</style>


Gabotronix started a new conversation List Posts By Month And Display "empty" Months

Hi, so I'm retrieving all posts from my database and grouping them by their created_at (month), then I display a list of months with their posts inside each month item, this works but I'd like to also show a month item even if doesn't hold any posts inside, basically I want to display ALL months and not only the months where posts were published.

Here is my component:

<template>
<div class="sidebar_posts_maincontainer">
    <span class="aside_title">Historial 2018</span>
    <div class="sidebar_posts_container" v-for="(month, index)  in posts" :key="index">
        <div class="sidebar_posts_month_container" @click="selectPost(index)">
            <span class="sidebar_posts_month_text">{{ month[0].created_at | moment('MMMM') | capitalize }}</span>
            <i class="sidebar_posts_month_icon fa fa-angle-down"></i>
        </div>
        <div class="sidebar_posts_month_links_container" :class="{'selected_post': activePost === index}">
            <a class="sidebar_posts_month_link" v-for="post of month" :key="post.id" :href="'/'+post.slug">
                <span class="sidebar_posts_month_link_text">•{{ post.title }}</span>
            </a>
        </div>
    </div>
</div>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import axios from 'axios'
export default
{
name: 'PostsByMonthList',

props: ['category'],

data: function () {
    return {
        activePost: null,
    }
},

computed: {
    ...mapState('PostsByMonthList', ['posts']),
},

mounted () {
    console.log(this.$options.name+' component successfully mounted');
    if(this.category) this.getCategoryPostsByMonth(this.category);
    else this.getAllPostsByMonth();
},

methods:{
    ...mapActions('PostsByMonthList', ['getAllPostsByMonth', 'getCategoryPostsByMonth']),
    
    selectPost(index){
        this.activePost = index;
    }
  
}


}
</script>
<!--STYLES-->
<style scoped>
.selected_post{height:auto !important;}
.sidebar_posts_maincontainer{width:100%; height:auto; display:flex; flex-direction:column; margin:15px 0px;}
.sidebar_posts_title{font-size:16px; color:rgba(0,0,0,0.7); font-weight:600; margin-bottom:15px;}
.sidebar_posts_container{width:100%; height:auto; display:flex; flex-direction:column; margin:2px 0px;}
.sidebar_posts_month_container{width:100%; height:35px; border-radius:5px; cursor:pointer; background-color:rgb(235,235,235); border:1px solid rgba(0,0,0,0.2); display:flex; align-items:center; padding:5px 10px;}
.sidebar_posts_month_text{font-size:15px; color:rgba(0,0,0,0.7); font-weight:600;}
.sidebar_posts_month_icon{font-size:16px; color:rgba(0,0,0,0.7); margin-left:auto;}
.sidebar_posts_month_links_container{width:100%; height:0px; display:flex; flex-direction:column; overflow:hidden; transition:all 400ms ease;}
.sidebar_posts_month_link{width:100%; height:30px; border-radius:5px; background-color:rgba(0,0,0,0.0); display:flex; align-items:center; padding:5px; margin:2px 0px;}
.sidebar_posts_month_link_text{color:rgba(0,0,0,0.7); font-size:15px;}
</style>
08 Dec
1 month ago

Gabotronix started a new conversation Using An Svg Image On My Component

I have saved a svg file into my public directory, the path is as follows:

public/img/credit-cards/card-logo-visa.svg

Now I added this into my component template:

<img src="/img/credit-cards/card-logo-visa.svg" alt="" style="outline:1px solid red;">

However the image is not displaying since I'm getting a 404 error?