p0t4t0

p0t4t0

Member Since 11 Months Ago

Experience Points 12,900
Experience
Level
Lessons Completed 80
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

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

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

14 Nov
1 month ago

p0t4t0 started a new conversation How To Access Auth()->user() From That Authenticates With Jwt-auth From Different Pages Of App?

I've been at this problem for several hours now and still can't figure it out, hoping to get help on this matter.

The problem: is it possible to have access to auth()->user() across different pages outside of React which has been "set" on a page where my React instance lives and does authentication/authorization?

Currently: I have two routes: /home and /dashboard, /home is your typical Laravel app (blade views, reloads, and all that jazz), /dashboard on the other hand is a single page React app which has routes of its own courtesy of React Router, probably not the best implementation but it does the job.

Expected outcome: to be able to have access to auth()->user() in the /home page (it seems to stop working after I login from the React app on /dashboard and navigate to /home).

Any and all help is appreciated thank you.

30 Sep
2 months ago

p0t4t0 left a reply on Having A Problem Making A Request With Axios 500 (Internal Server Error)

I seem to have figured it out. I tried adding the <meta name="csrf-token" content="{{ csrf_token() }}" tag and the error seemed to have lessen, I still get it although only rarely now. I still want to know what was wrong though and if the error really was because of the missing csrf token.

p0t4t0 started a new conversation Having A Problem Making A Request With Axios 500 (Internal Server Error)

I am using Laravel together with React, jwt-auth, and axios, I've successfully implemented user login, user registration, and logout but for some reason I'm getting a 500 error whenever my application first loads and tries to get data through componentDidMount, although it works if I navigate to a different page then go back to that page again, I've been at this for 3 hours now and I still couldn't figure it out. Here is the error message I am getting Argument 3 passed to Lcobucci\JWT\Signer\Hmac::doVerify() must be an instance of Lcobucci\JWT\Signer\Key, null given

p0t4t0 left a reply on Getting The Laravel 404 Page With React Router 4

@tykus yeah this did it for me thanks!

p0t4t0 started a new conversation Getting The Laravel 404 Page With React Router 4

I am using the React preset that comes along with Laravel: php artisan preset react and I seem to be having problems with it concerning routing with React. Every time I specify a /somewhere everything works fine but when I specify one route deeper /somewhere/one-level-deep it gives the 404 page. Anyone have any idea what is wrong? I tried with create-react-app and it works fine.

10 Aug
4 months ago

p0t4t0 left a reply on Problem With Mix

still haven't figured this out :(

06 Aug
4 months ago

p0t4t0 started a new conversation Problem With Mix

Hi so I am working on an existing Laravel project and trying to integrate Vue to it. It had this code in its webpack.mix.file before:

mix.scripts([
    'node_modules/jquery/dist/jquery.js',
    'node_modules/bootstrap/dist/js/bootstrap.js',
    'node_modules/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
    'node_modules/metismenu/dist/metisMenu.js',
    'node_modules/jquery-slimscroll/jquery.slimscroll.js',
    'node_modules/pace-progress/pace.min.js',
    'node_modules/moment/min/moment-with-locales.min.js',
    'resources/assets/js/app.js',
    // 'resources/assets/js/instascan.min.js',
], 'public/js/app.js', './');

From my understanding the scripts method does not convert ES5+ code into javascript so I changed it to the babel method instead. The problem is this method doesn't seem to transpile ES5+ code either because I get this error in the console (browser) saying that it can't understand the import or require declarations I have in my resources/assets/jsapp.js file. But if I use the js method it understands the declarations just fine except the old jQuery the project had stop working. This is the code I have now:

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

And in my app.js file I have:

require('./bootstrap');
require('bootstrap-datepicker');
require('metismenu');
require('jquery-slimscroll');
require('moment');
require('./inspinia');

import Vue from 'vue';
import { store } from './store/store';
import MainComponent from './components/MainComponent.vue';

const app = new Vue({
  el: '#wrapper',
  store,
  components: {
    MainComponent
  }
});

It's weird because I'm not getting errors regarding how $ isn't defined in the console anymore but the jQuery the project had before I even touched stopped working altogether. What should I do?

PS I should also probably mention that I was getting this error when running npm run dev or npm run watch before (also, when I run npm run watch it sometimes stops "watching" my code for changes which is I am taking as something is definitely going on).

