jcmargentina

Experience

28,910

22 Best Reply Awards

  • Member Since 1 Year Ago
  • 123 Lessons Completed
  • 0 Favorites

22nd July, 2018

jcmargentina started a new conversation AngularJS + Interceptor - Cannot Access Authorization Header But Is There In Chrome Dev Tools! • 14 hours ago

I am totally lost with this issue. I have being struggling with it since 5 hours ago. I dont know what is going on.

I have an angularJS app. The app uses JWT tokens in order to authenticate.

The token gets refreshed in every single request it makes to the backend.

The token gets attached in the header of the response or request.

So when a request goes out to the backend, the response has the new token in the header.

The issue ,.....

I cann perfectly see the new token from Chrome Developer tools under the network tab. But in my angularJS ... the authorization header is not there.

I leave here the codes I am using and also some screenshots from my browser.

Any help is welcome.

Screenshots:

here we can see the actual request sent to the server. Under the "request headers" I succesfully attach the TOKEN saved in my localStorage.

And under the "Response headers" we can successfully see the new token sent by the Backend ... BUT! I cannot update the token in my local storage with the new one, because it looks like angularJS does not "see" the authorization header or somethin like that.

request header response header

My interceptor:

app.config( function ($httpProvider) {

    $httpProvider.interceptors.push(["$q", "$location", function ($q, $location) {

        return {

            "request": function (config) {
                config.headers = config.headers || {};

                var token = window.localStorage.getItem("_token");

                if (token) {
                    config.headers.Authorization = "Bearer " + token;
                }

                return config;
            },

            "response" : function (response) {
                /* Aqui debo sacar el token del header y guardarlo en el localstorage */

                console.log("Response", response);

                let token = null;

                if (response && response.data && response.data.access_token) {

                    token = response.data.access_token;

                } else if (response && response.config && response.config.headers && response.config.headers.Authorization) {

                    token = response.config.headers.Authorization;

                    if (token) {
                        token = token.split(" ")[1];
                    }

                } else {

                    console.log("ERROR FATAL");
                    token = null;
                }

                if (token) {

                    window.localStorage.setItem("_token", token);

                    response.config.headers.Authorization = "Bearer " + token;
                }

                return response;
            },

            "reponseError": function (response) {

                if (response.status == 401 || response.status == 403) {

                    window.localStorage.removeItem("_token");

                    //$location.path("/login");
                }

                $q.reject(response);
            } 

        };

    }]);

});

1st July, 2018

jcmargentina left a reply on Too Few Argument Problem In Laravel 5.6 • 3 weeks ago

sorry. your code was ok then.

jcmargentina left a reply on Data Showing As "undefined" When Printing Values Into Blade • 3 weeks ago

just updated my answer

jcmargentina left a reply on Too Few Argument Problem In Laravel 5.6 • 3 weeks ago

mmm wait ... are you using the default RegisterController.php file laravel gives you ? or you wrote your own ?

jcmargentina left a reply on Data Showing As "undefined" When Printing Values Into Blade • 3 weeks ago

can you try this?

var linked_entry;
    
    var sliders_row = '<tr> \
    <td> %id </td> \
    <td>%title</td> \
    <td>%description</td> \
    <td>%image</td> \
    <td>%isVisible</td> \
    <td class="entry_table_options_container"> \
    <i class="fa fas fa-pencil-alt" data-id="%id" data-title="%title" data-content="%description" data-image="%image" title="Editar" style="background-color:#5BC0DE;"></i> \
    <i class="fa far fa-trash-alt" data-id="%id" data-title="%title" data-content="%description" data-image="%image" title="Borrar" style="background-color:#D9534F;"></i> \
    </td> \
    </tr>';
    
    var csrf = $('meta[name=csrf-token]').attr('content');
    console.log(csrf);
    
    $('.sidebar_entry_container').click(function(e){
        e.preventDefault();
        linked_entry = $(this).attr("data-link");
        $('.entry_container').removeClass('visible');
        $('.entry_container[data-link=' + linked_entry + ']').addClass('visible');
        console.log(linked_entry);
        
        
        
        $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        
        
        $.ajax({
            type: 'GET',
            url:  '/' + linked_entry + '',
            
            success: function(data) {
                console.log(data);
                $.each(data, function () {
                    
                    newRow = sliders_row;
                    newRow = newRow.replace(/%id/g,data.id);
                    newRow = newRow.replace(/%title/g,data.id);
                    newRow = newRow.replace(/%description/g,data.id);
                    newRow = newRow.replace(/%image/g,data.id);
                    newRow = newRow.replace(/%isVisible/g,data.id);

                    $('.entry_table_container[data-link=' + linked_entry + ']').append(newRow);
                });
                
            },
            
            error: function(data) {
                
                alert('Something failed');              
            }
        });   
    });

