mushood

mushood

Member Since 2 Years Ago

Port Louis

Back End Web Developer at Esokia Web Agency ltd

Experience Points 149,580
Experience Level 30

420 experience to go until the next level!

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

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 1053
Lessons
Completed
Best Reply Awards 68
Best Reply
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.

23 May
4 hours ago

mushood left a reply on Data Shows In Console, But Not In The View

created() {
            const vm = this;
            axios.get('./api/admin')
            .then(response => vm.clients = response.data.data);
        },

I want to explain this part but I dont have the clear words to actually do so,I would suggest watching the Vue 2 step by step video. Basically its about the keyword "this" in JS. The this in the axios promise is not the same this as outside the promise where your clients exist.

22 May
1 day ago

mushood left a reply on Data Shows In Console, But Not In The View

@wallyj

in your controller, return a json response

return response()->json(compact('user','clients'));

now in your axios then promise

methods: {
            loadUsers() {
const vm = this;
                axios.get("api/user").then(({ data }) => (vm.users = data.user));
            }

mushood left a reply on Open Source Real World Laravel Projects?

@devfrey Spot on. In the beginning of this project, most of them were open-source. Nevertheless, quite a few of them still are :)

mushood left a reply on Data Shows In Console, But Not In The View

I usually have the loadUsers in the mounted() section. You could try that.

One thing that could help in debugging is the vue-js dev tools

https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en

See what is being set to users.

mushood left a reply on Error While Uploading Zipped Images

try to check the error_log in public_html/error_log. If not present, try to look for error logger in cPanel. Usually error 500 are logged somewhere. Maybe you need to clear your tmp file. Or allow more size in your tmp file

mushood left a reply on How To Change PHP Version In Homestead

If i'm not wrong, you have to run "vagrant provision" first when you make such changes

mushood left a reply on Data Shows In Console, But Not In The View

try this

methods: {
            loadUsers() {
const vm = this;
                axios.get("api/user").then(({ data }) => (vm.users = data.data));
            }

mushood left a reply on 404 On /storage. FollowSymLinks Option Cannot Be Enabled On VPS.

Maybe you can create a storage driver with a path that points directly to your public_html, so that you can save your files there.

If your hosting provider cannot enable symlinks, not much can be done about that. I use bluehost on my side and symlinks are enabled there.

21 May
2 days ago

mushood left a reply on Modify Ajax Script To Perform Update/create On The Same Route

You should have an hidden input called id on your form

@if ($score != null)
<input type="hidden" name="score_id" value="{{$score->id}}"/>
@else
<input type="hidden" name="score_id" value="0"/>
@endif

So if you have your score model and updating, the score_id will be the id of the score. If you are creating, it will be zero

Then in your controller

if ($request->score_id == 0) {
    $v = new Score();
}

if ($request->score_id > 0) {
    $v = Score::find($request->score_id);
}
    $v->team= $team;
    $v->fouls= $fouls;
    $v->score= $score;
    $v->save();

mushood left a reply on Need Help For (school) Questions/tests Relationship

Hello

I would like to clear the confusion first. Using the example from documentation, if you needed to have Tags on a video model and on a post model, you would need to add two model, VideoTag and PostTag. But since both are tags, we can use a Polymorphic relationship and the Tag model will have a type column which will say if it belongs to a Post or a Video.

Coming to your problem. You have the following models: Question, TypeMultipleChoices, TypeOrdering, Choice

One question can have many choices, so if you define a 1:N rel between Question and Choices. You can access the choice by $question->choices

Now the polymorphic part: TypeMultipleChoices should be able to transform into a question model, TypeOrdering should also be able to transform into a question.That way, if you want to get the choices of a randomly selected question, you can just use $model->question->choices

But from what I can see the TypeModel can only become ONE question. So one to one polymorphic rel would be more suited.

How i would do it. If my TypeModel had some unique functions, I would go polymorphic. Otherwise, i would simply have a type column on the question mode to tell me what type of question it is, then 1:N relationship between question and choices

mushood left a reply on Re-useable Vue Popover/tooltip

I would suggest looking at the source code of those packages. You can understand how they work and then import only those codes into your project. You can tailor the code to exactly your need.

mushood left a reply on CORS Issue Only On Axios

This question was in reference to this one: https://laracasts.com/discuss/channels/general-discussion/cors-error-2?page=1#reply=512871

I was able to correct my mistake. If you have the same above issue, maybe look into the above link for some hints

mushood left a reply on CORS Error

I fixed my issue by changing the request. Somehow if I include the content-type in the POST, on android version of my app it was not working. However the iOS version does work even with the content-type

Hope this helps you debug.

var data = new FormData();

        data.append('grant_type', 'password');
        data.append('client_id', '2');
        data.append('client_secret', 'secret_token');
        data.append('scope', '*');

        data.append('username', 'mail');
        data.append('password', 'pwd');

        const config = {
        'mode': 'cors', 
            method: 'POST',
            headers: {
                'Accept': 'application/json',
            },
            body: data,
        }   

        var link = 'https://domain.com/oauth/token';
        fetch(link, config)
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);

            })
            .catch(err => {
                console.log(err);
            })