npm Error : EBUSY resource busy or locked and [BABEL] Note: The code generator has deoptimised the styling of "unknown" as it exceeds the max of "500KB".

28 Jul
4 months ago

p0t4t0 started a new conversation How To Iterate Through Associative Array In Factory Seeders?

I have the code below in my CategoriesTableSeeder

$filters = [
          'Accessories' => [
            'Type' => ['First Aid Kits', 'Tent Poles & Stakes', 'Stuff Sacks'],
          ],
          'Backpacks' => [
            'Size' => ['27L', '32L', '40L', '44L', '50L', '55L', '60L', 'More'],
          ],
          'Cooking Gear' => [
            'Type' => ['Titanium', 'Teflon (Non-Stick)'],
          ],
          'Tents' => [
            'Size' => ['1-Person', '2-Person', '3-Person', '4-Person'],
            'Type' => ['1 Season', '2 Season', '3 Season', '4 Season'],
          ],
          'Hydration bladders' => [
            'Size' => ['0.75L', '1.0L', '1.5L', '1.8L', '2.0L', '3.0L', '4L', 'More'],
          ],
          'Lighting' => [
            'Type' => ['LED', 'Rechargeable'],
          ],
          'Men\'s Clothing' => [
            'Size' => ['XXXS', 'XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'],
            'Type' => ['Shirts', 'Pants', 'Shorts', 'Jackets', 'Shoes', 'Underwear'],
            'Material' => ['Fleece', 'Gore-Tex', 'Synthetic'],
          ],
          'Sleeping Bags' => [
            'Type' => ['1 Season', '2 Season', '3 Season', '4 Season'],
          ],
          'Sleeping Pads' => [
            'Type' => ['Air', 'Foam', 'Self-Inflating'],
          ],
          'Trekking Poles' => [
            'Type' => ['Folding', 'Telescoping'],
          ],
          'Water Bottles' => [
            'Size' => ['1.0L', '1.5L', '2.0L', '3.0L'],
          ],
          'Women\'s Clothing' => [
            'Size' => ['XXXS', 'XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'],
            'Type' => ['Shirts', 'Pants', 'Shorts', 'Jackets', 'Shoes', 'Underwear'],
            'Material' => ['Fleece', 'Gore-Tex', 'Synthetic'],
          ],
        ];

        factory(App\Category::class, 12)->create()->each(function($c) use ($filters) {
          $c->filters()->saveMany( factory(App\SearchFilter::class, foreach($filters[$c->name] as $key => $item) {
            return sizeof($item);
          })->make([
            'name' => $filters[$c->name][$key][$item],
            'filter' => $filters[$c->name][$key]
          ]) );
        });

I've been staring at it for hours and I just can't seem to figure it out, how am I supposed to pass a dynamic second argument to the factory() method which should be the total number of values in each key (Size, Type and/or Material) as well as passing it to the make method to let my FilterFactory know that name should be this and the filter should be that? I just don't get it.

here is my FilterFactory.php file btw

<?php

$factory->define(App\Filter::class, function () {
    return [
        'category_id' => null,
        'name' => null,
        'filter' => null,
    ];
});
22 Jul
4 months ago

p0t4t0 started a new conversation Trailing Slashes In Query Strings A Good Idea?

so I've seen websites with urls such as site.com/products/?sort=lowestprice and ones without the trailing slash site.com/products?sort=lowestprice and was wondering what the difference between the two is and should I use one over the other? I know how to do the second one but the first one I have no clue

21 Jul
4 months ago

p0t4t0 left a reply on How Do I Secure My API Endpoints From Requests Outside Of My App?

@NickVahalik I see. I still have so much to learn on how everything flows security-wise so all this is alien still to me. Anyway, I'd like to know your thoughts on the CreateFreshApiToken middleware. From what I've understood, it seems that it takes the csrf token from <meta name="csrf-token" content="{{ csrf_token() }}"> and uses it to validate each request made to my app. Hmm but now that I think about it, couldn't someone just take the token and add it to their headers or something when sending a request to my app? Taking into account that it sits in plain view in the html? Hmm then again, I could stop that with CORS. So, would a combination of the two be sufficient for my needs?

20 Jul
4 months ago

p0t4t0 started a new conversation Do I Still Need CORS When Using The CreateFreshApiToken Middleware?

