Gabotronix

Gabotronix

Member Since 1 Year Ago

Experience Points
23,490
Total
Experience

1,510 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
45
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 5
23,490 XP
Nov
12
19 hours ago
Activity icon

Started a new Conversation SQLSTATE[22007]: Invalid Datetime Format: 1366 Incorrect Integer Value: 'true' For Column 'isVisible'

Hi everybody, I'm sending data with FormData object to my laravel backend, issue is I have a checkbox input which is causing me trouble, my backend logs the following error message:

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'true' for column 'isVisible' ...

In my migrations isVisible field is declared as a boolean:

$table->boolean('isVisible')->default(false);

If I hack into the payload and send an 1 instead of 'true' or 0 instead of 'false' my Post entry is created succesfully.

Any idea how I can solve this?

Nov
11
1 day ago
Activity icon

Started a new Conversation Model Not Returning Properties With Default Value After Creation

Hi everybody, in my controller after I create a new Post I return the new post in a post variable, for some reason I don't get the properties with default values back, I noticed if I set the value to something in controller it does indeed return the properties in the payload.

public function create(Request $request)
    {
        $validatedData = $request->validate(PostValidator::$create);
        
        $post = new Post();
        $post->postcategory_id = $request->input('postcategoryid');
        $post->user_id = $request->input('authorid');
        $post->thumbnail = $this->uploadFile($request, 'thumbnail', config('app.defaultImage'));
        $post->video = $request->input('video');
        $post->slug = $this->slugify($request->input('title'));
        $post->url = '/publicaciones/'.$this->slugify($request->input('title'));
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->isVisible = false; //IF I DO THIS isVisible is returned in $post variable
        $post->save();

        $post->load(['postcategory','author']);
        
        return response()->json([
            'post' => $post,
        ]);
        
    }
Activity icon

Started a new Conversation Question About Server Date And Laravel Cron Jobs

Hi everybody, I just learnt about cron jobs in the server and larave crons, in my laravel apps I set timezone in .env file like this:

APP_TIMEZONE='Europe/Madrid'

Now in my ubuntu VPS I ran the command

date

And noticed it says UTC with one hour earlier than my local time (one hour less sorry for english), Now I have two questions:

When I run a cron job from laravel using the schedule command what time does the app take into account to run the commands, my VPS time (UTC, one hour less) or my laravel app time (Europe/Madrid)?

I want to fix my VPS time so its the same as my local time (changing it to UTC+1 would fix it) , how can I change the date/timezone? Is it a good idea to do this?

Nov
09
3 days ago
Activity icon

Started a new Conversation Help With Spread Operator On Laravel Blade

Hi everybody, my app is based on a bunch of empty blade templates filled with vue components, I pass props to this components and this props come from my backend through Vue prototype global variables, I'm trying to pass to my component only item 1 and 2 of an array of three, I know I could do this with computed property but I'm trying to do this with spread operator and inline.

I'm getting the following error:

Error in render: "TypeError: $app.globals.allSections[0] is not iterable"

This is how it looks in my blade template:

@extends('layouts.master')
@section('content')
<v-wrapper :jc="'space-around,flex-start'" :h="'calc(100vh - var(--navHeight)),auto'" :p="'20px,10px'">
    <layout-card-7 v-for="item in [ ...$app.globals.allSections[0], ...$app.globals.allSections[1] ]" :item="item" :key="item.id"></layout-card-7>
</v-wrapper>
@endsection

Is there another way to achieve this in a single line?

Nov
08
4 days ago
Activity icon

Started a new Conversation SQLSTATE[HY000]: General Error: 1364 Field 'parent_id' Doesn't Have A Default Value

Hi everybody, I'm building my own forum as practice, I set up Topic and Comment models with polymorphic relationship, a comment can belong to a topic or another comment, this is because I want to have nested comments. Another issue is when I reply to the topic I get the following error:

SQLSTATE[HY000]: General error: 1364 Field 'parent_id' doesn't have a default value (SQL: insert into `comments` (`user_id`, `body`, `commentable_id`, `commentable_type`, `updated_at`, `created_at`) values (1, <p>ljlnlnlnlnlnllnlnlnlnlnln</p>, 1, App\Models\Topic, 2019-11-08 20:41:43, 2019-11-08 20:41:43))

My models and Migrations.

Topic model:

class Topic extends Model
{
    
    
    protected $table = 'topics';
    
    public function author()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

    public function comments()
    {
        return $this->morphMany('App\Models\Comment', 'commentable')->whereNull('parent_id');
    }

public function up()
    {
        Schema::create('topics', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->index();
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('title');
            $table->text('body');
            $table->string('url')->unique();
            $table->string('slug')->unique();
            $table->boolean('isVisible')->default(false);
            $table->timestamps();
        });
    }


}

Comment model:

class Comment extends Model
{
    
    
    protected $table = 'comments';

    public function author()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

    public function replies()
    {
        return $this->hasMany('App\Models\Comment', 'parent_id');
    }


}


public function up()
    {
    Schema::create('comments', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->integer('user_id')->unsigned();
       $table->integer('parent_id')->unsigned();
       $table->integer('commentable_id')->unsigned();
       $table->string('commentable_type');
       $table->text('body');
       $table->timestamps();
    });
    }
Activity icon

Started a new Conversation Paginate Polymorphic Relationship, Topic->comments()

Hi everybody, I'm building a basic forum, there are many topics and each topic has comments, a comment or "commentable" can be a a comment or a reply (commented a comment), this is because I want to have nested comments, that's where parent_id is useful. I'm wondering if my polymorphic relationship is the best way to achieve this so I'm open to any suggestions. The first issue I came up with is I don't know hw to do ajax pagination of topic->comments ..., I thought with something like Comment::whereHas('topic') ... but my comments dont' have a topic relationship defined in the model.

I'm using laravel advanced ajax pagination, how can I paginate comments?

Topic model:

class Topic extends Model
{
    
    
    protected $table = 'topics';
    
    public function author()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

    public function comments()
    {
        return $this->morphMany('App\Models\Comment', 'commentable')->whereNull('parent_id');
    }

public function up()
    {
        Schema::create('topics', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->index();
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('title');
            $table->text('body');
            $table->string('url')->unique();
            $table->string('slug')->unique();
            $table->boolean('isVisible')->default(false);
            $table->timestamps();
        });
    }


}

Comment model:

class Comment extends Model
{
    
    
    protected $table = 'comments';

    public function author()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

