usama.ashraf

usama.ashraf

Lahore

Hire Me

Member Since 2 Years Ago

Experience Points 33,720
Experience
Level
Lessons Completed 181
Lessons
Completed
Best Reply Awards 41
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 Nov
2 years ago

usama.ashraf left a reply on Select Models That More That 24 Hours Have Passed Since Their Creation In Laravel

$question = Question::where('created_at', '<', 'timestampadd(hour, -24, now())');
17 Nov
2 years ago

usama.ashraf left a reply on REST APIs - JSON Strings Vs Arrays

@mass6 not really. json_decode($request->all());would retrieve an array with a single key; users. And the value against it would be a JSON string, which will have to be decoded.

The difference is between sending a JSON string against a POST body parameter or sending the entire body as a JSON object (with a application/json content-type header, probably what you're referring to as the "defacto standard").

usama.ashraf left a reply on DB Versioning?

Not sure exactly what you mean. But the whole purpose of migrations is DB versioning.

usama.ashraf started a new conversation REST APIs - JSON Strings Vs Arrays

Hi there,

I came across two ways to accept input on a POST endpoint for a REST API that I'm building.

  1. Send data as a single JSON string like:
'users' => '[ {"name": "xyz"}, {"name": "abc"}, {"name": "def", "posts": [1, 2, 3, 4]} ]'
  1. Send data in a proper array, like HTML forms would:
'users[0]['name']'  => 'xyz',
'users[1]['name']'   => 'abc',
'users[2]['name']'  => 'def',
'users[2]['posts']'  => [1, 2, 3, 4],

Number 1 is harder to validate on the server-side.

Can any one please list some of the benefits and drawbacks of each approach? Which is the prefered standard?

Thanks !

16 Nov
2 years ago

usama.ashraf left a reply on Problem With Showing 'name' From Foreign Table Instead Of 'id'

$cars is a collection. You're looking for $car->colors.

usama.ashraf left a reply on Basic Understanding Of Gulp, Elixir, Webpack...

  • npm is like composer for Node.

  • Elixir is just a wrapper around gulp i.e. it make gulp easier to use.

  • Gulp is what we call an asset management tool/task runner etc. It's used for among other things, minifying CSS/JS, compiling coffeescript/ES6 etc. to vanilla javascript, compiling SASS/LESS into CSS.

  • Webpackis an alternative to gulp.

  • 'Webpack', gulp etc can actually be used together by employing other npm modules like gulp-webpack.

08 Nov
2 years ago

usama.ashraf left a reply on Laravel Or Lumen?

Lumen is an API framework (REST) built on top of Laravel. And it's good.

So definitely what you want to accomplish.

03 Nov
2 years ago

usama.ashraf left a reply on Storing Array Data In Laravel

I'd rather not run multiple queries within a loop.

$arr = [];

for ($i = 0; $i < count($images); $i++) {
    array_push($arr, ['picture_id' =>$images[$i], 'picture_owner' => auth()->id]);
}

Image:insert($arr);
23 Oct
2 years ago

usama.ashraf started a new conversation Using Redis And Pusher Simultaneously

Hi there

I'd appreciate if any one could point to an elegant solution allowing for both Redis and Pusher to be used as broadcast drivers at the same time, on Laravel 5.2.

I have existing implementations for a notification system (Pusher) and a chat application (Redis), both occupying one channel each.

Thanks.

18 Oct
2 years ago

usama.ashraf left a reply on Forcing A Unique Rule To Ignore A Given ID:

public function rules()
    {
        return [
            'lead_code' => 'required|min:3|unique:clients,lead_code, ' . $this->route('id'),                         
            //'lead_code' => 'required|min:3',
            'mobile' => 'required|phone:AUTO,GB,mobile',

        ];
    }
17 Oct
2 years ago

usama.ashraf left a reply on Forcing A Unique Rule To Ignore A Given ID:

public function rules()
    {
        return [
            'lead_code' => 'required|min:3|unique:clients,lead_code, ' . $this->nameOfRequestParameterThatHasTheID,                         
            //'lead_code' => 'required|min:3',
            'mobile' => 'required|phone:AUTO,GB,mobile',

        ];
    }
13 Oct
2 years ago

usama.ashraf left a reply on Can Not Run Through A Nested Loop

Try this:

<ul>
            <li v-for="subjects in questions">
                <li v-for="question in $parent.$subjects">
                    @{{ question }}
                </li>
            </li>
</ul>
10 Oct
2 years ago

usama.ashraf left a reply on Difference Between Env() And Config::get()

env() tries to get the value directly from the .env file. Config::get() retrieves whatever the configuration files return, which may or may not be what is in the .env

05 Oct
2 years ago

usama.ashraf left a reply on What Are The Best Practices In Creating Multiple User Roles/different Fields And Permissions?

Have two separate roles and permissions tables.

  • users
  • roles
  • permissions

Pivot tables:

  • role_user
  • permission_role

A user can have many roles. And a role can be associated with many permissions.

20 Sep
2 years ago

usama.ashraf left a reply on Forgive Me, Once Again..

php artisan serve underneath uses the default php server that comes with the installation. It has nothing to do with Nginx or Apache and is used for/in the testing and/or development phase of an application since it's lightweight and obviously very easy to use.

Do this:

  • php artisan serve --port=9000
  • Go to localhost:9000

And you're done.

18 Sep
2 years ago

usama.ashraf left a reply on HasManyThrough Problems With SoftDeletes

Try this:

return $this->hasManyThrough(Payment::class, Operation::class)->withTrashed();

Or, you could just use the query builder with joins.

16 Sep
2 years ago

usama.ashraf left a reply on What Is Diffrence Between Thease Imports And Requires

The import syntax is new in ES6 and helps to modularize your application: https://laracasts.com/series/es6-cliffsnotes/episodes/10

But for the most part, the intent of both is the same. One important thing is that on some environments you'll have to convert the ES6 to ES5 if they don't support it.

12 Sep
2 years ago

usama.ashraf left a reply on Process JSON Data From User Auth MySQL

Well then may be you should state your question more clearly.

usama.ashraf left a reply on Process JSON Data From User Auth MySQL

I'm sorry if I'm not understanding you correctly, but I think this what you want:

Session::put('userEmail', Auth::user()->email);
// Or this (unnecessary): 
// $user = DB::table('users')->where('email', Auth::user()->email)->first();
// Session::put('userEmail', $user->email);

By the way, that's not JSON, just an Eloquent model/object.

I suggest reading up more on PHP (and javascript apparently) before diving into Laravel.

usama.ashraf left a reply on Can I Modify ResetsPasswords?

Override the required methods in the PasswordController. As a general rule, never edit the core files.

11 Sep
2 years ago

usama.ashraf left a reply on Composer Not Installing Latest Version

That's a common problem. One version is what the server uses and the other is of the CLI. It is unnecessarily complex.

Try this first:

brew install php70

If php -v still shows 5.5, you can look up how to get php 7 on a MAC.

usama.ashraf left a reply on Composer Not Installing Latest Version

Ok. Your PHP version is probably < 5.6.4.

Update your PHP first.

usama.ashraf left a reply on Composer Not Installing Latest Version

Not unless you have a composer.json file already. Please follow the steps I outlined. If they don't work, let me know.

Or try this:

  • Create a new, empty directory for your project.
  • Run this in the new directory: composer create-project --prefer-dist laravel/laravel your_project_name

usama.ashraf left a reply on Composer Not Installing Latest Version

"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.3.*"
    },