I'm really new to the whole JWT authentication thing and from what I understand so far from researching is that in order for me to be able to secure my API from external requests (requests made from other servers/domains), I would have to make use of CORS (this package specifically https://github.com/barryvdh/laravel-cors) and set 'allowedOrigins' => ['*'] to ['mydomain'] in order to tell it to only accept requests coming from my web app. But since reading the laravel docs on the CreateFreshApiToken middleware over and over again, I have realized that I may not need CORS after all since this middleware, as stated in the docs, passes the csrf token I have in a meta tag with each request which my app uses to validate them. If anyone could shed some light on me whether or not I understand these concepts correctly, I would really appreciate it. Thanks in advanced.

PS what I am basically trying to do is just disallowing all incoming requests IF they are not made specifically from my app.

p0t4t0 left a reply on How Do I Secure My API Endpoints From Requests Outside Of My App?

@NickVahalik I've been posting on several platforms the same question and someone in one of them advised me to use CORS. Wouldn't that be an option?

18 Jul
4 months ago

p0t4t0 started a new conversation How Do I Secure My API Endpoints From Requests Outside Of My App?

I built an API with Laravel and tried the auth:api middleware that comes with Passport but it doesn't seem to be what I need. What I basically want is for my endpoints to be accessible ONLY if the request was made from MY app (users don't have to be logged in to be able to get a response). Is it possible?

17 Jul
5 months ago

p0t4t0 started a new conversation Need Advice With My Vue + Passport Login System

so I tried creating a login system with Vue + Laravel Passport without making use of the /oauth/token route and having to send the client_id and client_secret along with my ajax request, although it works I kind of have the feeling that I am overdoing it, here is my flow

  1. User hits submit on login form, form sends an ajax post request to a LoginController
  2. LoginController validates data, creates a token if data is valid, sends token back to Vue
  3. Vue stores token in localStorage, sets window.axios.defaults.headers.common.Authorization to 'Bearer ' + the token that was sent from the LoginController
  4. Send a post request to '/api/user' to get user details

so any thoughts on how I can improve it? P.S. this is a first party login and I am just trying to make my api endpoints inaccessible to anyone outside of my user base

13 Jul
5 months ago

p0t4t0 left a reply on Is It Safe To Define Passport Client_id And Client_secret In .env File?

another way i'm thinking about doing it just send the username and password with axios to a controller like so

axios.post('/register', {
  username: this.email,
  password: this.password
});
Route::post('/register', '[email protected]');

and use guzzle to post to /oauth/token

public function create(Request $request)
{
  // some validation...

  $username = $request->username;
  $password = Hash::make($request->password);

  $client_id = env('PASSPORT_CLIENT_ID');
  $client_secret = env('PASSPORT_CLIENT_SECRET');

  // use guzzle to post to /oauth/token
}

haven't tested this out yet, also i just learned about guzzle so i'm not entirely sure if this is the correct usage

p0t4t0 started a new conversation Is It Safe To Define Passport Client_id And Client_secret In .env File?

Is it safe to post to /oauth/token via axios with this method?

vue file

axios.post('/oauth/token', {
grant_type: 'password'
client_id: process.env.MIX_PASSPORT_CLIENT_ID,
client_secret: process.env.MIX_PASSPORT_CLIENT_SECRET,
username: this.email,
password: this.password
});

.env file

MIX_PASSPORT_CLIENT_ID="whatever"
MIX_PASSPORT_CLIENT_SECRET="whatever"
11 Jul
5 months ago

p0t4t0 left a reply on When Building A Hybrid MPA With Laravel + Vue, Is It Better To Use Laravel's Default Authentication System Or Should I Go For Passport?

So with the CreateFreshApiToken middleware I really don't have to do anything... hmm... does that mean when a user either logs in to my site or registers, my app generates a token for them automatically? Does it also handle passing said token to each request a user makes? That's really convenient. Also, if that is the case then what are the routes generated by Passport for? Are they only for when my app starts getting requests from 3rd parties?

p0t4t0 left a reply on When Building A Hybrid MPA With Laravel + Vue, Is It Better To Use Laravel's Default Authentication System Or Should I Go For Passport?

