Gabotronix

Gabotronix

Member Since 1 Year Ago

Experience Points
24,430
Total
Experience

570 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
24,430 XP
Jan
17
1 week ago
Activity icon

Started a new Conversation Can't Find Axios Module ? Module Build Failed: Error: ENOENT: No Such File Or Directory

I'm getting the following error in my laravel-vue app:

Error: Module build failed: Error: ENOENT: no such file or directory, open 'C:\xampp\htdocs\candemtown.es\node_modules\axios\index.js

Pretty weird considering I can see the file is there, I tried deleting node_modules and package-lock.json and doing a npm install again but I keep getting the error.

My package.json file:

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "@babel/plugin-syntax-dynamic-import": "^7.2.0",
        "babel-eslint": "^8.2.6",
        "babel-plugin-dynamic-import-webpack": "^1.1.0",
        "babel-preset-env": "^1.7.0",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1",
        "laravel-mix": "^4.0.15",
        "popper.js": "^1.12",
        "resolve-url-loader": "^2.3.2",
        "sass": "^1.17.2",
        "sass-loader": "^7.1.0"
    },
    "dependencies": {
        "axios": "^0.18.1",
        "chart.js": "^2.8.0",
        "jquery": "^3.4.1",
        "lodash": "^4.17.15",
        "vue": "^2.6.8",
        "vue-moment": "^4.1.0",
        "vue-parallaxy": "^1.1.1",
        "vue-slick": "^1.1.15",
        "vue-template-compiler": "^2.6.8",
        "vue2-datepicker": "^2.6.4",
        "vue2-editor": "^2.6.6",
        "vuex": "^3.1.0",
        "vuex-persistedstate": "^2.5.4"
    }
}

Activity icon

Replied to Can't Restart/reload Nginx In My Ubuntu Droplet

None of this worked, see OP again for more details.

Jan
16
1 week ago
Activity icon

Started a new Conversation Can't Restart/reload Nginx In My Ubuntu Droplet

I have a DigitalOcean droplet, after launching a laravel app into production I tried the following command:

sudo systemctl reload nginx

But I get this error:

Job for nginx.service failed because the control process exited with error code.
See "systemctl status nginx.service" and "journalctl -xe" for details.

I ran sudo nginx -t to see if there were errors but conf and syntax is ok, after that I ran:

sudo nano /var/log/nginx/error.log

and I got this:

2020/01/16 14:53:53 [notice] 14195#14195: signal process started
2020/01/16 14:53:53 [error] 14195#14195: invalid PID number "" in "/run/nginx.pid"
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:443 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:80 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:443 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:80 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:443 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:80 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:443 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:80 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:443 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: bind() to 0.0.0.0:80 failed (98: Address already in use)
2020/01/16 14:53:53 [emerg] 14198#14198: still could not bind()

Any idea why I can't restart my web server, my webs are still visible but I can't seem to restart or reload nginx.

Jan
03
3 weeks ago
Activity icon

Started a new Conversation Error With Artisan Command To Create Database

Hi everybody, I created an artisan command to make life easier, this commadn creates a mysql database from the command prompt, it looks like this:

<?php
namespace App\Console\Commands;


use Illuminate\Console\Command;
use DB;


class CreateDatabase extends Command
{
    protected $description = 'This command creates a new database';
    protected $signature = 'db:create';


    public function handle()
    {
        $database = config("database.connections.mysql.database");
        $charset = config("database.connections.mysql.charset");
        $collation = config("database.connections.mysql.collation");

        $query = "CREATE DATABASE IF NOT EXISTS $database CHARACTER SET $charset COLLATE $collation;";

        DB::statement($query);
    }

}

I tried to keep it simple, when I run this command I get this error:

C:\xampp\htdocs\herboristeriajara>php artisan db:create

   Illuminate\Database\QueryException  : SQLSTATE[HY000] [1049] Unknown database 'herboristeriajara' (SQL: CREATE DATABASE IF NOT EXISTS herboristeriajara CHARACTER SET  COLLATE ;)

  at C:\xampp\htdocs\herboristeriajara\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[HY000] [1049] Unknown database 'herboristeriajara'")
      C:\xampp\htdocs\herboristeriajara\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70

  2   PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=herboristeriajara", "GabotronES", "Perolaperra2206624012017<38", [])
      C:\xampp\htdocs\herboristeriajara\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70

  Please use the argument -v to see more details.
Activity icon

Replied to Access Model Variable From Outside Model

Sorry guys, I missed the $ haha

Dec
23
1 month ago
Activity icon

Started a new Conversation Access Model Variable From Outside Model