And delete the composer.lock file at the root of the project, if it's there.

usama.ashraf left a reply on Composer Not Installing Latest Version

Just change it to 5.3.*. And if you're starting out, make sure there's no composer.lock file at the project root.

usama.ashraf left a reply on Foreign Key Constraints Not Applied On Self Referencing Table

Try this:

public function up()
{
        Schema::create('top_categories', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->string('categoryname')->unique();
            $table->string('parent')->nullable();
        $table->foreign('parent')->references('categoryname')->on('top_categories')->onUpdate('cascade')->onDelete('restrict'); 
            $table->timestamps();
       });
}
10 Sep
2 years ago

usama.ashraf left a reply on Store User Session In Redis

On login, the user will be provided a JWT that will have to be sent to the node server. Your node server could then decode the JWT to retrieve the user. Or it'll fail in case of an invalid token.

usama.ashraf left a reply on Store User Session In Redis

Ok. Your problem might be related to cookies/sessions being encrypted.

But a better approach would be to use JWT (JSON Web Tokens). Look them up.

usama.ashraf left a reply on Store User Session In Redis

Just set this in your .env SESSION_DRIVER=redis and you can use sessions just like you would otherwise. And you don't have to explicitly set the user login session. Laravel takes care of that.

usama.ashraf left a reply on Store User Session In Redis

Why not just set your session driver to redis rather than explicitly setting it?

09 Sep
2 years ago

usama.ashraf started a new conversation Any Argument For Extremely Lengthy Stored Procedures?

I've recently come across the code-base and DB for a VOIP application. It's like a murder scene.

The app has countless (many hundreds of) MySQL stored procedures that go up to 900 lines long ! It was written in 2006. The stored procedures hold most of the business logic (practically all of it) and the code is very much unreadable, poorly structured.

One of the longer SPs that sifts through a lot of data across 10 tables (max. 5 GB) is called almost 15 times a second depending on the traffic.

I was talking to the senior engineer who managed the project back then. He, to my surprise, defended the application's design very ferociously arguing that a data-intensive, read-heavy application demands such long stored procedures because of performance considerations. He was willing to do the same today, even with everything that is available now.