@burlresearch Ok I think I get it a bit now but I still have some more questions if you don't mind. I tested out what you said and now it looks like I don't have to manually add the auth:api middleware to every route in my api routes, thanks! But I still have one problem though. I'm having trouble understanding the difference between personal access tokens and password grant tokens. I've read the docs and with password grant tokens it seems that it's what I need to get my login system with passport up and running, correct me if I'm wrong but I think what I need to do with it is

  1. When a user logs in with his/her credentials I send a post request to /oauth/token
  2. I get back an access_token and a refresh_token
  3. Said access_token is used to authenticate user's api requests? (not sure)
  4. Not sure what the refresh_token is for but I do understand that a token has an expiry
  5. When a token expires, I'm guessing the user won't be able to make requests to my api anymore so would there be a convenient to way to know when that token expires?
  6. Use refresh_token to refresh user's token?
  7. How is user supposed to be able to post to /oauth/token auth:php? Is it not defined in api.php?

With all that said, I just don't get what personal access tokens are for.

10 Jul
5 months ago

p0t4t0 started a new conversation When Using Passport, Is It A Choice Between Make:auth Or It Or Can/should You Use It Both Simultaneously?

When using Passport, is it a choice between make:auth or it (Passport) or can/should you use it both simultaneously?

p0t4t0 left a reply on When Building A Hybrid MPA With Laravel + Vue, Is It Better To Use Laravel's Default Authentication System Or Should I Go For Passport?

@burlresearch I just read a comment on this post https://laracasts.com/discuss/channels/laravel/passport-rest-makeauth that the csrf-token generated by fresh installs of Laravel 5.3+ takes care of making your API routes inaccessible to applications other than your own. Is this true? Also, with Passport what do you exactly mean by "skip most of that"? I just watched this tutorial on how to implement it https://www.youtube.com/watch?v=D7gUz3RcTm8&t=610s and I think I get it a little now. So what Passport basically gives you is the ability to generate "safe" tokens which you can use to authenticate your API requests against. Is that correct? And if that is the case, how am I able to use it on the default make:auth that Laravel uses? Sorry for all the questions.

09 Jul
5 months ago

p0t4t0 started a new conversation When Building A Hybrid MPA With Laravel + Vue, Is It Better To Use Laravel's Default Authentication System Or Should I Go For Passport?

When building a Hybrid MPA with Laravel + Vue, is it better to use laravel's default authentication system or should I go for Passport? I have little to no understanding of Passport at the moment, I only know that when you need your API endpoints to be accessible only by your app you should implement it (correct me I'm wrong please).

p0t4t0 started a new conversation Hybrid MPA With Vue?

I've noticed most of the websites I visit don't fully go with the "SPA" approach but instead a somewhat of a mix of a traditional website (wherein pages actually load) and single page apps, is this a good idea? If so, how would Vue "look like" on the front end? For example I have two pages Home and Products. On the home page I return a blade template but on the Products page I also return a blade template except in that template I am loading up Vue. While that works, I am faced with a slight problem. How am I able to pass the category listed in the url to the Vue instance so it knows which products to load? One way I thought of was on the products.blade.php file I added a <script>window.category = {{ Request::segment(1) }}</script> the url would look like this site.com/category-1now I have access to the category and can load the products that belong to that category with axios but I am wondering if this is advisable.

07 Jul
5 months ago

p0t4t0 left a reply on Trying To Install Vuetify To My Existing Laravel App But Its Css Files Don't Seem To Be Importing Correctly

found out I was lacking the <v-app></v-app> wrapper

<v-app>
// all your vuetify components
</v-app>

p0t4t0 started a new conversation Trying To Install Vuetify To My Existing Laravel App But Css Doesn't Seem To Be Importing

So in my /assets/js/app.js file I have...

window.Vuetify = require('vuetify');

Vue.use(Vuetify);

...which seems to be working fine and are displaying the components on my front end however in my /assets/css/app.scss file I have tried...

@import 'vuetify/dist/vuetify.min.css';

@import '~vuetify/dist/vuetify.min.css';
@import '~vuetify/dist/vuetify';

..but none seem to work, the vuetify components are showing up fine but they don't have the correct styling. What am I doing wrong?

05 Jul
5 months ago

p0t4t0 started a new conversation How Do I Run Redis On Windows?

I downloaded the files found here https://github.com/MicrosoftArchive/redis, then followed this guide https://laracasts.com/discuss/channels/general-discussion/step-by-step-guide-to-installing-socketio-and-broadcasting-events-with-laravel-51, but it doesn't seem to be working.

My server.js file

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const Redis = require('ioredis');
const redis = new Redis();