    public function replies()
    {
        return $this->hasMany('App\Models\Comment', 'parent_id');
    }


}


public function up()
    {
    Schema::create('comments', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->integer('user_id')->unsigned();
       $table->integer('parent_id')->unsigned();
       $table->integer('commentable_id')->unsigned();
       $table->string('commentable_type');
       $table->text('body');
       $table->timestamps();
    });
    }

This is where I took inspiration:

Nov
04
1 week ago
Activity icon

Started a new Conversation Remove @mailservice.com From Email String With PHP

Hi everybody, in PHP I want to get only the characters before "@", if I get [email protected] I want to get supercool back.

Oct
30
1 week ago
Activity icon

Started a new Conversation Using Laravel Scout Tntsearch Driver With Other Eloquent Methods For Sorting/filtering.

Hi everybody, in my larave-vue app I want to be able to filter by a search term using laravel scout tntsearch, along with this I also perform additional filtering, sorting or where clauses in my controller. I can't get both to work correctly in my app.

In my controller I have this:

$posts = Post::filter($filters)->search($request->input('query'))->paginate(0);
            $posts->load(['postcategory.section','author']);

            if($posts->isEmpty())
            {
                return response()->json([
                    'message' => 'No results found',
                ],500);    
            }

            return response()->json([
                'message' => 'Results found',
                'posts' => $posts,
            ]);

It gives me the following error:

Call to undefined method Illuminate\Database\Eloquent\Builder::search()

For some reason It's not working, I have tried changing the order of the filter, search and paginate but I still get errors.

In case you are wondering how does my filter method works it's basically a scope

You can read an indepth write up about it here:

https://medium.com/@mykeels/writing-clean-composable-eloquent-filters-edd242c82cc8

See my QueryFilters and Filterable trait bellow just in case

<?php
namespace App\Filters;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class QueryFilters
{
    protected $request;
    protected $builder;
  
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function title($term)
    {
        $lowerCaseTerm = strtolower($term);
        return $this->builder->where('title', 'LIKE', "%$lowerCaseTerm%");
    }

    public function postCategory($term)
    {

        return $this->builder->whereHas('postcategory', function ($query) use ($term){
            $query->where('id', $term);
        });
    }

    public function sort($term)
    {
        $sortArray = explode(",", $term);

        for($i = 0; $i <= $sortArray.length; $i++)
        {
            $sortBy = substr_replace($sortArray[i], "", -1);

            $sortChar = substr($sortArray[i], -1);
        
            $sortOrder = $sortChar == '+' ? 'ASC' : 'DESC';  
           
            $this->bulider->orderBy($sortBy, $sortOrder);
        }

        return $this->builder;
    }
  
    public function apply(Builder $builder)
    {
        $this->builder = $builder;
        foreach ($this->filters() as $name => $value)
        {
            //if method doesn't exists continue out of the loop 
            if ( ! method_exists($this, $name))
            {
                continue;
            }
            //method exists so check if it has a value payload so call the method with arguments
            if (strlen($value)) 
            {
                $this->$name($value);
            } 
            //it doesn't have a payload so call the method without arguments
            else 
            {
                $this->$name();
            }
        }
        return $this->builder;
    }
  
    public function filters()
    {
        //returns associative array of request body key value pairs
        return $this->request->all();
    }

}

And Filterable Trait

<?php
namespace App\Filters;

use Illuminate\Database\Eloquent\Builder;

trait Filterable
{
    public function scopeFilter($query, QueryFilters $filters)
    {
        return $filters->apply($query);
    }
}
Oct
29
2 weeks ago
Activity icon

Started a new Conversation Is It Safe To Use Dynamic-imported Components In Vue With Laravel-mix

Hi everybody, I tried dynamic importing of vue components to increase performance of my app by loading components async and only when needed, as yu can see in the links bellow I had lots of problems with trying to get this to work, so I decided to ditch the idea, now I'm wondering if thave there been any news about this?

https://laracasts.com/discuss/channels/elixir/laravel-mix-dynamic-imports

https://laravel-mix.com/docs/5.0/upgrade

laravel and vue are used a lot so it's rare to see such a crazy bug hasn't been fixed yet.

Oct
27
2 weeks ago
Activity icon

Started a new Conversation Issue With Composer And Tntsearch

I'm trying to install tnt search driver for laravel scout with composer but I'm getting the following error:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - teamtnt/tntsearch v2.1.0 requires ext-sqlite3 * -> the requested PHP extension sqlite3 is missing from your system.
    - teamtnt/tntsearch v2.0.0 requires ext-sqlite3 * -> the requested PHP extension sqlite3 is missing from your system.
    - teamtnt/laravel-scout-tntsearch-driver v7.2.0 requires teamtnt/tntsearch 2.* -> satisfiable by teamtnt/tntsearch[v2.0.0, v2.1.0].
    - Installation request for teamtnt/laravel-scout-tntsearch-driver ^7.2 -> satisfiable by teamtnt/laravel-scout-tntsearch-driver[v7.2.0].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\xampp\php\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

My composer.json file:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": "^7.1.3",
        "andreasindal/laravel-markdown": "3.0.1",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "^6.3",
        "kriswallsmith/buzz": "^1.0",
        "laracasts/utilities": "^3.0",
        "laravel/framework": "5.8.*",
        "laravel/scout": "^7.2",
        "laravel/tinker": "^1.0",
        "mailgun/mailgun-php": "^3.0",
        "nao-pon/flysystem-google-drive": "~1.1",
        "nyholm/psr7": "^1.1",
        "spatie/laravel-backup": "^6.2",
        "teamtnt/laravel-scout-tntsearch-driver": "^7.2"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.0",
        "stripe/stripe-php": "^7.4.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

I'm using XAMP in my windows machine for development.

Activity icon

Started a new Conversation Addd Partial Blade View Template To All Views?

Hi everybody, I have a partial view with a script I want to include in all my views, I dont't wanna @include this partial in all my layouts and blade views but instead add it to all rendered views, my partial looks like this:

<script type="text/javascript">window.$app = {!! json_encode(app(App\Helpers\Javascript::class)->app) !!};</script>

How can I do this?

Oct
26
2 weeks ago
Activity icon

Started a new Conversation CSS: Make Hollow And See Through Element

Hi everybody, my design has a circle between a white colored and red colored panel, as you can see in the image bellow I use a white border on the circle so that it looks like there's nothing surroinding the circle, sadly since my background has a linear gradient the white strikes badly, I could make the background pure white but first I wanna know if it's be possible to achieve my desired effect with CSS?

