danyal14

danyal14

Member Since 2 Months Ago

Experience Points 6,900
Experience
Level
Lessons Completed 54
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.

22 Jan
9 hours ago

danyal14 started a new conversation Laravel Blade Pasing Json To Vue Component

I tried every possible way, may be I am missing something. when i pass json to vue component it breaks.

Route::get('/', function () {
   return view('web.index', [
       'active_link' => 'home',
       'data' => [
           ['id' => 1, 'image' => '/images/img1'],
           ['id' => 2, 'image' => '/images/img2'],
           ['id' => 3, 'image' => '/images/img3'],
       ]
   ]);
});
        <home :active-menu-link="'{{ $active_link }}'" :data="{!! json_encode($data) !!}"></home>
        <home :active-menu-link="'{{ $active_link }}'" :data="'{!! json_encode($data) !!}'"></home>

This is being displayed on page.
":1,"image":"\="" images\="" img1"},{"id":2,"image":"\="" img2"},{"id":3,"image":"\="" img3"}]'"="">

        <home :active-menu-link="'{{ $active_link }}'" :data="{{ $data }}"></home>

htmlspecialchars() expects parameter 1 to be string, array given (View: /path/resources/views/web/index.blade.php)

21 Jan
1 day ago

danyal14 left a reply on Lumen PHPUnit Lost Post Data

@DELE - Thanks for reply, it works now.

20 Jan
2 days ago

danyal14 started a new conversation Lumen Laravel Passport

Hi,

I am creating microservices in Lumen

  • user api
  • content api
  • UI

Aim is to consume user api via UI to get content from content API, I would like to know how does Laravel Passport come in use?

How does user will register using UI via user api? As I understood and implemented Laravel passport in user api.

I have created a client for personal access token, and every user that is created using UI via userAPI: uses that client key/secret to register/login.

Once user is loggedin it gets the access token/refresh_token.

I am trying to understand that if Im following the correct way of implementation?

UI saves access_token in client cookies and then send access_token with every next call required authentication.

where does refresh_token comes in use?

/**
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Psr\Http\Message\StreamInterface
     */
      public function login(Request $request){
          $http = new \GuzzleHttp\Client;

          try {
              $response = $http->post(config('services.passport.login_endpoint'), [
                  'form_params' => [
                      'grant_type' => 'password',
                      'client_id' => config('services.passport.client_id'),
                      'client_secret' => config('services.passport.client_secret'),
                      'username' => $request->username,
                      'password' => $request->password,
                  ],
              ]);
              return response()->json(json_decode((string) $response->getBody(), true));

          } catch (\Exception $e) {
            if ($e->getCode() == 401) {
                return response()->json([
                    'status' => 'fail',
                    'message' => 'Unauthenticated'
                ], $e->getCode());
            }
          }
      }
/api/auth/login
{
    "username": "[email protected]",
    "password": "secret123456"
}

returns
{
    "token_type": "Bearer",
    "expires_in": 1800,
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJ...........",
    "refresh_token": "def502000f97d446695743dc789b714fe56c6b7fe48........"
}

/api/auth/register
{
    "name": "Tester",
    "email": "[email protected]",
    "password": "test211",
    "password_confirmation": "test211"
}

danyal14 started a new conversation Passing Data From Laravel Blade To Vuejs

Hello,

I am testing case where in blad view I am calling vue component and passing a variable.

When accessing that variable in vue, getting following error.

Route:

Route::get('/about-us', function () {
    return view('web.about-us', [
        'active_link' => 'aboutus'
    ]);
});

Blade:

@section('app')
    <div id="app">
        <about-us :active-menu-link="'{{ $active_link }}'"></about-us>
    </div>
@stop

VUE:

<template>
    <section class="hero is-fullheight">

        {{ activeMenuLink }}
        
        <top-menu :activeMenuLink="activeMenuLink"></top-menu>

        <header class="hero-body">
            <div class="is-overlay has-text-centered single-spaced" style="top: 82px;">
                <h1 class="subtitle is-4 has-text-weight-light has-text-black">TEST</h1>
                <h2 class="title is-1 has-text-black">SOME</h2>
            </div>
        </header>

    </section>
</template>