Hi everybody, I want to access a variable I created in my Prize Eloquent model in laravel, I want to access it like this in my Middleware/Controller:

Prize::activePrize;

I defined $activePrize in my Model:

<?php
namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class Prize extends Model
{


    protected $table = 'prizes';
    public static $activePrize = 'Una copa a tu gusto';


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

I'm trying to do $prize = Prize::activePrize; but I'm getting the following error:

Undefined class constant 'activePrize'
Dec
22
1 month ago
Activity icon

Started a new Conversation Pass Html Element String To Vue Directive, Issue With Eslint

Hi everybdy, I created two custom vue directives to insert an html element after or before another element, I pass an html element string to the element I apply the directive but VS Code is giving me the following error:

Parsing error: unexpected-character-in-attribute-name.eslint-plugin-vue

This is how I'm doing it:

<rad-stack title="Precio final" v-insert-before="'<div class="RADcard3_texts_info_divider"></div>'">{{ item.finalPrice }} €</rad-stack>

My directive looks like this:

Vue.directive('insert-before', {
    isLiteral: true,
    inserted: (el, binding, vnode) => {
        el.parentNode.insertBefore(binding.value, el);
    }
});
Dec
21
1 month ago
Activity icon

Started a new Conversation Help With Dependency Injection And Static Method For My Models

Hi everybidy, I created a helper class for searching and filtering my laravel models (method uses tntsearch and a custom scope), currently it works all right but I want to make some improvements to it, sadly it's proving difficult to achieve what I want:

What I want to improve:

  1. Being able to call search method statically on all my laravel models, like this:
Model::search();

Currently I have to instantiate the class and call the method like:

 $results = $searchHelper->search($request, $filters);

2)Right now I also have to pass two arguments to constructor, in my class I try dependency injection in construct magic method but I still have to pass request and filters as arguments...

How it looks in my controller:

public function search(Request $request, QueryFilters $filters)
    {
        $search = new Search($request, $filters);

        
        $posts = $search->search('Post', ['postcategory', 'author', 'favorites']);

        return response()->json([
            'message' => 'Encontramos unas coincidencias',
            'posts' => $posts,
        ], 200);   
    }

My helper class:

<?php
namespace App\Helpers;


use Illuminate\Http\Request;
use App\Filters\QueryFilters;
use App\Filters\Filterable;


class Search
{

    public $request;
    public $filters;

    public function __construct(Request $request, QueryFilters $filters)
    {
        $this->request = $request;
        $this->filters = $filters;
    }

    public function search( $model, $relationships = [] )
    {
        $model = app("App\Models\".$model."); 
        
        $results = $model::search($this->request->input('search'), '')->get(); 

        if(!$results->isEmpty())
        {
            $ids = implode(',', $results->pluck('id')->toArray());
            $filters->merge(['whereIn' => $ids]);    
        }

        $results = $model::filter($this->filters)->with($relationships)->paginate(10);

        return $results; 
    }


}

I want to call the method like this, NO passing arguments to constructor (DI should handle that), call method STATICALLY

Appointments::search();
Activity icon

Started a new Conversation Can't Access Data Property From Parent In Slot Child Component

I have two components rad-list and rad-card, I placed a slot element in rad-list where I will place rad-card, now rad-card receices an object from computedResults array (in parent scope) and iterates through them and pass result to item prop in rad-card, but since computedResults is defined in parent component my rad-card instance doesn't have access to it?

<rad-list model="Discount" module="Discount" results="discounts">
        <rad-card :item="result" v-for="result in computedResults" :key="result.id" :model="module"></rad-card>
    </rad-list>

I get following error:

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

(found in <Root>)

My rad-list component:

<template>
<div class="RADlist_maincontainer">
    <layout-pagination-1 v-show="pagination.last_page > 1" :pagination="pagination" @paginate="paginate({ page:pagination.current_page, paginate:paginate })"></layout-pagination-1>
    <div class="RADlist_wrapper">
        <!--rad-card, or any other component which will use computedResults GOES HERE-->
        <slot></slot>
    </div>
    <layout-pagination-1 v-show="pagination.last_page > 1" :pagination="pagination" @paginate="paginate({ page:pagination.current_page, paginate:paginate })"></layout-pagination-1>