https://i.imgur.com/W71YUtp.jpg

Oct
25
2 weeks ago
Activity icon

Started a new Conversation Where Do You Find Inspiration For Your UI Layouts With CSS/HTML

Hi everybody, I was wondering where do you guys find inspiration for your web layout designs, I recently came up with premast in instagram,

https://www.instagram.com/premast.co/?hl=en

they upload many good looking web thems and designs there, I generally look for some insteresting designs and web layouts, maybe some CSS shapes, nice color matching and gradients and basic web layout structuring, nothing too fancy, I use these for inspiration, copy them or maybe give it a spin of my own.

https://i.imgur.com/CMmFo3v.jpg

Activity icon

Started a new Conversation Stacking Clip-path Hexagon Shapes With CSS?

Hi everybody, after trying out clip-path property I finally got my hexagon shape working, now I want to have hexagons "stack" into each other like kind of a beehive, I know I could do this with absolute positioning but this seems le not the best approach tbh.

I want something similar to this: https://i.imgur.com/1dUjUj3.jpg

HTML

<div class="poligon"></div>
<div class="poligon"></div>

CSS:

.poligon {
  display: inline-block;
  position: absolute; top:50px; right:50px;
  width: 300px;
  height: 300px;
  background: red;
  box-sizing: border-box;
  clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
}
Oct
24
2 weeks ago
Activity icon

Started a new Conversation CSS: Align Horizontally With Respect To Viewport Child Of Rotated Element

Hi everybody, I'm making a css solar system with css, I got the orbits and planets right but now each "planet" has a text box placed outside of it, I'm having difficulties with having the text boxes horizontally aligned with respect to viewport and to the left side, take a look at this image bellow:

https://i.imgur.com/sDE84Uf.jpg

https://jsfiddle.net/31Lvs75w/

Oct
22
3 weeks ago
Activity icon

Started a new Conversation CSS Concentric Circles With Orbiting "planets"

Hi everybody, I'm trying to render a "solar system" diagram only with css, the concentric circles are easy to do with css border-radius, border and some transforms but I'm trying to find a way to have the little "planets" adhere to the "orbits" or colored borders. There has to be a more precise way to achieve this

If you look at this image you will see what I'm trying to do: https://i.imgur.com/xXRCU9C.jpg

And how it currently looks, sorry for inline css... https://i.imgur.com/UrYmeHS.jpg

<div style="width:100%; height:100vh; padding:0px; background-color:white; display:flex; flex-direction:column; position:relative; align-items:flex-end;">
        <div style="width:250px; height:250px; position:absolute; border-radius:50%; background-color:red; top:50%; transform:translateY(-50%) translateX(50%);  right:0px"></div>
        <div style="width:450px; height:450px; position:absolute; border-radius:50%; border:2px solid red; top:50%; transform:translateY(-50%) translateX(50%);  right:0px"></div>
        <div style="width:650px; height:650px; position:absolute; border-radius:50%; border:2px solid red; top:50%; transform:translateY(-50%) translateX(50%);  right:0px"></div>
        <div style="width:850px; height:850px; position:absolute; border-radius:50%; border:2px solid red; top:50%; transform:translateY(-50%) translateX(50%);  right:0px"></div>
        <div style="position:absolute; height:70%; width:100px; top:50%; transform:translateY(-50%); right:15%; outline:1px solid red;">
            <div style="width:25px; height:25px; border-radius:50%; border:1px solid red; position:absolute; top:0px; left:0px;"></div>
            <div style="width:25px; height:25px; border-radius:50%; border:1px solid red; position:absolute; transform:translateY(-50%); top:50%; right:100%;"></div>
            <div style="width:25px; height:25px; border-radius:50%; border:1px solid red; position:absolute; bottom:0px; left:0px;"></div>
        </div>
        <div style="position:absolute; height:80%; width:100px; top:50%; transform:translateY(-50%); right:55%; outline:1px solid red;">
            <div style="width:50px; height:50px; border-radius:50%; border:1px solid red; position:absolute; top:0px; left:0px;"></div>
            <div style="width:50px; height:50px; border-radius:50%; border:1px solid red; position:absolute; transform:translateY(-50%); top:50%; right:100%;"></div>
            <div style="width:50px; height:50px; border-radius:50%; border:1px solid red; position:absolute; bottom:0px; left:0px;"></div>
        </div>
    </div>
Oct
21
3 weeks ago
Activity icon

Started a new Conversation Vue: Choosing Html Element Type With Props

Hi everybody, I have a vue component which can be either a button or a link, I want to have a prop called 'type' which accepts a string 'button' or 'link', is there a way to programatically render such component without a hacky v-if?

Oct
18
3 weeks ago
Activity icon

Started a new Conversation Get Url Query String Value With Javascript

Hi everybody, I have a laravel-vue app where after a vue component is mounted I want to chek if the url has the a given query string parameter and its value, for example given this url:

/?show-login-form=1

On compoennt mounted I want to check if url is login-form == true, how would you approach this situation?

Activity icon

Replied to Can't Use Laravel Singleton Inside Middleware

I fixed it by adding

use App\Helpers\Javascript;

to my Middleware! After trying your way it works too, interesting.

Activity icon

Replied to Issue With Sending Data From My Backend To Frontend After Redirect

Clever and simple, I'll wait a bit more to see if people have more ideas but I'll probably mark your reply as best answer

Activity icon

Started a new Conversation Issue With Sending Data From My Backend To Frontend After Redirect

Hi everybody, I have an auth middleware which redirects back to home page if you are not logged in, once the user is redirected to home page I want to open a modal for him to log in via checking if showLoginModal is true or something like that, currently in order to send data from my laravel backend to my vue frontend I created a singleton from my Javascript helper class, this has been working all right so far but when redirected I can't access my backend variables in my vue components.

How would you guys go about this?

Here is my Middleware:

<?php
namespace App\Http\Middleware;


use Closure;
use Illuminate\Http\Request;
use App\Helpers\Javascript;
use Auth;



class AuthAdmin
{


    public function handle($request, Closure $next)
    {
        $user = Auth::user();

        if($user && $user['privileges'] > 2)
        {
            return $next($request);   
        }

        app(Javascript::class)->put(['showLoginModal' => true]);

        return redirect('/');
        
    }
}

And my Javascript helper class:

<?php
namespace App\Helpers;


use Illuminate\Http\Request;


class Javascript
{
    public $app = [];

    public function put($array)
    {
        $this->app = array_merge($this->app, $array);
    }
  
}