3 questions:

  • Does any one with a database background think there's a better way? Like using in-memory stores for frequently-accessed data ? Or caching?

  • Should good design still be important, and the business logic be shifted to the code?

  • What kind of a situation would justify this design?

Would seriously appreciate some well-thought opinions. Thank you.

usama.ashraf left a reply on Organizing Routes

Have multiple route files. You can create a new one inside Http and add this to your app/Providers/RouteServiceProvider.php's mapWebRoutes method.

$router->group([
      'namespace' => 'App\Http\Controllers',  'middleware' => 'web',
      ], function ($router) {
            require app_path('Http/new_routes_file.php');
       // require files as per your needs.
 });

Each routes file should ideally correspond to a distinct module of the application.

usama.ashraf left a reply on Need Help Writing ES6 Code To Use In Laravel Project

Use this instead: import Polygon from './Polygon'

08 Sep
2 years ago

usama.ashraf left a reply on Redirect Request PRIOR To Login

This is an artisan command not a shell command. So it'll run at the root of any Laravel project no matter where it's deployed.

usama.ashraf left a reply on Redirect Request PRIOR To Login

You don't have to that manually. Just do php artisan down to shut your app. And php artisan up for restoring it.

When the app is down (in maintenance mode), it renders views/errors/503.blade.php. Just customize the message it displays on that page.

usama.ashraf left a reply on L5.3 Api Routes Type Hinting Doesn't Work

Please show your routes file. This could be a case of the wrong route being invoked.

usama.ashraf left a reply on Single Application Multiple Modules, Best Way To Control It And Version It

Use one repository. You could opt to have separate branches for each module and then may be more branches for sub-modules (sub-branches). Keep a separate dev branch and periodically merge work from the other branches into dev.

When enough work has been done that is stable, merge dev into master.

I'd also recommend studying version control more.

usama.ashraf left a reply on Can Laravel Handle Big Data Intensive Application And Which Database To Use MYSQL Or NOSQL

That's not really a Laravel or PHP question.

"And also want to know whether to go with traditional MYSQL or New NoSQL Databases"

NoSQL should be considered if the data is unstructured. The volume is not what matters the most.

MySQL can handle fairly large amounts of data. Other relational databases too, e.g. MSSQL works even better.

usama.ashraf left a reply on How To Place Vue Variable Inside A Laravel Bracket

I suggest that you make a custom attribute on your Course model. Call it course_url and then just do this:

<a href="@{{ course.course_url }}">@{{ course.title }}</a>

There can be other ways too. But this works well.

usama.ashraf left a reply on How To Place Vue Variable Inside A Laravel Bracket

That's not possible. The route function call is server-side code. course.id is rendered at the client-side.

usama.ashraf left a reply on Setters Does Not Work For Me

But if you're not assigning any value to the project_id explicitly, this won't be called.

In that case, try this in your model:

public function __construct(array $attributes = array())
{
    $this->attributes['project_id'] = Session::get('proj_id');
    parent::__construct($attributes);
}

usama.ashraf left a reply on Setters Does Not Work For Me

Use this signature: setProjectIdAttribute($value)

07 Sep
2 years ago

usama.ashraf left a reply on Retweet/Reblog Setup

I'd suggest a different design. Keep the reblogs as entries in the post table, with a nullable, self-referencing parent_id field pointing to the original post.

This will also give you the leverage to somehow may be customize a tweeted blog yet retain the 'qualities' of a post.

usama.ashraf left a reply on Registration Routes

Nothing wrong with tweaking the trait.

You could also this in the router:

Route::get('/register', function() { return redirect(url('/register/applicant')); })

usama.ashraf left a reply on Choosing The Controller Method For API Endpoints?

Well you're getting a resource(s) essentially, so index or show if you're following conventions.

I think @martinbean's answer suffices.

usama.ashraf left a reply on Choosing The Controller Method For API Endpoints?

  1. Don't create a single method.

  2. /seller/id/products should mean "get all products associated with the seller having this id". With this, this request should be handled in a SellerController. The same for /categories/id/products.

usama.ashraf started a new conversation Node.js - Parse Websites Using Different Control Flow Strategies

Recently I attempted a coding test in node js where I was supposed to parse a list of websites provided by the user, and display the content of the title tags on each page. Here is the problem statement: https://gist.github.com/caremerge/b71716d403d62542a7e5

I was supposed to do this 4 times; using raw node.js, using async.js, using promises and then using streams.

I failed the test, to my great surprise. Here's my solution: https://github.com/UsamaAshraf/careaxiom-test-solution

I would seriously appreciate any one who could spend half an hour or less to evaluate my code and see what I did wrong. Thanks !

usama.ashraf left a reply on Store Logic In Commands Vs Controllers

No. Read up on Laravel Jobs. They can be used without the cron.