</div>
</template>
<!--SCRIPTS-->
<script>
import { mapState } from 'vuex';
export default{
name: 'RADlist',


computed:
{
    computedResults: function()
    { 
        return this.$store.state[this.module][this.results];
    },
    pagination: function()
    { 
        return this.$store.state[this.module].pagination;
    },
    ...mapState('Loader', ['loader'])
},


props:
{
    component: { default:'rad-card', type:String },
    module: { default:'Post', type:String },
    action: { default:'list', type:String },
    results: { default:'posts', type:String },
    page: { default:1, type:Number },
    paginate: { default:6, type:Number },

},


mounted()
{
    console.log(this.$options.name+' component successfully mounted');
    this.$store.dispatch(this.module+'/'+this.action, { page: this.page, paginate: this.paginate, loaderId:2473});
},


}
</script>
Dec
20
1 month ago
Activity icon

Started a new Conversation Vue: Access Parent Component Data In Slotted Child Component?

I have two components rad-list and rad-card, I placed a slot element in rad-list where I will place rad-card, now rad-card needs to access a computedResults data from parent rad-list component, how can I access it using vue slots, is it possible?

RAD LIST

<template>
<div class="RADlist_maincontainer">
    <layout-pagination-1 v-show="pagination.last_page > 1" :pagination="pagination" @paginate="paginate({ page:pagination.current_page, paginate:paginate })"></layout-pagination-1>
    <div class="RADlist_wrapper">
        <!--rad-card, or any other component which will use computedResults GOES HERE-->
        <slot></slot>
    </div>
    <layout-pagination-1 v-show="pagination.last_page > 1" :pagination="pagination" @paginate="paginate({ page:pagination.current_page, paginate:paginate })"></layout-pagination-1>
</div>
</template>

This is how it loks in my template:

<rad-list model="Discount" module="Discount" results="discounts">
        <rad-card :item="result" v-for="result in computedResults" :key="result.id" :model="module"></rad-card>
    </rad-list>

My full RADlist component justi in case it's needed:

<template>
<div class="RADlist_maincontainer">
    <layout-pagination-1 v-show="pagination.last_page > 1" :pagination="pagination" @paginate="paginate({ page:pagination.current_page, paginate:paginate })"></layout-pagination-1>
    <div class="RADlist_wrapper">
        <!--rad-card, or any other component which will use computedResults GOES HERE-->
        <slot></slot>
    </div>
    <layout-pagination-1 v-show="pagination.last_page > 1" :pagination="pagination" @paginate="paginate({ page:pagination.current_page, paginate:paginate })"></layout-pagination-1>
</div>
</template>
<!--SCRIPTS-->
<script>
import { mapState } from 'vuex';
export default{
name: 'RADlist',


computed:
{
    computedResults: function()
    { 
        return this.$store.state[this.module][this.results];
    },
    pagination: function()
    { 
        return this.$store.state[this.module].pagination;
    },
    ...mapState('Loader', ['loader'])
},


props:
{
    component: { default:'rad-card', type:String },
    module: { default:'Post', type:String },
    action: { default:'list', type:String },
    results: { default:'posts', type:String },
    page: { default:1, type:Number },
    paginate: { default:6, type:Number },

},


mounted()
{
    console.log(this.$options.name+' component successfully mounted');
    this.$store.dispatch(this.module+'/'+this.action, { page: this.page, paginate: this.paginate, loaderId:2473});
},


}
</script>

Dec
13
1 month ago
Dec
11
1 month ago
Activity icon

Started a new Conversation Use StripeController Action In ProductController?

Hi everybody, I created my own laravel-vue e-commerce app, people buy Product Model with Stripe PHP sdk, what I was doing till now is I created a StripeController for handling stripe operations like charge, start subscriptions, refunds (for me this made sense), but I noticed my StripeController is not the best way to do this, before finsihing a charge I performed some actions like:

1)Transform cartTotalPrice to cents. 2)Check if cart items were all on stock with Product::outOfStock($cartItems);

  1. And maybe some simple auth check

This to me started to smell of bad code practice, so I'm thinking now I should move this actions (atleast charging and subscribing) to their related Model controllers (Product in this case) adn maybe transform my StripeController into a helper calss where I can wrap my refund, charge, createCustomer and getCustomerPaymentMethods actions into a Stripe helper class I would call in my ProductController, DiscountController or any other "buyable" model right?.

Another option would be calling my StripeController actions from ProductController but that smells even worse honestly.

What do you guys think of my idea?

Dec
09
1 month ago
Activity icon

Started a new Conversation "value.toString(...).toUppercase Is Not A Function"

Hi everybody, in my vue component I have an "uppercase" filter to tranform strings into uppercase, however I'm gettinh the following error:

TypeError: "value.toString(...).toUppercase is not a function"

This is my filter:

Vue.filter('uppercase', function (value) {
    console.log(typeof value); // this returns string
    if (!value) return '';
    value = value.toString().toUppercase();
    return value;
});
Dec
06
1 month ago
Activity icon