redis.subscribe('test-channel', function(err, count) {

});

redis.on('message', function(channel, message) {
  console.log('Message Received: ' + message);
  message = JSON.parse(message);
  io.emit(`${channel}:${message.event}`, message.data);
});

http.listen(3000, function() {
  console.log('Listening on Port 3000');
});

My web.php file

Route::get('/fire', function() {
  event(new App\Events\TestEvent());
  return "event fired";
});

Route::get('/', function () {
    return view('welcome');
});

My TestEvent.php file

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class TestEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $data;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->data = array(
          'power' => '10'
        );
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return ['test-channel'];
        // return new PrivateChannel('channel-name');
    }
}

And lastly my test.blade.php file

@extends('layouts.app')

@section('content')
  <div class="test">
    0
  </div>
@endsection

@section('footer')
  <script src="{{ asset('js/socket.io.js') }}" type="text/javascript"></script>
  <script type="text/javascript">
  var socket = io('http://192.168.10.10:3000');
  socket.on("test-channel:App\Events\TestEvent", function(message) {
    $('.test').text(parseInt($('.test').text()) + parseInt(message.data.power));
  });
  </script>
@endsection

I have the redis-cli.exe and redis-server.exe files running but nothing seems to be happening, I tried checking if the redis-cli and redis-server commands work on my console but they don't. I can't really figure out how to fix this. Any help is appreciated. Thank you in advance.

01 Jul
5 months ago

p0t4t0 left a reply on How Do I Use Javascript/jquery Plugins In Laravel?

I figured it out. I was editing the wrong file. Looks like all I needed to in resources/assets/js/bootstrap.js was

window.Nanobar = require('nanobar');

p0t4t0 left a reply on How Do I Use Javascript/jquery Plugins In Laravel?

@Majeed how am I supposed to import it from asset() when I haven't compiled it yet?

p0t4t0 started a new conversation How Do I Use Javascript/jquery Plugins In Laravel?

Hello, I'm not quite sure if I'm doing this right but in my /resources/assets/js/app.js file I tried importhing this plugin I just installed with npm but it isn't working

require('../../../node_modules/nanobar/nanobar');

and in my view I have

<script type="text/javascript">
      var nanobar = new Nanobar({
        classname: 'nanobar'
      });
    </script>
09 Jun
6 months ago

p0t4t0 left a reply on Is It Advisable To Hash Ids In Url?

@Sergiu17 I am aware of validation checks and middleware and wasn't the point of my post but thanks for trying, @Snapey thanks this is exactly what I was looking for

p0t4t0 started a new conversation Is It Advisable To Hash Ids In Url?

I'm not sure what the proper terms are or if it's even called hashing but is it advisable to do something like /user/gPUasb or /user/gPUasb/edit? to perhaps prevent users from guessing ids and manually going to each user's profile and maybe spam them or worse collect data from them? I'm just curious because I've never seen big sites with urls that point to user profiles with something as simple as user/1 or user/1/edit

05 Jun
6 months ago

p0t4t0 left a reply on What Things Should I Read Up On When Learning To Deploy Laravel Apps?

@amirhazz how much does it typically cost overall to launch an ecommerce website made with Laravel?

04 Jun
6 months ago

p0t4t0 started a new conversation What Things Should I Read Up On When Learning To Deploy Laravel Apps?

Hello, I just watched a video on how to set up a LEMP stack on Digital Ocean and it seems to have concepts I am still very unfamiliar with (SSH and such). Could anyone possibly give me a list of what I should be studying to learn this kind of stuff? I am unsure what I should be searching on Google because I don't just want to learn how to deploy Laravel apps but all apps built with different tech if they follow a similar process.

19 May
6 months ago

p0t4t0 left a reply on Is There A Better Way To Handle Account Verification Via Sms?