<script>
    import TopMenu from './TopMenu.vue'

    export default {
        props: ['activeMenuLink'],
        name: 'about-us',
        computed: {
            welcome() {
                return this.$store.getters.welcome
            }
        },components: {
            TopMenu
        },
        mounted() {
            console.log(this.activeMenuLink);
        }
    }
</script>

Uncaught ReferenceError: activeMenuLink is not defined
    at Module../node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/web_app/js/components/TopMenu.vue?vue&type=script&lang=js& (app.js:1913)
    at __webpack_require__ (app.js:20)
    at Module../resources/web_app/js/components/TopMenu.vue?vue&type=script&lang=js& (app.js:48778)
    at __webpack_require__ (app.js:20)
    at Module../resources/web_app/js/components/TopMenu.vue (app.js:48742)
    at __webpack_require__ (app.js:20)
    at Module../node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/web_app/js/components/Home.vue?vue&type=script&lang=js& (app.js:1810)
    at __webpack_require__ (app.js:20)
    at Module../resources/web_app/js/components/Home.vue?vue&type=script&lang=js& (app.js:48640)
    at __webpack_require__ (app.js:20)
18 Jan
4 days ago

danyal14 left a reply on Eloquent Mutators And Accessors In Lumen

@VILFAGO - I try it with other date, but the what is the benefit of ->setAttribute?

danyal14 started a new conversation Lumen PHPUnit Lost Post Data

Hi Guys,

When running following test, in controller action $request->json() get nothing, even $request contains nothing.

// Test
$this->post('/api/breakingnews', ['hello' => 'world'], [
            'Content-Type' => 'application/json',
            'X-Requested-With' => 'XMLHttpRequest'
        ]);

        $this->get('/api/breakingnews');
        $this->seeStatusCode(StatusCode::HTTP_CREATED);

// Controller
 /**
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {

        $payload = $request->json();
        dd($payload);
    }


Any idea?, I found some old post related to Lumen 5.3 and looks like issue was fixed in 5.4 but I am getting same issue.

17 Jan
5 days ago

danyal14 left a reply on Eloquent Mutators And Accessors In Lumen

@VILFAGO - It shouldn't be necessarily like this.

            $breakingNews = BreakingNews::findOrFail($id);
            $breakingNews->setAttribute('expired_at', Carbon::now());
            $breakingNews->save();

Worked for me now with same code but using now()

danyal14 started a new conversation Eloquent Mutators And Accessors In Lumen

Hi Guys,

I am trying to update a field, using "Mutators" change to database is not happening. Any Idea

In controller

 $breakingNews = BreakingNews::findOrFail($id);
 $breakingNews->setAttribute('expired_at', Carbon::today()->format('Y-m-d H:i:s'));
 $breakingNews->save();

/**
     * @param null $value
     */
    public function setExpiredAtAttribute($value)
    {
        if (!$value) {
            $this->attributes['expired_at'] = Carbon::today()->format('Y-m-d H:i:s');
        } else {
            $this->attributes['expired_at'] = $value;
        }
    }

I also followed the link https://code.tutsplus.com/tutorials/eloquent-mutators-and-accessors-in-laravel--cms-30312

16 Jan
6 days ago

danyal14 started a new conversation WebSockets / Webhook

Hi Guys,

My experience with WebSockets or Webhooks is not that good, I have following use case.

/breakingnews notify platform (website & mobile devices)

I have worked with events & listeners, where I enrich data based on listener.

What should I use to broadcast breakingnews to web and mobile devices, where as they should be listening to same WebSockets for updates.

And what is need at frontend to make it listen and update UI element accordingly.

Regards Danyal

15 Jan
1 week ago

danyal14 started a new conversation Lumen Config Folder Is Missing

Hi,

I know Lumen doesn't include config folder in framework but in vendors. My question is how can I define custom env variables as I used to do in Laravel.

I used to define new custom config key in config/app.php, then to set in .env file all worked.

But in Lumen I don't see this happening.

Another thing if I can create my own config file to define Company/App related env vars.

/Regards

danyal14 left a reply on Eloquent Modeling

@MARTINBEAN - Thanks, polymorphic relations will serve my use case.

danyal14 left a reply on Eloquent Modeling

@VILFAGO - Thanks for the reply, I just want to know if Laravel relations serve my purpose. I made the same solution. Then @martinbean suggestion is make more sense :)