Replied to Use Model Methods In Seeder?

Could this also work in my seeders?

$newUser = new User();
$newUser->generateSlots();
$newUser->save();

If so I begin to use this method instead since that's how my controllers look normaly (CRUD endpoints...), that way I will be able to access my model variables and methods.

Also is there a way to put model Scopes (basically traits) in the model class, like actually putting the query builder struff in the model, I 'm all for separation of concerns but I prefer having entity Model related stuff close together.

Activity icon

Started a new Conversation Use Model Methods In Seeder?

Hi everybody, I have a seeder file for creating some default users, I want to seed some relations via using a User instance method, this could be easy in a controller method ($user->generateSlots(); ) but in my seeder file I use insert instead of save method like in controller, how can I do this?

My method looks like this:

public function generateSlots()
    {
        for ($i = 0; $i < $this->slotsPerUser; $i++)
        {
            $slot = new Slot();
            $slot->user_id = $this->id;
            $slot->unicode = $this->generateRandomToken2();
            $this->slots()->save($slot);
        }
    }

My seeder looks like this:

DB::table('users')->insert([
            //'name' => config('admin.name'),
            'email' => config('admin.mail'),
            'password' => bcrypt(config('admin.password')),
            'privileges' => 3,
            'confirmationKey' => sha1(Carbon::now()),
            'confirmed' => true,
            'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
        ]);
Dec
03
1 month ago
Activity icon

Started a new Conversation Laravel Authentication In Nativescript-vue App, Anyone Has Done It?

Hi everybody, I'm fairly new to nativescript-vue dev and I'd like to set authentication for my native app, I have been thinking about using firebase auth but I'd rather go the laravel route (if it's a good choice at all).

How I think I'd handle this is to send a post request to my backend (which is a laravel app) into my custom auth controller, then in the success callback I'd change isLogged in the vuex store to true or false, since I'm suing also vuex-persistedstate to persist some data into my localStorage (actually it's Application Settings in natviescript afaik).

Is my way of doing this okk? has anyone done it?

Dec
01
1 month ago
Activity icon

Started a new Conversation Adding Script With Blade Syntax In From App.js In Vue

Hi everybody, is it possible to add a javascript inline script to my html head page using javascript, in my app which uses laravel and vue I want to add the following script from the created method in my entry app.js file.

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

As you can see there's some blade syntax in there.

Is it possible to do? I know I could add a partial to my master layout but something like what I'm trying to do is better/more maintaneable imo.

Nov
18
2 months ago
Activity icon

Started a new Conversation How Can I Get A Vertical Print Of My Webpage In PDF/Image

Hi everybody, I want to get a vertical image/PDF print of my webpage, I have tried many online tools which transform pages into PDF for free but the results are really bad, the CSS styles appear all fucked up, is there a way to get an image like this for free?

https://i.pinimg.com/originals/cd/a5/80/cda580be017f344a6b743dbacf088250.png

Nov
16
2 months ago
Activity icon

Started a new Conversation Merging Request Params With Array

Hi everybody, I'm trying to get laravel-scout tntsearch with eloquent's query builder, this has proven difficult so my current approach is to first use tntsearch to get results, pluck ids from the results adn then add a wherIn clause with the plucked ids, to do this I have an additional class QueryFilters to sort and filter in a composable way.

Issue is I'm getting the following error:

Call to undefined method App\Filters\QueryFilters::merge()

Here is my code:

public function search(Request $request, QueryFilters $filters)
    {
        //Search with tntsearch 
        $posts = Post::search($request->input('search'))->get();

        //Grab ids and prepare to merge with $filters
        $postIds = $posts->pluck('id');
        $toMerge = collect(['whereIn' => $postIds]);

        $filters->merge($toMerge);
        //Filter and sort results
        $posts = Post::filter($filters)->with(['postcategory','author','favorites'])->paginate(10);
}

How QueryFilters works is iterating throught the request object looking for methods with the same name and returning each time an instance of the query builder.

<?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)
    {
        if($term == 0)
        {
            return $this->builder->whereHas('postcategory', function ($query) use ($term){
                $query->where('id', '>', 0);
            });
        }
        
        return $this->builder->whereHas('postcategory', function ($query) use ($term){
            $query->where('id', $term);
        });
    }
    
    public function sortBy($term)
    {
        $sortArray = explode(",", $term);

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

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

        return $this->builder;
    }

    public function whereIn($postIds)
    {
        return $this->builder->whereIn('id', $postIds);
    }
  
    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();
    }

}

