p0t4t0

Experience

12,730

0 Best Reply Awards

  • Member Since 8 Months Ago
  • 80 Lessons Completed
  • 0 Favorites

10th August, 2018

p0t4t0 left a reply on Problem With Mix • 1 month ago

still haven't figured this out :(

6th August, 2018

p0t4t0 started a new conversation Problem With Mix • 1 month ago

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".

28th July, 2018

p0t4t0 started a new conversation How To Iterate Through Associative Array In Factory Seeders? • 1 month ago

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,
    ];
});

22nd July, 2018

p0t4t0 started a new conversation Trailing Slashes In Query Strings A Good Idea? • 1 month ago

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

21st July, 2018

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

@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?

20th July, 2018

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

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? • 2 months ago

@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?

18th July, 2018

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

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?

17th July, 2018

p0t4t0 started a new conversation Need Advice With My Vue + Passport Login System • 2 months ago

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

13th July, 2018

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

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? • 2 months ago

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"

11th July, 2018

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? • 2 months ago

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? • 2 months ago

@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.

10th July, 2018

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? • 2 months ago

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? • 2 months ago

@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.

9th July, 2018

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? • 2 months ago

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? • 2 months ago

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.

7th July, 2018

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 • 2 months ago

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 • 2 months ago

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?

5th July, 2018

p0t4t0 started a new conversation How Do I Run Redis On Windows? • 2 months ago

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.

1st July, 2018

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

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? • 2 months ago

@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? • 2 months ago

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>

9th June, 2018

p0t4t0 left a reply on Is It Advisable To Hash Ids In Url? • 3 months ago

@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? • 3 months ago

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

5th June, 2018

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

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

4th June, 2018

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

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.

19th May, 2018

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

@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.

18th May, 2018

p0t4t0 started a new conversation Laravel Custom Class As Service Provider • 4 months ago

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? • 4 months ago

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? • 4 months ago

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

16th May, 2018

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

@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 • 4 months ago

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?

8th May, 2018

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

Are there are better alternatives?

1st May, 2018

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

@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? • 4 months ago

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.

29th April, 2018

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

@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)

27th April, 2018

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

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?

22nd April, 2018

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

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 left a reply on Need Help With My Polymorphic Models • 5 months ago

@Vilfago thanks! it worked

p0t4t0 started a new conversation Need Help With My Polymorphic Models • 5 months ago

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?

21st April, 2018

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 • 5 months ago

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

8th April, 2018

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

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

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

@jlrdw it's working, i can console.log(id) just fine

p0t4t0 started a new conversation Can Someone Help Me With My Laravel AJAX Call, Why Is This Not Working? • 5 months ago

web.php

Route::post('/test/{id}', '[email protected]')->middleware('admin');

scripts.js

$(document).ready(function() {
  $('.foo').click(function() {
    var $this = $(this),
        id = $this.data('id'),
        token = $this.data('token'),
        answer = confirm('Are you sure you want to flag this post as spam?');
    if (answer) {
      $.ajax({
        url: '/scriblr/public/test/' + id,
        type: 'post',
        dataType: 'json',
        data: {
          'id': id,
          '_method': 'POST',
          '_token': token
        },
        success: function(response) {
          console.log(response);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.log(JSON.stringify(jqXHR));
          console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
      });
    }
    return false;
  });
});

AdminController.php

public function spam(Request $request)
    {
      return response()->json([
        'foo': 'bar'
      ]);
    }

i get this error in the console POST http://localhost/scriblr/public/test/9 500 (Internal Server Error)

p0t4t0 left a reply on I've Imported JQuery And A JQuery Plugin With A CDN But Plugin Still Doesn't Work • 5 months ago

@Snapey oh what do I need to do then to get my script.js file to work with it? because I tried creating a script file in public/js/ and it didn't work. That's why I imported jQuery with the CDN.

p0t4t0 left a reply on I've Imported JQuery And A JQuery Plugin With A CDN But Plugin Still Doesn't Work • 5 months ago

@Snapey I'm not sure what you mean. I tried logging something with jQuery before I imported jQuery with the CDN but it doesn't seem to work. That's why I imported it.

p0t4t0 left a reply on I've Imported JQuery And A JQuery Plugin With A CDN But Plugin Still Doesn't Work • 5 months ago

@topvillas the $.confirm function

@Snapey yes all files are loading okay, nope app.js is just there. the error happens after i click the button.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.