In my blade master layout I have something like this:

<script type="text/javascript">window.$app = {!! json_encode(app(App\Helpers\Javascript::class)->app) !!};</script>
Activity icon

Started a new Conversation Lodash Filter Not Working With Multiple Conditions

Hi everybody, I'm using lodash library to filter an array of objects but for some reason the filter it's returning the same value I pass to it, any idea what am I doing wrong?

This is the function I use to transform data:

getFlattenFields(schema)
    {
        let flatten = _.flatten(schema.fields);
        console.log('flatten',flatten);
        let filtered = _.filter(flatten, item => item.element != 'loader' || item.element != 'button' );
        console.log('filtered',filtered);
        return filtered;
    },

And my schema variable is this object:

formSchema: 
    {
        fields: 
        [
            [ 
                { id: 'email', label: '', default: '', element:'input', type: 'text' },
                { element: 'button', text:'Enviar', icon:'fas fa-reply' }, 
            ],
            [
                { element: 'loader' }, 
            ]
        ]
    }
Activity icon

Replied to Programatically Check If Mailgun Mail Was Sent Correctly With PHP SDK

That package seems abandoned so I decided to use PHP SDK instead, all I want is to check if email was sent succesfully right after, is that even possible?

Activity icon

Replied to Can't Use Laravel Singleton Inside Middleware

I added the error message to OP

Activity icon

Started a new Conversation Programatically Check If Mailgun Mail Was Sent Correctly With PHP SDK

Hi everybody, I 'm tinkering with Mailgun's PHP SDK in my laravel app, the emails are sent correctly after checking Mailgun's dashboard but I'm wondering if there's a way to get a confirmation programatically, currently I'm getting back an empty variable from my sendMail trait:

<?php
namespace App\Traits;


trait SendMail
{

    public function sendMail($view, $mailData, $subject, $to)
    {
        $html = view($view, compact('mailData'))->render();

        $result = app(Mailgun::class)->messages()->send(config('mail.mailgun.domain'), [
            'from' => config('mail.from.name').' <'.config('mail.from.address').'>',
            'to' => $to,
            'subject' => $subject,
            'html' => $html,
        ]);
        
        return $result;
    }

    
}

Here, result returns an empty array, always... how can I know if mail was sent with my code without checking Mailgun's dashboard or my mail inbox. Thanks in advance.

Activity icon

Started a new Conversation Can't Use Laravel Singleton Inside Middleware

I have a custom middleware where I want to use a singleton I use to pass php variables into my frontend, however I get the following error:

 ReflectionException (-1)
Class App\Http\Middleware\Javascript does not exist

My middleware:

<?php
namespace App\Http\Middleware;


use Closure;
use Illuminate\Http\Request;
use Auth;



class AuthAdmin
{


    public function handle($request, Closure $next)
    {
        $user = Auth::user();

        if($user && $user['privileges'] > 2)
        {
            return $next($request);   
        }

        app(Javascript::class)->put(['showLoginModal' => true]);

        return redirect('/');
        
    }
}

My ServiceProvider:

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Helpers\Javascript;


class JavascriptServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Javascript::class, Javascript::class);
    }
}

composer dump-autoload didn't fix anything, I have been having problems where the Javascript Class is not found for some reason, any ideas or sugestions?

Oct
14
4 weeks ago
Activity icon

Started a new Conversation Help With Stripe Subscription And PaymentIntents API

Hi everybody, I use Stripe PHP's SDK for handling charges in Europe, I just recently got on-session charges working using PaymentIntent's API in regulation with SCA rules, now I want to have users be able to subscribe to various plans for monthly payments, reading the docs and looking in the internet for examples using PaymentIntent's API for recurring examples hasn't helped much, so my question is how can I hanfle it?

My workflow is like this:

  1. Collect a payment method with elements and create stripe customer
  2. User chooses plan
  3. Subscribe user for recurring payments

This is my controller method, how can I complete subscription using PaymentIntent:

public function addSubscription(Request $request)
    {    
        $validatedData = $request->validate(StripeValidator::$addSubscription);

        $customer = Auth::check() && Auth::user()->stripeId ? Customer::retrieve(Auth::user()->stripeId) : false;

        if(!$customer)
        {
            return response()->json([
                'message' => 'Registrate para disfrutar de nuestras mejores promociones.',
            ], 500);
        }

        $paymentMethod = PaymentMethod::retrieve($request->input('paymentMethodId'));

        $plan = Plan::create([
            "product" => 
            [
                "name" => "Product name"
            ],
            "interval" => "month",
            "interval_count" => "1",
            "currency" => "eur",
            "amount" => "3000",
        ]);

        $subscription = Subscription::create([
            "customer" => $customer->id,
            "items" => 
            [
                ["plan" => $plan->id ],
            ],
        ]);

        return response()->json([
            'subscription' => $subscription,
            'message' => 'Te suscribiste a el plan con éxito.',
        ], 200);
    }

And just in case here is how I handle one-off on-session payments:

public function createCustomerAndPaymentMethod(Request $request)
    {
        $validatedData = $request->validate(StripeValidator::$createCustomerAndPaymentMethod);
        
        $user = Auth::user();
        
        if(!$user){
            return response()->json([
                'message' => 'Debes estar registrado para realizar una compra.',
            ], 400);
        }

        $customer = Customer::create([
            'email' => $user['email'],
            "description" => 'Customer for'.config('app.name')
        ]);

        $user->stripeId = $customer->id;
        $user->save();

        $paymentMethod = PaymentMethod::retrieve($request->input('paymentMethodId'));
        $paymentMethod->attach(['customer' => $customer->id]);

        $paymentMethods = PaymentMethod::all([
            'customer' => $customer->id,
            'type' => 'card',
        ]);

        return response()->json([
            'message' => 'Añadiste una tarjeta como forma de pago.',
            'customer' => $customer,
            'paymentMethods' => $paymentMethods
        ]);
    }


    public function confirmPayment(Request $request)
    {
        $customer = Auth::check() && Auth::user()->stripeId ? Customer::retrieve(Auth::user()->stripeId) : false;

        if(!$customer)
        {
            return response()->json([
                'message' => 'Registrate para disfrutar de nustras mejores promociones.',
                'customer' => null,
            ], 500);
        }

        //dd( $request->input('paymentMethodId'));
        
        $paymentIntent = PaymentIntent::create([
            'payment_method' => $request->input('paymentMethodId'),
            'customer' => $customer->id,
            'amount' => 2000,
            'currency' => 'eur',
            'confirmation_method' => 'manual',
            'payment_method_types' => ['card'],
            'confirm' => true,
            'setup_future_usage' => 'on_session',
        ]);

        $this->generatePaymentResponse($paymentIntent);
    }