To know more about this class see this medium article: https://medium.com/@mykeels/writing-clean-composable-eloquent-filters-edd242c82cc8

If I dd $filters I get this:

QueryFilters {#457
  #request: Request {#43
    #json: null
    #convertedFiles: null
    #userResolver: Closure($guard = null) {#421
      class: "Illuminate\Auth\AuthServiceProvider"
      this: AuthServiceProvider {#41 …}
      use: {
        $app: Application {#2 …}
      }
      file: "C:\xampp\htdocs\dog-media.es\vendor\laravel\framework\src\Illuminate\Auth\AuthServiceProvider.php"
      line: "83 to 85"
    }
    #routeResolver: Closure() {#423
      class: "Illuminate\Routing\Router"
      this: Router {#26 …}
      use: {
        $route: Route {#220 …}
      }
      file: "C:\xampp\htdocs\dog-media.es\vendor\laravel\framework\src\Illuminate\Routing\Router.php"
      line: "650 to 652"
    }
    +attributes: ParameterBag {#45
      #parameters: []
    }
    +request: ParameterBag {#51
      #parameters: array:3 [
        "loaderId" => "1111"
        "postCategory" => "0"
        "sortBy" => "created_at+"
      ]
    }
    +query: ParameterBag {#51}
    +server: ServerBag {#47

...
Nov
15
2 months ago
Activity icon

Started a new Conversation Using V-model With Nested Components In Vue

Hi everybody, in my admin app I have an <admin-rich-editor>, inside this component I also have Vue 2's quill rich editor which uses v-model for its data, now I want to pass the v-model from my child vue-2-editor to my own parent component, the docs say you can have custom v-model in yur compoennt with props value and emiting an 'input' event with that value, but how can I pass one v-model to another, from child to parent component.

Im using vue 2 editor, A text editor using Vue.js and Quill: https://github.com/davidroyer/vue2-editor

My component <admin-editor>:

<template>
<div style="width:auto; height:auto; display:flex; flex-direction.column;">
    <button @click="editorVisible = true">Show Editor</button>
    <vue-editor v-model="value" :editorToolbar="customToolbar" useCustomImageHandler @imageAdded="handleImageAdded"></vue-editor>
</div>
</template>
<!--SCRIPTS-->
<script>
import { VueEditor } from 'vue2-editor';
export default {
name: 'ADMINeditor',


props:
{
    value:{ required:true, type:String }
},


data()
{
    return { 
        editorVisible:false
    }
},


methods:
{

    wrote()
    {
        this.$emit('input', this.value);
    }
}


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

I want to be able to do:

<admin-editor v-model="text"></admin-editor>

More info about -model in custom components.

https://alligator.io/vuejs/add-v-model-support/

Activity icon

Started a new Conversation Using Laravel-scout Tntsearch Along With Eloquent Query Builder

Hi everybody, I want the user to sort, filter AND tnt-search Model entries, in my laravel backend I have a search method API call, currently I can't get scout's Model::search method to work along with Eloquent's query builder, so you either:

  1. Search by text if request has 'search'.
  2. Sort or filter with eloquent query builder (see link bellow for more info).

How can I get both the results from tnt-search term search and eloquent query builder to return a merged result, paginated;

My search method:

public function search(Request $request, QueryFilters $filters)
    {

        if($request->has('search'))
        {
            $posts = Post::search($request->input('search'))->paginate(10);
            $posts->load(['postcategory','author','favorites']); 

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

            return response()->json([
                'message' => 'Encontramos unas coincidencias',
                'posts' => $posts,
            ], 200);
        }
        else
        {
            $posts = Post::filter($filters)->with(['postcategory','author','favorites'])->paginate(10);

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

            return response()->json([
                'message' => 'Encontramos unas coincidencias',
                'posts' => $posts,
            ], 200);
        }
        
    }

And in case you are wondering what does Model::filter do, it just iterates through the request query params and uses Eloquent to sort and filter, you can check this medium article:

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

<?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 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();
    }

}
Nov
14
2 months ago
Activity icon

Started a new Conversation Get Model By Id Plus 10 Previous And 10 After It

Hi everybody, given an id of a model I want to grab that model, the ten previous model entries and ten after the selected id, I also want to return them paginated.

So if I get id 11 I want to return ids: 1 2 3 4 5 6 7 8 9 10 <- 11 -> 12 13 14 15 16 17 18 19 20

Nov
12
2 months 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
2 months 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
2 months 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
2 months 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
2 months 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
2 months 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 months 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 months 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 months 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 months 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
3 months 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 months 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 months 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 months 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
3 months 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 ...