@Snapey apologies, i am new to curl and this is the sample code they have on their website (the API i am using which is iTexMo btw which i don't believe anyone here has heard of since it is only a local company), yes i validated my inputs, everything is working fine, my activation gets sent each time a new user registers. i just need to know a better approach and someone advised me i should consider using service providers which is what i am doing but can't figure out how to get working.

18 May
6 months ago

p0t4t0 started a new conversation Laravel Custom Class As Service Provider

I have a class that handles API calls to an SMS API which I made manually (without using artisan). At the moment I use it to send users their activation code after they register in my RegisterController but plan to take it a step further in the future (send sms notifications when a user posts, someone comments on their post, someone private messages them)

public function create(Request $request)
{
User::create([
    'name' => $request->name,
    'email' => $request->email,
    'mobile_number' => $request->mobile_number,
    'activation_code' => $this->generateActivationCode();
    // and so on...
]);

$mySmsClass = new MySmsClass($user->mobile_number, $user->activation_code);
$mySmsClass->sendActivationCode();
} 

I was advised against this approach to avoid tight coupling in my code and was pointed in the direction of service providers. So I read a couple of articles and found that I should be doing this instead

$this->app->bind('App\MySmsClass', function() {
    return new MySmsClass();
});

and

public function create(Request $request, MySmsClass $mySmsClass)
{
User::create([
    'name' => $request->name,
    'email' => $request->email,
    'mobile_number' => $request->mobile_number,
    'activation_code' => $this->generateActivationCode();
    // and so on...
]);

$mySmsClass->sendActivationCode();
} 

But I don't see how this is going to work since my MySmsClass depends on the recently created user's mobile number and activation code.

My questions: 1.) How am I able to access the newly created user's data from my service provider? Is there a better approach?

$this->app->bind('App\MySmsClass', function() {
    return new MySmsClass($user->mobile_number, $user->activation_code);
});

2.) Where should I store my MySmsClass? Does it matter? Right now I have it just right under my app folder.

3.) I understand I have to use this to make my MySmsClass work with my Post, Comment and Inbox controllers in the future.

$this->app->when(MySmsClass::class)
          ->needs(Post::class)
          ->give(function () {
              // do something...
          });

But I'm not able to fully understand it. How will this look like in my controller when I implement it?

p0t4t0 started a new conversation Is There A Better Way To Handle Account Verification Via Sms?

This is the code I have right now. I haven't tested it out yet but it looks like it's going to work? lol

RegisterController.php

protected function create(array $data)
    {
        $user = User::create([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'mobile_number' => $data['mobile_number'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'authentication_code' => $this->generateAuthCode()
        ]);

        $textMessage = new SmsController($user->mobile_number, $user->authentication_code);
        $textMessage->sendAuthCode();

        if ($textMessage) {
            // success
        } else {
            // error
        }

        return $user;
    }

SmsController.php

public function __construct($number, $message) {
        $this->number = $number;
        $this->message = $message;
    }

    public function sendAuthCode()
    {
        $postData = array(
            '1' => $this->number,
            '2' => $this->message,
            '3' => $this->apicode
        );

        $url = "";

        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $this->url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));

        // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYUSER, 0);

        return curl_exec($ch);
        curl_close($ch);
    }

p0t4t0 started a new conversation Is There A Way To Make The Helper Function Str_random Return Only Letters From A-z And Not Include Numbers?

Is there a way to make the helper function str_random return only letters from a-z and not include numbers?

16 May
7 months ago

p0t4t0 left a reply on What's A Better Way To Limit A User's Ability To Post Per Day

@tykus looks pretty clean. i love it! but three questions 1.) i've never seen that today() function before, where is it coming from? (the one instead the scopeToday function) 2.) in the Post model local scope, why are we getting posts with a created_at > today? 3.) if i understand the code right, the Policy restricts the user from posting if it returns false? how does it execute that exactly?

p0t4t0 started a new conversation What's A Better Way To Limit A User's Ability To Post Per Day

Right now I am thinking adding a posts_allowed column to my users table, set it to 3 maybe, then decrement it every time a user posts, when it gets to 0 i'll maybe run a check for $post->created_at > $post->created_at + 24 hrs and reset posts_allowed when it returns true.

I am not a MySQL expert but I believe this is a waste of resource especially if I set posts_allowed to integer, maybe I should set it to tinyint instead? I dunno, any suggestions? Or is there a "Laravel" way of doing this instead?

08 May
7 months ago

p0t4t0 started a new conversation Has Anyone Used The Aimeos E-commerce Package Laravel? How Is It?

Are there are better alternatives?

01 May
7 months ago

p0t4t0 left a reply on What Is Session State? And What Is The Importance Of Having A Stateless Backend?

@martinbean Thank you for clearing this up for me although I still do have a couple of questions.

  1. How does it aid in scalability? What happens with applications that store state for every consumer?
  2. How can a state affect a response?