danyal14 started a new conversation Eloquent Modeling

Hi,

I am looking for suggestions for implementation of Eloquent models for following use case. I used to have this entities structure in Symfony3.

Just need to understand can I accomplish same in Laravel.

Use case: Model: RecipeBase: will have some generic properties Child Model: ArticleRecipe extends RecipeBase Child Model: VideoRecipe extends RecipeBase

table: recipes

How does $fillable and other traits work is this context?

13 Jan
1 week ago

danyal14 left a reply on Running Just VUEJS Application Alongwith Blade

@D9705996 - Yes I agree with your point, but we are avoiding to use vue-router because we have huge traffic and I am still not sure how vue-router works with SEO, Google and other tracking system.

How does browser rendering of vue app vs normal Laravel blade templates.

12 Jan
1 week ago

danyal14 left a reply on Running Just VUEJS Application Alongwith Blade

@D9705996 - Thanks for reply, we don't want full stack SPA. idea is to have light php Framework that serves Vue components. That php Framework will not run any php logic like console, database connections simple MVC consuming Lumen API. We are planning to have multiple micoservices containing own database and codebase , should I still consider Laravel for serving blade templating + vuejs components.?

danyal14 started a new conversation Running Just VUEJS Application Alongwith Blade

Hi Guys,

I am trying to find best solution to use Laravel + VueJS.

Idea is to use blade + VUE +LUMEN API.

That's mean I might use Laravel just for VUEJS as web entrypoint, my point is that using Laravel to only serve VUEJS website that will consume Lumen API, is kind of wastage of Laravel framework.

In my case, I will be only using Laravel web routes, controllers & blade. Where each controller will serve template with blade view + vuejs components.

What do you think?

09 Jan
1 week ago

danyal14 left a reply on Laravel HTTP Tests

@D9705996 - But of course without Laravel.

danyal14 left a reply on Laravel HTTP Tests

@D9705996 - Yes, this is what is did, thanks for the feed back.

{
    "require": {
        "phpunit/phpunit": "^7.5",
        "guzzlehttp/guzzle": "^6.3",
        "symfony/dom-crawler": "^4.2",
        "symfony/css-selector": "^4.2"
    },
    "autoload-dev": {
        "psr-4": {
            "DANYALDK\Tester\Tests\": "tests/"
        }
    },
    "scripts": {
        "test": "./vendor/bin/phpunit --verbose"
    }
}
08 Jan
2 weeks ago
07 Jan
2 weeks ago

danyal14 started a new conversation VUEJS & Laravel App

Hi Guys,

I am planning to update our old news website build in php. My plan is to use Laravel or Lumen for API & VUEJS for SPA.

I have some technical questions.

  1. Backend expected tasks.
    • Import data from providers, cronjobs
    • API's
    • Websockets to update data LIVE news feed.
      • Session or session less auth
    • Caching with cloudfront
  2. UI
    • VUEJS should I user Laravel blade + VueJS or VueJs as standalone app.

And how does Googleanalytics treats VueJs routes?

Thanks in advance.

danyal14 left a reply on Laravel HTTP Tests

@D9705996 - Hi @d9705996

URL::forceRootUrl "Can't find declaration to go to", didn't work.

Composer

 "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.7.*",
        "laravel/tinker": "^1.0"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.0"
    },
03 Jan
2 weeks ago

danyal14 started a new conversation Laravel HTTP Tests

Hi Guys,

I am trying to write HTTP tests in Laravel by targeting external urls. Looks like Laravel default target APP_URL as default.

Suppose

APP_URL=http://localhost

And I want to test my website that is not part of this application

public function testMobileCaching()
    {
        $response = $this->get('http://www.danyal.dk');
        $response->assertStatus(200);
    }


How to do that and even it's possible?

16 Dec
1 month ago

danyal14 left a reply on Laravel Telescope Records Nothing On Production

@D9705996 - Correct, I over looked it, thanks :)

danyal14 started a new conversation Laravel Telescope Records Nothing On Production

I successfully configured and run locally with no issues. But as I install Laravel Telescope on production env it's record noting but Exceptions.

Any idea why or it's default behaviour?

danyal14 left a reply on Class 'Collective\Html\HtmlServiceProvider' Not Found