Any suggestion is welcomed, there's not much documentation about this ...

Activity icon

Started a new Conversation Issue With Dependency Injection

I just learnt of laravel's service container and dependency injection, in order to try this out I created a MailgunServiceProvider to instantiate mailgun client, I laso have a trait called SendMail which acts as a wrapper for Mailgun:

However the $mailgun variable returns null, I'm getting the following message:

message Call to a member function messages() on null
exception   Symfony\Component\Debug\Exception\FatalThrowableError
file    C:\xampp\htdocs\dogmedia.com\app\Traits\SendMail.php
line    24

MailgunServiceProvider

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Mailgun\HttpClientConfigurator;
use Mailgun\Mailgun;



class MailgunServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Mailgun::class, function()
        {
            return Mailgun::create(config('mail.mailgun.secret'), 'https://api.eu.mailgun.net');
        });
    }
}

And my trait:

<?php
namespace App\Traits;

use Mailgun\Mailgun;


trait SendMail
{
    
    protected $mailgun;

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


    public function sendMail($view, $mailData, $subject, $to)
    {
        //dd($this->mailgun); this returns null

        $html = view($view, compact('mailData'))->render();

        $result = $this->mailgun->messages()->send(config('mail.mailgun.domain'), [
            'from' => config('mail.from.name').' <'.config('mail.from.address').'>',
            'to' => $to,
            'subject' => $subject,
            'html' => $html,
        ]);
        
        return $result;
    }

    
}
Oct
13
4 weeks ago
Activity icon

Started a new Conversation Passing Laravel Variables To Vue Frontend

Hi everybody, in order to pass php variables from laravel to vue frontend I created a Javascript class, I use this class static put method to send an associative array to frontend.

<?php
namespace App\Helpers;


class Javascript
{
    
    public static function put($array, $request)
    {
        //I call this static method to pass backend variables to Vue, from blade I json_encode the payload, assign it to a window variable
        //and later add it to the Vue.prototype so I can access in vue components like this.$app.whatever.

        //This helper method can be called more than one time in laravel's request->reponse cycle, from middleware, controller action, route redirect ... 
        //so instead of creating recreating $app array everytime I want to find a way to push passed key value pairs to a global javascript object
        
        $app = array();

        $app = array_merge($request->globals, $array);

        view()->share('app', $app);
    }
  
}

When I want to return a laravel blade view wth javascript data I do it like this:

$featuredPosts = Post::where('isFeatured', true)->where('isVisible',true)->with('postcategory')->get();
        
        Javascript::put([
            'meta' => $meta,
            'featuredPosts' => $featuredPosts,
        ], $request);
        
        return view('publicaciones.list', compact('meta'));

And in my blade master layout:

<script type="text/javascript">window.$app = {!! json_encode( $app ) !!};</script>

Another case is when I want to have global variables for all routes/views, for this purpose I have a global middleware called GlobalsVar where I do.