If you aren't too busy of course, could you give me one or two examples? The simpler the better. I would really appreciate it.

p0t4t0 started a new conversation What Is Session State? And What Is The Importance Of Having A Stateless Backend?

I've read somewhere that when defining routes in api.php, you ensure that your server doesn't make use of session state and thus remains stateless. Some time ago I have had trouble differentiating the two (api.php and web.php), on why anyone would still define routes in api.php when they could easily just do so in web.php. But just what is session state? And what is the importance of having a stateless back end? What are good use cases for this? Sample scenarios? Thank you.

29 Apr
7 months ago

p0t4t0 left a reply on Does The Old() Helper Function Make Use Of LocalStorage Or Cookies?

@Snapey I see. So what would you recommend? Session, cookie, or localStorage? Here is a post of mine from another forum. To be honest, I don't really see the difference between the three in my case. Since if I use localStorage wouldn't it be just like session or cookie if I use with it AJAX?

Scenario: site.com has a search bar with all sorts of input fields where once all those are filled will redirect the user to site.com/results which will show the user's search results based on the filters they set up on the previous page. Now, site.com/results/1 will show each individual search result. However, whenever a user hits 'back' from site.com/results/1 all of the previous filters that were set up by the user initially are erased. My boss doesn't want that. Also, in the future possibly my boss would want to implement sending emails for search results that had been 'abandoned' same as that with an abandoned shopping cart.

I am wondering if localStorage + AJAX would be perfect for this? Maybe from site.com once the user fills up the input fields have those values stored in the localStorage and use those values in the filters of site.com/results and also insert them to my AJAX calls when user changes the filters in site.com/results to dynamically change the results on that page. And in the future, have the values in localStorage be sent over to the user by email.

Or would I better off using php COOKIES or SESSION instead? (site uses PHP on the back end)

27 Apr
7 months ago

p0t4t0 started a new conversation Does The Old() Helper Function Make Use Of LocalStorage Or Cookies?

I am just curious. Because right now I am about to work on a project where I need to store user input throughout different pages and wouldn't localStorage be better for this?

22 Apr
7 months ago

p0t4t0 left a reply on Can Someone Help Me With My Laravel AJAX Call, Why Is This Not Working?

btw I figured this out if anyone else is experiencing the same problem I was here is the solution:

$.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
      });

the reason I think the request wasn't going through was because of Laravel's security feature, and the code above is a csrf token that gets sent along with the AJAX request, kind of like the @csrf in your forms.

p0t4t0 started a new conversation Need Help With My Polymorphic Models

Hello all

I have a polymorphic relationship set up with my Post and Comment models with Upvotes. Everything is fine except for I can't associate which user upvoted a Post or Comment.

here is my Upvotes table

public function up()
    {
        Schema::create('upvotes', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('upvoteable');
            $table->timestamps();
        });
    }

my Comment model

public function upvotes()
    {
      return $this->morphMany('App\Upvote', 'upvoteable');
    }

my Post model

public function upvotes()
    {
      return $this->morphMany('App\Upvote', 'upvoteable');
    }

routes

Route::post('/post/{id}/upvote', '[email protected]')->name('scribble.upvote');

or I could probably get away with

Route::post('/post/upvote', '[email protected]')->name('scribble.upvote');

since I was after all going to do the upvoting via AJAX...

and lastly my PostUpvoteController

public function upvote(Request $request)
    {
      $post= Post::findOrFail($request->id);
      $upvote = new Upvote;

      $post->upvotes()->save($upvote); // this is the part I can't figure out

      return response()->json([
        'upvoted' => // should return true or false depending on whether the user has already upvoted the post or not
      ])
    }

$post->upvotes()->save($upvote) I can't figure out how to pass the $post->user->id into this save method. Should I be adding a user_id column to my Upvotes table so I can associate each upvote to a user? If so, how can I persist the $post->user->id into said column?

21 Apr
7 months ago

p0t4t0 started a new conversation Is There Any Significant Difference To Setting Up Your API Endpoints In Routes/api.php As Opposed To Routes/web.php

I am just curious since I've seen tutorials where they set up URI endpoints in web.php

08 Apr
8 months ago

p0t4t0 left a reply on Can Someone Help Me With My Laravel AJAX Call, Why Is This Not Working?

i tried manually accessing my /test/{id} route and it gives a MethodNotAllowedHttpException, could that be it?