@SERGIU17 - I have do that already HtmlServiceProvider is removed from provider, this could be a cache issue on production.

Because when I clone this project as new and run composer install, this error doesn't appear.

And when I try to run php artisan cache:clear, I get same error.

Any other way of cleaning cache like removing Storage folder or something like it?

danyal14 started a new conversation Class 'Collective\Html\HtmlServiceProvider' Not Found

I removed this package, since I am not using it i my Laravel 5.7 app "laravelcollective/html": "5.1.*"

Now composer install on production complains

Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

In ProviderRepository.php line 208:

  Class 'Collective\Html\HtmlServiceProvider' not found

11 Dec
1 month ago

danyal14 left a reply on Docker Series

Would anyone like to share Dockerfile Lumen?

09 Dec
1 month ago

danyal14 left a reply on Laravel Gate, Policy And Supper Admin

I figured it out, Gate::before returns true & false based on $user->hasRole. Where it should only return true if user is super admin otherwise bypass.

        Gate::before(function ($user) {
            if ($user->hasRole(Authentication::ROLE_SUPER_ADMINISTRATOR)) {
                return true;
            }
        });

danyal14 started a new conversation Laravel Gate, Policy And Supper Admin

Hi Guys, I am implementing Gate in my application, where I have following setup.

Users
Roles

Route & policy middleware

Route::get('/expenses/{transaction}', '[email protected]')
        ->name('app.expenses.edit')->middleware('can:update,transaction');

Policy

class TransactionPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can update the transaction.
     *
     * @param  \App\User  $user
     * @param  \App\Transaction  $transaction
     * @return mixed
     */
    public function update(User $user, Transaction $transaction)
    {
        return $transaction->user_id == $user->id;
    }
}

Til here everything works fine, mean if any other user access the transaction of other user Laravel throws 403.

But as I add before gate and when gate::before returns true SuperAdmin gets access to the transaction but when gate:before returns false, that's me its not a SuperAdmin but a registered user, Laravel throws 403 instead of going to TransactionPolicy.

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Transaction' => 'App\Policies\TransactionPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @param Gate $gate
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::before(function ($user) {
            return $user->hasRole(Authentication::ROLE_SUPER_ADMINISTRATOR);
                
        });
    }
}

02 Dec
1 month ago

danyal14 started a new conversation Upgrade Larave 5.6 To 5.7

Hello guys,

Recently I upgraded my hobby project from 5.6 to 5.7, everything work like a charm.

Though, I would like to know the best way up adding missing middlewares to my upgraded project.

For example:

My upgraded project from 5.6 to 5.7 has following middlewares in Kernel.php

    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];

Since when I create new 5.7 project from scratch that comes with following middlewares:

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];

I assume, that I have to update my app Kernel manually those are missing. Or there is automate process to add those to existing Kernel and app/HTTP/Middleware folder?

Regards Danyal

25 Nov
1 month ago

danyal14 left a reply on Laravel Blade Form

@LUNAH - That's make sense, I was trying to find a reason laravelcollective/html was used in old project of Laravel 5.4. And since Laravel 5.7 done's have this anymore in framework, I decided to refactor it.

And seek the valid opinion, thanks for the detailed answer.

danyal14 started a new conversation Laravel Blade Form

Hi Guys,

I would like to ask, what is the major difference using these 2 method of defining form in blade?

    {!! Form::model(\App\Model::class, ['route' => ['app.transaction.update', $transaction->id], 'method' => 'put', 'classs' => 'form', 'novalidate' => 'novalidate']) !!}
    {!! Form::close() !!}

    <form method="POST" action="/profile">
    </form>

danyal14 started a new conversation Laravel Github & Licensing

Hi Guys,

I need help figuring out which license should I choose for private and public repos?

23 Nov
1 month ago

danyal14 left a reply on PHPunit Testing

@D9705996 - Worked like a charm :) Thanks

21 Nov
2 months ago

danyal14 left a reply on Undefined Variable: User_id