check if I have some syntax errors by the way. I know you will get the main idea of the code

jcmargentina left a reply on Too Few Argument Problem In Laravel 5.6 • 3 weeks ago

@mouse let us know

jcmargentina left a reply on Too Few Argument Problem In Laravel 5.6 • 3 weeks ago

can we try something ?

change your controller like this.

add at the top the following

use Illuminate\Http\Request;

then change your create method for

 public function create(Request $request)
    {
    $validData = $this->validate($request, [
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);

        return User::create([
            'email' => $validData['email'],
            'password' => Hash::make($validData['password']),
        ]);
    }

please check for typeo errors, as I am not in my computer and probably I missed out some characters.

good luck

jcmargentina left a reply on Is Laravel 'faster' Than Ruby On Rails? • 3 weeks ago

ok 2 things

  1. Comparing RoR vs Laravel, should be a comparison of features, or learning curve , something like that.

Because, every framework is designed with some gold in mind. That is why the metric should not be performance ... at least not the only one.

  1. RoR relies on Ruby and Laravel on PHP, Ruby vs PHP sounds like a more reasonable performance comparison... in that case you can find that PHP7 has a better performance than RUBY.

For example, check this out:

https://benchmarksgame-team.pages.debian.net/benchmarksgame/faster/php-yarv.html

At least this is my opinion, hope it helps

30th June, 2018

jcmargentina left a reply on Is Laravel 'faster' Than Ruby On Rails? • 3 weeks ago

laravel is not only faster ... also with an stable performance.

this is the most serious benchmark i found out there

https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=fortune

please do not confuse yourself. you will see some ruby at the top of laravel .... but its because they are using other frames in ruby.

also .... php is over ruby in the general view.

RoR does not even appear in the ranking due to the low performance.

jcmargentina left a reply on Route [users.index] Not Defined • 3 weeks ago

just edited my answer

jcmargentina left a reply on Route [users.index] Not Defined • 3 weeks ago

@Msoft .... fix your html

with an "href" mm ????? thats wrong

use this

Post Your Ad Here!

jcmargentina left a reply on Redirect User To Same Page With "#myRegistrations" Active • 3 weeks ago

i would like to know what do you actually want to achieve. hoy want to clear the session or want to set #myRegistrations active?

sounds stupid but you depending en your answer. ... are the choices we have

29th June, 2018

jcmargentina left a reply on Single Page Application - Techniques • 3 weeks ago

@RoboRobok , there is not an absolute formula that tells you that an SPA is better than a classical approach.

You need to use these "techniques" according your project needs.

2 cases.

  1. You need a SEO friendly website, for your institutional website (i.e restaurant site), then ... go with classical http back and fordward approach, what is the problem? LOL

  2. You dont care about SEO, lets say ... and admin panel , something like that, where you have a high rate of interaction ... choose SPA or hybrid approach.

these are just examples, not mandatory at all.

I think the secret here is to understand and use what is better in every single situation , I mean a situation not only the type of project ... but also ... the time you have to do it ... the money ... your team ... etc.

PD:

Guys lets debate, in peace. Some day in the future we will hang out together in a LaraCon afterparty ... all drunk like brothers and sisters.

Cheers!

jcmargentina left a reply on Single Page Application - Techniques • 3 weeks ago

oh mama! hot topic today. I will read this as soon as I get home

jcmargentina left a reply on Password: Reset() Method Issue • 3 weeks ago

you are welcome @splendidkeen

28th June, 2018

jcmargentina left a reply on Relation Definition With Multiple Fields • 3 weeks ago

as far as I know, relationships are declared between 2 fields only (origin and destiny)

your problem can be solved with the actual eloquent relationship model schema.

go for it!

jcmargentina left a reply on Password: Reset() Method Issue • 3 weeks ago

are you handling errors in the page you are redirected ? in order to see if laravel si sending you some.

just add something like

 @if ($errors->any())

                <ul>
                @foreach($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
                </ul>
          @endif

in the blade template you get after reset is execute, in order to see if you actually get some errors there.

I will asumme you have a /home declared.

jcmargentina left a reply on Dynamically Choose Database • 3 weeks ago

you are welcome my friend

jcmargentina left a reply on How To Show Json On Error 419 (csrf) On Laravel? • 3 weeks ago

even though the answer is correct i wonder if you only handle json requests in your laravel app.

because you handle another Type like the regular ones .... you should check the header in you request to know the Type of response to give back

jcmargentina left a reply on Dynamically Choose Database • 3 weeks ago

I would say that this depends in what you want to achieve.

for exanple ... for certain cases this would help you

https://laravel.com/docs/5.6/database#using-multiple-database-connections

if you want to run console commands you can always create your own commands (make:command) and handle the logic to select the proper db inside it.

jcmargentina left a reply on Logic To Change Button After Adjudicator Score A Participant • 3 weeks ago

I cannot see the image but you need to save the score of an adjudicator to the video. you need to save that action somewhere (i.e the database)

unfortunetly hoy dont have nothing coded yet so is hard for anyone to actually help you unless you want someone to do the work for you .... is not bad but you might have to pay for that work to someone.

are you new to programming? to laravel?

jcmargentina left a reply on How To Delay Database/mail Notifications? • 3 weeks ago

@a-coudray glad to know.good luck

27th June, 2018

jcmargentina left a reply on How To Delay Database/mail Notifications? • 3 weeks ago

RemindApplication is a notification created by php artisan right?

RemindApplication should implement the ShouldQueue interface and use the Queueable trait.

You shoudl configure your QUEUE and also ... RUN YOUR QUEUE WORKER (php artisan queue:work) and leave it running

the $when variable should be a Carbon instance object, ... right?

all of this is ok ?

jcmargentina left a reply on Download Csv File And Reload Page After Download In Controller • 3 weeks ago

execute your download by AJAX, and after completion, perform whatever you need to do.

Is the only way I think

jcmargentina left a reply on AJAX File Upload Failing Validation? • 3 weeks ago

whats is the list of errors you get?

Also, as far as I know, you CANNOT upload a file by AJAX, unless you do something extra.

Mostly you need to use FormData.

Please read these links and you will get a better understanding of what I am talking about.

(Algunos en español para vos)

https://desarrolloweb.com/articulos/upload-archivos-ajax-jquery.html

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

http://blog.teamtreehouse.com/uploading-files-ajax

https://stackoverflow.com/questions/4006520/using-html5-file-uploads-with-ajax-and-jquery

PD: This is expected, imagine if any website could just have a malicious javascript file, and could automatically upload an image from your computer??? Seria una mierda a? JAJA.

SALUDOS

jcmargentina left a reply on Logic To Change Button After Adjudicator Score A Participant • 3 weeks ago

I think you need to provide us something more elaborated. Things can be modeled in a lot of ways.

Try to do your best, desing your models , relationships, views, controllers, routes, etc. and then let us know

jcmargentina left a reply on Issue With Retrieving Data • 3 weeks ago

@dionarap , you are welcome , please mark an answer you think it was helpfull, in order to document your question for future readers in the forum

jcmargentina left a reply on Issue With Retrieving Data • 3 weeks ago

but how is the HTML rendered correctly ??? I dont get it

jcmargentina left a reply on Issue With Retrieving Data • 3 weeks ago

OMG, @Cronix is right, you have typo there

jcmargentina left a reply on Issue With Retrieving Data • 3 weeks ago

Ok, thats it. It is what I told you first my friend, is your javascript code.

you are using

event.target

and that is not correct.

in order to see the exact instruction do 1 thing. I know the answer but I want to you to get it.

remember the console.log(event.target) , that gave you null ???

ok, now just do

console.log(event)

and EXAMINE the event object, try to look something similar than "target" ... for example, "currentTarget" ... and check if its content is the control (in your case ) you are looking for.

jcmargentina left a reply on Issue With Retrieving Data • 3 weeks ago

@dionarap , ok. Excuse me if I dont understand well the situation, my native language is spanish so sometimes I dont get really good the english.

Please ... Please do this for me, doesnt matter if you think it is ridiculuous, please do it.

I am assuming you have chrome installed as your browser.

  1. when you render your page (view) , please, right click on it, and INSPECT the source code, and look you your are actually filling ok the data-id attribute of your element

  2. Please do "Developers tools, network tab" thing I told you to do, in order to actually see what is the browser sending to PHP

  3. Did you add the "console.log" instruction I suggested you? what was the output?

I will wait your reply.

jcmargentina left a reply on Problem With Saving Password During Edition User As Admin • 3 weeks ago

you are welcome.

pay attention I have use a variable called $requestData to retrieve all parameters from $request.

this is considered a good practice from a lot a software developers, because you have parameters exclusively in one single variable.

good luck!

26th June, 2018

jcmargentina left a reply on Problem With Saving Password During Edition User As Admin • 3 weeks ago

the problem is the order of the instructions.

make this changes

   public function update($id, CreateUserRequest $request)
    {
        $user = User::findOrFail($id);

        $requestData = $request->all();

        $requestData["password"] = Hash::make($request->password);

        $user->update($requestData);

        Session::flash('user_updated','Dane użytkownika zostały zaktualizowane');

        return redirect('users');
    }

jcmargentina left a reply on Issue With Retrieving Data • 3 weeks ago

what is the output of the console.log instruction ?

also ... open the developers tools of your browser, and go to the network tab, click your button, and check the request you are making ... let me know if you can see the "comment_id" field in the request.

PD: realted to the changes I proposed you, ... It is high recommended that you always return a stated response from your server. If you dont, it is HTTP-antipattern.

you need to debug the whole cycle of this.

Regarding this ...

Could the problem be possible that its a foreach so their is multiple comment_id's and multiple approval buttons?

should not be a problem

jcmargentina left a reply on Issue With Retrieving Data • 3 weeks ago

You need to check that you are actually sending the coment_id to PHP

in your JS, specific at this line:

data: {    comment_id: $(event.target).data("id")}

probably $(event.target) is undefined

change your jvascript to

var urlApproval = '{{ route('approvals') }}';
$('.approval').on('click', function(event){
    event.preventDefault();
    var buttonToChange = $(this);
    var $this = $(this);

/* attention here*/
 console.log(event.target);

    $.ajax({
                method: 'POST',
                url: urlApproval,
                data: {    comment_id: $(event.target).data("id")}
    })


            .done(function() {
                if(buttonToChange.hasClass('approved')) {
                    buttonToChange.addClass('not-approved');
                    buttonToChange.removeClass('approved');
                    count = $this.siblings('.approval-count');
                    count.html(parseInt(count.html()) - 1);
                }else {
                    buttonToChange.addClass('approved');
                    buttonToChange.removeClass('not-approved');
                    count = $this.siblings('.approval-count');
                    count.html(parseInt(count.html()) + 1);
                }
            });
});

then open the javascript console of your broser and click the button, and check the log and see if you are actually retrieveing the data you want.

also I would suggest you change your php to something like ,,,

public function setApproval(Request $request)
{

   try {
    $comment_id = $request['comment_id'];
    $comment = Comment::find($comment_id);

    $approved = Auth::user()->approvals()->where('comment_id', $comment_id)->first();
    if($approved == null) {
        $approved = new ApproveReview();
        $approved->user_id = Auth::user()->id;
        $approved->comment_id = $comment_id;
        $approved->save();
    }
    else{
        $approved->delete();
    }
        
        } catch (Exception $e) {
              
               return response()->Json([
               'msg' => "{$e->getMessage()}"
                ], 400);            
        }       

return response()->Json([
'msg' => 'Success'
], 200);

}

debbuging is the answer

13th June, 2018

jcmargentina left a reply on Post An <input Type="date"> To Laravel Backend - Deal With Dates - Convert To Carbon • 1 month ago

Sorry, never mind, I just found out the answer. LOL

jcmargentina started a new conversation Post An <input Type="date"> To Laravel Backend - Deal With Dates - Convert To Carbon • 1 month ago

I am having a little problem dealing with dates handling a regular date value in my laravel backend.

I receive the value as something like:

"2018-06-13T20:59:45.665Z", even though is actually 17:59 .... also I dont know how to convert this date format into a Carbon Date instance.

Also ... how to validate the field to be a date?

4th June, 2018

jcmargentina left a reply on Github • 1 month ago

how possible is it that microsoft turns github into a paid tool?

jcmargentina left a reply on Github • 1 month ago

WTF?!!!! what do you recommend as an alternative

jcmargentina left a reply on Github • 1 month ago

were did you read that ?

28th May, 2018

jcmargentina left a reply on AngularJS - Factory Array From Controller • 1 month ago

@nolros , I am still reading your code ... I am a newbie still in angularJS that is why is taking me a while to understand your code.

after I ready and understand everything I will give you a reply.

But ... thanks a lot for your effort writting this piece of code.

27th May, 2018

jcmargentina left a reply on Best Strategy To Model This? • 1 month ago

even thoug I was trying to avoid the use of plain SQL like instructions, your answer helped me and I am sure it will help others.

I will mark it as correct ... but for future readers ... please keep in mind this too:

https://stackoverflow.com/questions/50537890/laravel-best-strategy-to-model-tables-relations/50538010#50538010

So these answers do not cover all the issue ... both gives you a better understanding of the problem and how can be solved.

25th May, 2018

jcmargentina left a reply on Best Strategy To Model This? • 1 month ago

I would like to get the school/store of a user from a user model instance too

jcmargentina started a new conversation Best Strategy To Model This? • 1 month ago

Hello everyone, I have the following issue.

I am trying to find out what is the best way to organize a relationship beetwen Users-Roles-Stores-Schools.

A User can have multiple Roles attached to a Store or to a School, so one can create the realtion :

"User [[email protected]] is [root] for school [HighSchool1]"

and also

"User [[email protected]] is [user] for store [Store1]"

So a user can have multiple roles, but that roles is attached to a School OR a Store

at begining I was about to do this ...

User
-id
-name
-email
-password

Roles
-id
-name

Roles_user
-id
-rol_id
-user_id
-school_id           //whatch this
-store_id             //whatch this

School
-id
-name

Store
-id
-name

The problem is, that in the future, the system could also handle supermarkets ... and I would have change my roles_user table to attach new columns for that.

How can I achieve this .... using of corse Eloquent and Relationships?

Thanks in advance

jcmargentina started a new conversation AngularJS - Factory Array From Controller • 1 month ago

I have a newbie question here.

I am coding a factory in angularJS. With it I want to have a list of users, and also a method to fill it.

So this is my code ...

The factory

app.factory("usuariosFactory", function ($http) {


    var f = {};

    f.users = [];

    f.getUsers = function (callback) {
        var token = window.localStorage.getItem("_token");


        $http.get("http://localhost:8000/api/user/list?token=" + token).then(function (response) {
            f.users = response.data.users;

            /* the console.log outputs OK with the users from the server */
            console.log(f.users);
        });
    }; 

    return f;
});

the controller

app.controller("usuariosController", function ($scope, usuariosFactory) {
    var scope = this;

    /* link users from factory to controllerś scope .. NOT WORKING */
    usuariosFactory.getUsers();

    scope.usuarios = usuariosFactory.users;
});

I am having troubles getting this to work

jcmargentina left a reply on CORS - Urgent - Stuck Since 2 Hours Ago, Cannot Move Fordward! • 1 month ago

I found the answer ... OMG!!!!!!!!!!!!!!

the problem was I was not adding a "headers" section in my request.

I have to add this in my AJAX request:

headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }

3 hours ..... 3 HOURS!!!!!!!!!!!!!!!!!!!

jcmargentina left a reply on CORS - Urgent - Stuck Since 2 Hours Ago, Cannot Move Fordward! • 1 month ago

thanks @click , but I wanted to use my own code.

jcmargentina started a new conversation CORS - Urgent - Stuck Since 2 Hours Ago, Cannot Move Fordward! • 1 month ago

Hey everybody. I am building a SPA using angularJS and Laravel 5.6.21.

I am having problems with POST requests using Jquery + Ajax. I am getting this

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

GET requests are fine, POST is not working at all.

I have a Middleware like this:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, PUT, POST, PATCH, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Credentials',' true')
            ->header('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, Authorization, X-Requested-With, application/json'); 
    }
}

My Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\Cors::class, /* HERE MY MIDDLEWARE */
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

.........

The route is under api.php so the /api/ is prefixed.

My post requests using jquery dont work and I dont know what else to do.

Edit Your Profile
Update

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