public function handle($request, Closure $next)
    {
$globals['auth'] = Auth::user() ? User::with('appointment')->find(Auth::id()) : false;

        $globals['previousUrl'] = URL::previous();

        $request->globals = $globals;
        
        return $next($request);

Currently inside my Javascript class I create an empy array and merge part of my requests with the passed array from my controllers, I also pass request object as seconda parameter, I want to improve this in two ways:

  1. Each time I call Javascript::put static method the passed values are merged into the exisiting object, this is because if during the request -> response cycle I call Javascript::put the payload is recreated and previous data is lost, is there a way to preserve this data?

  2. I don't want to pass Request $request object each time I run Javascript::put, is there a way to always inject the Request method

Activity icon

Replied to Convert FormData To Javascript Object In Vue?

Yes I know how to send FormData to server using axios with multipart/form-data, what I wanna do is send as js object instead, first I append data to FormData object(like uploading an image and some inputs) and then I want to covert it to javascript object literal, is it possible?

Activity icon

Started a new Conversation Convert FormData To Javascript Object In Vue?

Hi everybody, FormData is a way to send files to a server, in my Vue app I want to send to laravel backend FormData object but like a javascript object literal instead, this way it's easier form me to manipulate.

I create FormDta like this:

let data = new FormData();
            
for (const [key, value] of Object.entries(this.formData))
{ 
      data.append(key, value );
}

And I want to send something to backend which looks like this:

let convertedFormData = { file: 'ÿÄbdnj jfdjdir,yrýjrvj' , title : 'Hi, this is an object from FormData'  } ;

Something that looks like that, is it possible to send files via ajax like javascript object? also is there a difference between JSON and javascript object? they look the same to me...

Oct
10
1 month ago
Activity icon

Started a new Conversation Vue V-visible Directive Help

Hi everybody, I want to create a custom directive similar to v-show and v-if but it sets the visibility of the element to hidden instead, how can I evaluate id the expression passed to the directive is true or false, the expression passed can be a prop or data variable.

This is what I have so far, which is not much anyway.

Vue.directive('visible', {
    isLiteral: true,
    inserted: (el, binding, vnode) => {

        //How can I check if passed condition is true
        let condition;

        el.style.visibility = condition ? 'visible' : 'hidden';
    }
});
Oct
08
1 month ago
Activity icon

Started a new Conversation Help With Vue Transition

Hi everybody, I made a custom image slider with vue, I got it working alright but I can't get the desired transition effect using vue's enter/leave transitions, the effect I want is so the current slider stays in place and the entering slider slides into position over the old one, right now I got it only half working, the next slider snaps right into position instead, you can see it here the seconda time slider changes...

https://i.imgur.com/BfA647F.gif

This is the transition I'm using:

.slide-ftop-tbottom-enter { transform:translateY(-400px); }
.slide-ftop-tbottom-enter-active { transition: all 2s ease; }
.slide-ftop-tbottom-enter-to { transform:translateY(0px); }
.slide-ftop-tbottom-leave { opacity:1; }
.slide-ftop-tbottom-leave-active { transition: all 2s ease; }
.slide-ftop-tbottom-leave-to { opacity:1; }

And my slider component:

<template>
    <div class="SLIDERcontainer13_item_container">
        <transition-group name="slide-ftop-tbottom">
        <div class="SLIDERcontainer13_item_image" v-for="(item,index) in slideritems" :key="index+'I'" v-show="activeslider == index" :style="'background-color:'+item+';'"></div>
        </transition-group>
    </div>
</template>
<!--SCRIPTS-->
<script>
export default {
name: 'SLIDERcontainer13',


props:
{
    sliderinterval: { default: 7000, type: Number },
},


data() {
    return {
        sliderTimer: 0,
        slideritems:['red','blue','green','yellow'],
        activeslider:0,
    }
},


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


methods:{

    
    starTimer() {
        this.sliderTimer = setTimeout(() => {
            this.nextSlider();
        }, this.sliderinterval);
    },

    stopTimer() {
        clearTimeout(this.sliderTimer);
    },

    resetTimer() {
        clearTimeout(this.sliderTimer);
        this.starTimer();
    },

    goToSlider(sliderIndex) {
        this.resetTimer();
        this.activeslider = sliderIndex;
        console.log('changed active slider');
    },

    prevSlider() {
        if (this.activeslider === 0) return this.goToSlider(this.slideritems.length - 1);

        this.goToSlider(this.activeslider - 1);
    },

    nextSlider() {
        if (this.activeslider === this.slideritems.length - 1) return this.goToSlider(0);

        this.goToSlider(this.activeslider + 1)
    },

}


};
</script>
<!--STYLES-->
<style scoped>
.SLIDERcontainer13_item_container{width:350px%; height:350px; position:relative; overflow:hidden;}
.SLIDERcontainer13_item_image{width:100%; height:100%; position:absolute; top:0px; left:0px;}
@media only screen and (max-width: 736px) 
{
}
</style>

Sep
30
1 month ago
Activity icon

Started a new Conversation Where To Place Vuex Subscribe Function ?

Hi everybody, I use vuex in my laravel/vue app and have a subscribe function for all actions, I have placed that login in my app.js file, in the created hook of my Vue instance however this doesn't lok like a good place, what'd be a good place for it?

My function:

created()
{
    console.info('******* VUE INSTANCE CREATED *******');
    console.info(this.$app);
    
    this.$store.subscribeAction(
    {
        before: (action, state) => 
        {
            console.log('Action dispatched: '+action.type);
            if(action.payload && action.payload instanceof FormData)
            {
                let id = action.payload.get('loaderId');
                this.$store.commit('Loader/SET_LOADER_ID',id);
                console.log('id set to: '+id);
            }
            else if(action.payload)
            {
                let id = action.payload.loaderId;
                this.$store.commit('Loader/SET_LOADER_ID',id);
                console.log('id set to: '+id);
            }
        }
    });

    
},

And my vuex index file loks like this:

/*
|-------------------------------------------------------------------------------
| 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';

//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 Nav from './modules/Nav.js';

const persistedPaths = [
    'Modals.seenCustomModalIds', 'Modals.cookiesAccepted','Modals.cookieModalVisible', 'Modals.contactClickTime',
    'Cart.showCartTab', 'Cart.showCartAlert', 'Cart.cartItems',
    'Discounts.showCodeCheckout'
];

//Exports our data store.
export default new Vuex.Store({
    strict: false, //debug
    
    modules: { 
        Auth,
        Loader,
        AdminPanel,
        
    },


    plugins: [
        createPersistedState({ paths: persistedPaths })
    ]

    
});
Activity icon

Started a new Conversation Adding V-model To Non-input Custom Component In Vue?

Hi everybody, I created a custom calendar component and I was wondering how I can send value upwards, I thought about using v-model but all the posts I saw about it use input elements and my component uses divs. I know I could technically use vuex for this but that doesn't speak reusability to me ...

I want to have something like :

<v-calendar v-model="interval" ></v-calendar>

In my calendar component the user clicks on days and these days are added to data property interval:


data(){
    return {
        interval:[]
    }
},

methods:
{
clickedDay(weekDay, calendar)
    {
        let index = calendar.index;
        let add = Vue.moment(weekDay.fullDate, 'M-D-YYYY');

        if(index == 0)
        {
           add.isAfterOrSame(Vue.moment(this.interval[0], 'M-D-YYYY'));
           this.$set(this.interval, 0, weekDay.fullDate);
        }
        else
        {
            add.isAfter(Vue.moment(this.interval[0], 'M-D-YYYY'));
            this.$set(this.interval, 1, weekDay.fullDate);
        }
    },
}
Sep
27
1 month ago
Activity icon

Started a new Conversation Applying Css Properties To Multiple Children On Hover

Hi everybody, I want to apply different properties to a element on hover, all elements are children of the class I apply hover but it's not working for some reason...

My button element:

<button class="LAYOUTbutton_container fs_huge c_light" type="button">
            ASESORIA
            <div class="LAYOUTbutton_line_top"></div>
            <div class="LAYOUTbutton_line_bottom"></div>
            <div class="LAYOUTbutton_line_left"></div>
            <div class="LAYOUTbutton_line_right"></div>
        </button>

My classes

.LAYOUTbutton_container{font-family:'Oswald'; margin:0px 20px; background-color:rgba(0,0,0,0.3); padding:20px; position:relative; text-transform:uppercase; display:flex; align-items:center; justify-content:center;}
.LAYOUTbutton_line_top{width:0px; height:4px; position:absolute; top:0px; left:0px; transition:all 1s ease; background-color:white;}
.LAYOUTbutton_line_bottom{width:0px; height:4px; position:absolute; bottom:0px; left:0px; transition:all 1s ease; background-color:white;}
.LAYOUTbutton_line_left{width:4px; height:0px; position:absolute; top:0px; left:0px; transition:all 1s ease; background-color:white;}
.LAYOUTbutton_line_right{width:4px; height:0px; position:absolute; top:0px; right:0px; transition:all 1s ease; background-color:white;}
.LAYOUTbutton_container:hover .LAYOUTbutton_line_top .LAYOUTbutton_line_bottom{width:100% !important;}
.LAYOUTbutton_container:hover .LAYOUTbutton_line_left .LAYOUTbutton_line_right{height:100% !important;}
Activity icon

Started a new Conversation Array To String Conversion Error When Running Laravel Seeders

I'm getting the error below when running seeders for my appointments table:

  ErrorException  : Array to string conversion

  at C:\xampp\htdocs\daisyspet\vendor\laravel\framework\src\Illuminate\Support\Str.php:353
    349|
    350|         $result = array_shift($segments);
    351|
    352|         foreach ($segments as $segment) {
  > 353|             $result .= (array_shift($replace) ?? $search).$segment;
    354|         }
    355|
    356|         return $result;
    357|     }

  Exception trace:

  1   Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Array to string conversion", "C:\xampp\htdocs\daisyspet\vendor\laravel\framework\src\Illuminate\Support\Str.php")
      C:\xampp\htdocs\daisyspet\vendor\laravel\framework\src\Illuminate\Support\Str.php:353

  2   Illuminate\Support\Str::replaceArray("?", "insert into `appointments` (`petservice_id`, `user_id`, `fullName`, `petInfo`, `petNumber`, `comments`, `days`, `interval`, `phone`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)")
      C:\xampp\htdocs\daisyspet\vendor\laravel\framework\src\Illuminate\Database\QueryException.php:56

  Please use the argument -v to see more details.

Appointments seede file looks like this:

<?php


use Illuminate\Database\Seeder;


class AppointmentsSeeder extends Seeder
{
   

    public function run()
    {
        
        DB::table('appointments')->insert([
            'petservice_id' => 3,
            'user_id' => 2,
            'fullName' => 'John Doe',
            'petInfo' => 'My dog is very good',
            'petNumber' => 1,
            'comments' => 'I have no special requests',
            'days' => [ 'jueves', 'viernes' ],
            'interval' => ['5-10-2019', '15-11-2019'],
            'phone' => 6566332122
        ]);
    }
}

And migration:

<?php

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

class CreateAppointmentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('appointments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->index();
            $table->foreign('user_id')->references('id')->on('users');
            $table->unsignedInteger('petservice_id')->index();
            $table->foreign('petservice_id')->references('id')->on('petservices');
            $table->string('fullName');
            $table->string('phone');
            $table->longText('petInfo');
            $table->integer('petNumber');
            $table->text('interval');
            $table->text('days');
            $table->longText('comments')->nullable();
            $table->timestamps();
        });
    }

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

And just in case my model, notice how I use casts property to transform jso into array, maybe that's why I'm getting this error:

<?php
namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class Appointment extends Model
{
    
    
    protected $table = 'appointments';
    protected $casts = [ 'days' => 'array', 'interval' => 'array'];

    public function petservice()
    {
        //antes tenia hasOne
        return $this->belongsTo('App\Models\PetService', 'petservice_id');
    }

    public function user()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }
    
    
}
Sep
24
1 month ago
Activity icon

Started a new Conversation Add Property - Value Pair To Javascript Object Inline

Hi everybody, I want to add property - value pair "loaderId : 7777" to a vuex action payload, in this case in my template, I know I would create a method for where I create the payload object and add property like this:

setAppointmentObj(){
    let appointment = { id:1, by: 'Gabriel', loaderId:7777 };
    this.create(appointment);
}

but I'd like to know if it's possible to do like this:

<button @click="create(appointment[loaderId] = 7777)" type="button">Make</button>

Instead of the appointment object this is what is being sent to backend

7777:   
Sep
14
1 month ago
Activity icon

Started a new Conversation Review Model Relationship With Multiple Tables?

Hi everybody, My app has many models, particularly any logged in user can give feedback and create a review, they can create a plain Review, a DiscountReview and PostReview, this three models are my review models. One DiscountReview belongs to a Discount, one Discount can have many DiscountReviews ... so after some time I just noticed that since a review will always have the same attributes (title, body, rating ... ) maybe I should write a single Review Model and attach it to other Models, a Post, a Discount and other Models can have a Review associated to them or not.

So my question is how can I set up a relationship like this with laravel?

Aug
19
2 months ago
Activity icon

Started a new Conversation Laravel For Backend/API For Nativescript-vue App?

Hi everybody, I have been reading a lot about nativescript-vue recently for developing native apps on mobile while using vue's single file components and familiar syntax and structure, however I haven't find anything about connecting my laravel backend to my nativescript-vue application? Basically I want to manage auth and API endpoints with laravel and have vuex modules to manage application state and UI in mobile, are there any examples on how to connect a nativescript-vue app to consume laravel backend services?

Aug
09
3 months ago
Activity icon

Started a new Conversation Access Vuex State Dynamically With Bracket Notation In Template

Hi everybody, I have an v-for in my template and a piece of state which I want to dynamically access using bracket notation (this works for actions so it should work for state afaik) but nothing is getting rendered, this is my template:

<template v-if="field.element == 'select'">
    <select class="modal_input_select" v-model="formData[field.id]">
        <option v-for="result in $store.state[field.module][field.results]" :key="result.id" 
           :value="result.id">{{ result.title }}</option>
        </select>
</template> 

And this is my schema I use to build my modal:

createSchema:
    {
        title: 'Nueva publicación', description:'',
        formData: { image: '', title: '', body:'' },
        fields: 
        [
            { id: 'image', label: 'Imagen', element: 'image', type: 'image' },
            { id: 'title', label: 'Titulo', element: 'input', type: 'text' },
            { id: 'body', label: 'Contenido', element: 'editor', type: 'html' },
            { id: 'postcategory', label: 'Categoría', element: 'select', type: 'select', module: 'PostCategories', results: 'postCategories'},
        ],
        buttons:
        [
            { text: 'Guardar', background: 'var(--blue_boot)', validate: true, module: 'Posts', action: 'create' },
            { text: 'Volver', background: 'var(--grey_boot)', validate: false, module: 'AdminPanel', action: 'hideModal' },
        ],
        mounted:
        [
            { module: 'PostCategories', action: 'all' },
        ]
    },
Jul
06
4 months ago
Activity icon

Started a new Conversation Javascript Array.slice Not Working As Intended

Hi everybody, I have four image sliders and an array of images, I'm using four computed properties to have four arrays and pass these as props to my image sliders, however only the first slider is displaying correctly, other three sliders aren't showing images at all, what am I doing wrong?

After checking vue dev tools second,third and fourth array are empty...

<template>
<section class="SLIDERcontainer9_maincontainer shadow">
    <div style="width:50%; height:50%;  display:flex; border:1px solid var(--web_secondary_color);">
        <slider-container-13 :sliderinterval="5000" :slideritems="firstItems"></slider-container-13>
    </div>
    <div style="width:50%; height:50%;  display:flex; border:1px solid var(--web_secondary_color);">
        <slider-container-13 :sliderinterval="6000" :slideritems="secondItems"></slider-container-13>
    </div>
    <div style="width:50%; height:50%;  display:flex; border:1px solid var(--web_secondary_color);">
        <slider-container-13 :sliderinterval="7000" :slideritems="thirdItems"></slider-container-13>
    </div>
    <div style="width:50%; height:50%;  display:flex; border:1px solid var(--web_secondary_color);">
        <slider-container-13 :sliderinterval="8000" :slideritems="fourthItems"></slider-container-13>
    </div>
    <div class="SLIDERcontainer9_texts_container"></div>
    <img src="/img/misc/soho-logo.jpg" style="width:200px; height:auto; position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);">
    <transition name="slide-fright-tleft"> 
        <a class="SLIDERcontainer9_phone_container" :href="'tel:+34'+globals.generals.appPhone" v-if="showBio">
            <div class="SLIDERcontainer9_phone_texts_container">
                <i class="SLIDERcontainer9_phone_texts_icon fa fa-phone c_light fs_big"></i>
                <span class="SLIDERcontainer9_phone_texts_title fs_big c_light">Reservar</span>
            </div>
        </a>
    </transition> 
</section>
</template>
<!--SCRIPTS-->
<script>
import { mapState } from 'vuex';
export default {
name: 'SLIDERcontainer9',


computed:
{
    ...mapState('Globals', ['globals']),
    firstItems: function(){ let firstItems = this.slideritems.slice(0,4); return firstItems},
    secondItems: function(){ let secondItems = this.slideritems.slice(4,4); return secondItems},
    thirdItems: function(){ let thirdItems = this.slideritems.slice(8,4); return thirdItems},
    fourthItems: function(){ let fourthItems = this.slideritems.slice(12,4); return fourthItems},
},


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


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


};
</script>

Jul
01
4 months ago
Activity icon

Started a new Conversation Vue: Commit Mutation From Inside Custom Directive

Hi evwrybody, I want to commit a mutation to the store from inside a custom vue directive I made, is it possible to access it inside the directive context? how about changing data state in a component from a directive?

Here is my code:

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

        let scrolled = false;
        let stickyTop = null;

        window.addEventListener('load', function() {
            stickyTop = el.offsetTop;
            checkPosition();
            window.addEventListener('scroll', function() {
                scrolled = true;
            });
        });

        let checkPosition = function(){
            if (window.pageYOffset > stickyTop && window.innerWidth > 765) {
                el.classList.add(binding.value);
                //COMMIT VUEX MUTATION HERE
            }
            else {
                el.classList.remove(binding.value)
                //COMMIT VUEX MUTATION HERE
            }   
        };

        let timeout = setInterval(function() {
            if (scrolled) {
                scrolled = false;
                checkPosition();
            }
        }, 2000);

    }
});
Jun
30
4 months ago
Activity icon

Started a new Conversation Meaning Of $name => $value When Iterating Arrays

Hi everybody, when looping through arrays I usually see something like this:

foreach ($this->filters() as $name => $value)

I have never used that syntax, I usually go with something like this:

foreach ($this->filters() as $filter) 

What are the differences?

Jun
28
4 months ago
Activity icon

Started a new Conversation Javascript: Adding A Single Function To Multiple Events

Hi everybody, currently I have something like this:

window.addEventListener('load', function() {
        self.checkIsMobile();
    });

    window.addEventListener('resize', function() {
        self.checkIsMobile();
    }); 

Is it possible to do the same action for multiple events in a single line, something like:

window.addEventListener(['load', 'resize'], function() {
        self.checkIsMobile();
});

Thnaks in advance

Activity icon

Replied to Make Url Not Appear On Google

@SNAPEY - How can I hide /gestor-contenido-info url from crawlers using robots.txt

My current robots.txt looks like this:

User-agent: *
Disallow:
Activity icon

Started a new Conversation Make Url Not Appear On Google

Hi everybody, my web has a page (url) which I don't want to appear in google indexes when someone searches my web, I don't want google to index it so only users who I told about the url will know it's actually there, I DO NOT plan to use auth middleware for this, any suggestions on how to achieve this?

Jun
25
4 months ago
Activity icon

Started a new Conversation Vue: Rendering Images/components With V-for

Hi everybody, I have an app section where various images are showcased, I get this images from an array and I lop through them with v-for to rener them in my component, now inside of that array I added a 'component' property instead of image, I want to render a compnent by name instead of image when specified in my array.

This is my array (backend), I do a json_encode to get it into my frontend (vue).

$globals['bioItems'] = [
            [ 'image' => '/img/misc/pelo-1.jpg', 'component' => false, 'title' => '' ],
            [ 'image' => false, 'component' => 'layout-image-1', 'title' => '' ],
            [ 'image' => '/img/misc/pelo-3.jpg', 'component' => false, 'title' => '' ],
            [ 'image' => '/img/misc/pelo-4.jpg', 'component' => false, 'title' => '' ],
            [ 'image' => '/img/misc/pelo-5.jpg', 'component' => false, 'title' => '' ],
            [ 'image' => '/img/misc/pelo-6.jpg', 'component' => false, 'title' => '' ],   
        ];

And in my component this is how I render the list of images:

<div class="LAYOUThub1_center_row_item_container" v-if="showImages">
            <div class="LAYOUThub1_center_item33_container" v-for="(item,index) in globals.bioItems" :key="index+'F'">
                <transition :name="transitionByIndex(index)" appear>
                <div class="LAYOUThub1_center_item33_image" :style="'background-image:url('+item.image+');'"></div>
                </transition>
            </div>
        </div>

How can I do this?

Jun
21
4 months ago
Activity icon

Started a new Conversation Error When Running Envoy Task, Server [ Server_name] Is Not Defined

Hi everybody, I'm trying to use laravel envoy task runner to deploy an app with just a command, however when I execute envoy run deploy I het the following error message in terminal.


[email protected]:/var/www/dtcburger.es$ envoy run deploy

In TaskContainer.php line 193:

  Server [web] is not defined.


run [--continue] [--pretend] [--path PATH] [--conf CONF] [--] <task>

[email protected]:/var/www/dtcburger.es$

It can't find my server despite me adding the correct user and IP to @servers array...

This is part of my Envoy.blade.php file:

@servers(['web' => '[email protected]'])

@setup
    $on = 'web';
    $user = 'deployuser';
    $domain = 'gabrielgbtest.com';
    $repo = '[email protected]:GabotronES/projectname.git';
@endsetup


@story('deploy')
    clone
    dependencies
    migrations
    perms
    nginx
    ssl
@endstory


@task('pull', ['on' => $on, 'confirm' => true])
    git fetch origin master
    git reset --hard origin/master
@endtask

Any idea what I'm doing wrong?