@aurawindsurfing is right or you can do as following.

    public function create($user_id)
    {
        return view('contacts.create'', ['user_id' => $user_id]);

    }

danyal14 left a reply on How To Check If Values Are Repeated From Controller Laravel

@abdulbazith you didn't share a code, how you save and attach the selected educations from UI to database.

But if you saving multiple selected education as JSON or serialized array in database, do the following before updating user's education.

Suppose in controller

$user_selected_educations = ["CA","Computers and Management", "Sculpture"];
$user_stored_educations = ["CA","Pursuing"];

$collection = collect($user_selected_educations, $user_stored_educations);

$collection should be unique and now you can update user education.

tinker output

php artisan tinker
Psy Shell v0.9.9 (PHP 7.2.3-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> $user_selected_educations = ["CA","Computers and Management", "Sculpture"];
=> [
     "CA",
     "Computers and Management",
     "Sculpture",
   ]
>>> $user_stored_educations = ["CA","Pursuing"];
=> [
     "CA",
     "Pursuing",
   ]
>>> $collection = collect($user_selected_educations, $user_stored_educations);
=> Illuminate\Support\Collection {#2948
     all: [
       "CA",
       "Computers and Management",
       "Sculpture",
     ],
   }
>>> 

danyal14 left a reply on PHPunit Testing

Agree, but using sqlite in phpunit.xml make no effect on database migrations & seeding for --env="testing"

even though I specify DB_CONNECTION & DB_DATABASE in phpunit.xml, how does artisan know which database target?

20 Nov
2 months ago

danyal14 left a reply on Side Projects???

@sunny In order to understand Laravel, I starter expense manager for my personal use and now it's live, yet not promoting think missing some stuff

danyal14 left a reply on PHPunit Testing

yes, this way phpunit test works only if test database has tables migrated, but I need to migrate and seed test data to api_test. when using following commands. original database is being target.

artisan migrate --env="testing"
artisan db:seed --env="testing"

danyal14 started a new conversation PHPunit Testing

I writing phpunit tests for Lumen API, and for some reason framework doesn't using .env.testing configuration file for the test database.

As from Laravel 5.5 - Laravel 5.7, I used to create .env.testing file to run test seeders and phpunit tests.

.env

APP_ENV=local
APP_DEBUG=true
APP_KEY=appkey
APP_TIMEZONE=UTC

LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=api
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
QUEUE_DRIVER=sync

.env.testing

APP_ENV=testing
APP_DEBUG=true
APP_KEY=appkey
APP_TIMEZONE=UTC

LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=api_test
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
QUEUE_DRIVER=sync

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/app.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory suffix="Test.php">./tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>
</phpunit>


danyal14 left a reply on How Can I Achieve This?

@shashi_verma

You need to define GET & POST for the endpoint, and this can be achieve in two ways.

// 1. Using closure

Route::get('/signup', function() { }); 
Route::post('/signup', function() { });

These routes are using closure, but in case you are using controller then it's a different case.

// 1. Using controller

$router->get('/signup', '[email protected]');
$router->get('/signup', '[email protected]');

danyal14 left a reply on Authentication Middleware & Custom Responses

@MARTINBEAN - Of course, I am off today :) that's correct request is not going any further since middleware is checking api_token.

Thanks

danyal14 left a reply on Authentication Middleware & Custom Responses

@MARTINBEAN - suppose I am trying to hit auth/verify with invalid api_token, Authenticate middleware with react and respond with "Unauthorized", and same goes with logout and profile endpoint.

This is when I want to respond with different messages.

danyal14 left a reply on Validation With Rules::exists

@TAKDW - @takdw Thanks for the reply, it works.

reason I am using Validator::make() to capture validation errors in variable and then to wrap in response as I want.

Like $validator = Validator::make() and response

{
    "status": "fail",
    "message": "Validation errors.",
    "errors": {
        "username": [
            "The selected username is invalid."
        ],
        "old_password": [
            "The old password field is required."
        ]
    }
}

And request()->validate() & response

{
    "errors": {
        "username": [
            "The selected username is invalid."
        ],
        "old_password": [
            "The old password field is required."
        ]
    }
}

Just to make response as unified as possible.

danyal14 started a new conversation Validation With Rules::exists

When validating post data, I would like to use Laravel validation to check if email exists in users table along with other validations, questions is can Rule::exists() can be used to fulfill this purpose?

        $validator = Validator::make($request->all(), [
            'username' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::exists('users')->where(function ($query, $request) {
                    $query->where('email', $request->usename);
                })
            ], 'email',
            'password' => 'required|string|min:6',
        ]);