20 May
3 days ago

mushood left a reply on CORS Issue Only On Axios

Bump and additional info:

In the axios call, I am able to access the POST data via

file_get_contents('php://input');

However my $_POST is empty

18 May
5 days ago

mushood left a reply on CORS Issue Only On Axios

Hello

I went from .html to .php. Not through laravel @

17 May
6 days ago

mushood started a new conversation CORS Issue Only On Axios

Hello I am getting a CORS issue only on axios.

In this html page, I am using a traditional form to post from domain A to domain B.

The form submit works correctly. The ajax post request works correctly. The axios post returns me to a CORS .

Access to XMLHttpRequest at 'https://domainB/post.php' from origin 'http://domain A.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource


Registration Form

<h2>Registration Form</h2>

<form action="https://domainB.com/post.php" method="POST">

    Last name:

    <input type="text" name="username"> 

    <input type="hidden" name="form_submitted" value="1" />

    <input type="submit" value="Submit">

</form>

<script>
    $(document).ready(function(){
$.post("https://domainB.com/post.php",
{
  username: "Donald Duck",
  city: "Duckburg"
},
function(data,status){
  alert("Data: " + data + "\nStatus: " + status);
});

});

(function() {

axios.post('https://domainB.com/post.php', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

})();

```

my post.php

<?php
echo 'post working';
var_dump( $_POST);
 $_POST['username'];
?>
16 May
1 week ago

mushood left a reply on CORS Error

Sample request


---------------
Edit: Sample request

var data = new FormData();

    data.append('grant_type', 'password');
    data.append('client_id', '2');
    data.append('client_secret', 'secret_token');
    data.append('scope', '*');

    data.append('username', 'mail');
    data.append('password', 'pwd');


    var link = 'https://domain.com/oauth/token';
    fetch(link, config)
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson);

        })
        .catch(err => {
            console.log(err);
        })

mushood started a new conversation CORS Error

Hello.

I created a mobile app which consumes a back-end API.I am using fetch api on JS end to make my requests. However, I am getting a CORS error

Error message: Access to fetch at 'mydomain.com' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried the following:

A/ In my .htaccess

 RewriteEngine On
 RewriteCond %{HTTPS} off
 RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]]
 <FilesMatch ".(ttf|otf|eot|woff)$">
 <IfModule mod_headers.c>
 Header set Access-Control-Allow-Origin "*"
 Header set Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
 Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With, token"
 Header set Access-Control-Allow-Credentials "true"
 </IfModule>

This had the effect of at least letting my GET request to pass.

B/ in my index.php

header("Access-Control-Allow-Origin: *")
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");

Same effect as .htaccess, only GET request passes, with OPTIONS . I also saw the my Access-Control-Allow-Origin would be "*, null" and i would get an error stating that only one is allowed.

C. https://github.com/barryvdh/laravel-cors In AuthServiceProvider, i tried both these. Only one at a time, not at the same time.

        Route::group([ 'middleware' => 'cors'], function() {
            Passport::routes();
        });

    Passport::routes(null, ['middleware' => [ \Barryvdh\Cors\HandleCors::class ]]);

D. Created a custom middle with this code

    public function handle($request, Closure $next)
    {
                return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }

I dumped my $_SERVER and could not find the HTTP_ORIGIN, HTTP_REFERER. I did get my HTTP_REMOTE_ADDR

What is even more frustrating was that my app was working correctly, and I just suddenly started having the issue (back-end hosted on bluehost)

15 May
1 week ago

mushood left a reply on Controller Namespace Best Practices

I think they examplified that by the way the Verification Controller was implemented. It just verifies emails.

I think this is a very clean way of doing things, but you risk having too many controllers then. Thats why I would say, if this case happens, just organize them in different folders. Have a CRUD folder for controllers that just deal with CRUD.

You could also use traits, to add functionality to your controllers. For example, a publish link, which is just meant to publish an article, set the isPublished flag to true. Have a publishable trait and use it at the top.

mushood left a reply on Multiple Laravel Form Request Validation Rules In A Single File

While I would not be prone to do that myself because I do prefer the rules to be in each seperate file, here is a way you can do it:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ReviewRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return $this->getCustomRules($this->input('class'));
    }

    public function getCustomRules($class)
    {
        $rules = [];

        switch($class) {
            case "asdf" :
                $rules = [
                    'title'         => 'required|max:255',
                    'description'   => 'nullable',
                    'type'          => 'required|in:tag,category',
                    'image'         => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                ];
                break;
            case "B":
                $rules = [
                    'title'         => 'required|max:255',
                    'description'   => 'nullable',
                    'type'          => 'required|in:tag,category',
                    'image'         => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                ];
                break;
        }

        return $rules;
    }
}

You'll need to have an input which will be used in the switch method to know which rule to use. I used 'class' in my case. I did not extensively test it, but did a small test and works on my side.

You'll also have to think how to handle exception.

Check how params are bound in the route service provider. You could also use that approach. Like when there is a {product} in my route, it will resolve it to a Product model.

Hope I helped nudged you in the right direction.

13 May
1 week ago

mushood left a reply on Frontend Email Verification?

Yes, you can run

php artisan vendor:publish

Choose laravel-mail in the options or laravel-notifications, depending on your use case.

12 May
1 week ago

mushood left a reply on Session Is Missing Expected Key [errors]. Failed Asserting That False Is True.

Like this

   // try {
        request()->validate(['body' => 'required|spamfree']);

        $reply = $thread->addReply([
            'body' => request('body'),
            'user_id' => auth()->id()
        ]);
  //  } catch (\Exception $e) {
   //     return response('Sorry, your reply could not be saved at this time', 422);  
   // }

    return $reply->load('owner');

mushood left a reply on Session Is Missing Expected Key [errors]. Failed Asserting That False Is True.

@h The validation exception is being caught in your catch and you are returning only this response

return response('Sorry, your reply could not be saved at this time', 422);  

Comment out the try catch block and see if it works

mushood left a reply on Where Should This Code Go??

I agree with @shez1983 . Services are for complex logic and would be an overkill in this case.

mushood left a reply on Where Can I Modify The Email Verification?

As explained above, check the verification controller and there should be a $redirectTo that you can override.

The controller also uses a trait. Open the trait and see what functions it is using. Be careful to look at all the functions and see which piece of logic you need to override. Then copy paste that code in the controller and change it according to your case.

If you wish to modify the views, run php artisan vendor: publish. Then modify the views that are now published in resources/vendor

mushood left a reply on PRINT PDF, HTML To DomPdf

I think the issue come from using blade templating. Try to load a self-contained view, that does not use include or extends

mushood left a reply on Preg_match_all With More Than One Value

You should try to refactor your function so that when you pass to it a string, it correctly formats the text and returns the correct version based on your conditions.

You can then simply apply it the body, title, etc.

From what i know, you cannot apply same accessors to multiple attributes.

mushood left a reply on Session Is Missing Expected Key [errors]. Failed Asserting That False Is True.

Be sure to have Session::start() at the beginning of your test. You can also place this in your setup function if you are using it several places.

mushood left a reply on Can Not Edit Simple Record

The issue is that you are not able to use route model binding.

Notice the the variable name is $group_permission. In your route, you need to make sure that the variable name inside {} is the same.

Two ways to correct this:

  1. Run php artisan route:list in command line. Check the variable name for this route and change in your controller.
  2. Define a route and use the name group_permission inside the {}

mushood left a reply on Select Customer From Database And Insert Into Another Table Will Multiple Data

You should think about using relationships on your model.

https://laravel.com/docs/5.8/eloquent-relationships

Depending on the relationship, there are different ways of associating them. Look at the documentation for examples.

mushood left a reply on What Pattern Prefer To Use When Combine Laravel And Vuejs

While i believe the way to go depends on your preference, i do prefer the second method. It seems cleaner to me. No need to switch between blade and Vue file, everything in one place.

At the end of thr day, it will really depend on your use case

As for user details, i pass it in as a prop.

07 May
2 weeks ago

mushood left a reply on Updated Record Via Model With Custom Identity Column

On your commission Model, you may need to set your primary key correctly

protected $primaryKey = 'destination_id';

mushood left a reply on Please Help Me With Apache2 Virtual Host Configuration

Can you access the error log for the 500 error Found at this path: ErrorLog ${APACHE_LOG_DIR}/error.log

mushood left a reply on Curl Error

It would be helpful to post the code for the curl request

mushood left a reply on Failed Asserting That Actual Size 0 Matches Expected Size 1.

The test should still be able to run even if you comment the databaseMigrations trait.

run php aritsan migrate:fresh in your terminal in necessary to set up your DB

Of course this is only temporary just for debugging

mushood left a reply on Implicit Binding Broken

Make sure that your routeKeyName is correct

If you defined this in your User model, it will look for user by name. If you did not declare any, it will look for it by id (default).

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'name';
}

You can also try removing the type hinting and check if the $user variable is correctly the ID or name.

mushood left a reply on Stark Contrast Between Chrome Vs. Chrome Incognito For Development

Do have similar issues in Firefox(not private browsing) Very difficult to give you an answer on this. Seems like an edge case.

The request is to load a file or does this request hit your controller? Do session / cookies need to be set in this request?

06 May
2 weeks ago

mushood left a reply on Stark Contrast Between Chrome Vs. Chrome Incognito For Development

There should be no major difference between Chrome and Chrome incognito.

Try posting a specific example of an error. This can be useful for precise debugging.

mushood left a reply on Error 500 When Using W3 Validator

Maybe the issue is with your .htaccess

What I would suggest doing to debug this issue:

  1. in your public, change index.php to index1.php (backup)
  2. Then create a simple index.html page . Your site should now only show this simple page
  3. Then test your page on validator.
  4. It should work correctly. If not, try changing your .htaccess to .htaccess1 (diable the .htaccess)
  5. Then if its still not working, submit a ticket to your host provider

Make sure to revert your backups after testing

mushood left a reply on The MorphOne Relation Always Return Null

I think the error comes from

protected $morphClass = 'Payement';

It should be

protected $morphClass = 'App\Payement';

mushood left a reply on 定制国外留学文凭、(551190476微/Q)英国班戈大学学位证书【英国假文凭】班戈大学假毕业证假成绩单假学历证【代办未毕业文凭认证】Bangor University

Well its spam

Translation Customized Diploma of Study Abroad, (551190476 micro / Q) University of Bangor University degree certificate [British fake diploma] Bangor University fake graduation certificate transcript false academic certificate [agent not graduated diploma certification] Bangor University

mushood left a reply on Failed Asserting That Actual Size 0 Matches Expected Size 1.

If you are not using any traits that resets your database in your test, you should open your database in something my phpmyadmin and check the table named "notifications"

mushood left a reply on Laravel Passport Tokens Tables With Thousands Of Rows

Maybe store those tokens on the user table, so that each user can only have one value

mushood left a reply on Failed Asserting That Actual Size 0 Matches Expected Size 1.

  1. Check if in your notifications table, the notification was correctly created.
  2. Did you add this to your User Model
use Notifiable;

mushood left a reply on Allowed Memory Size Of 138412032 Bytes Exhausted (tried To Allocate 20480 Bytes)

The best way is to optimize your sql. However, I dont see anything particularly wrong here.

Maybe increase memory size

ini_set('memory_limit','256M');