usama.ashraf

Hire Me

Experience

33,670

41 Best Reply Awards

  • Member Since 2 Years Ago
  • 181 Lessons Completed
  • 8 Favorites

22nd November, 2016

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

$question = Question::where('created_at', '<', 'timestampadd(hour, -24, now())');

18th November, 2016

17th November, 2016

usama.ashraf left a reply on REST APIs - JSON Strings Vs Arrays • 1 year ago

@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? • 1 year ago

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 • 1 year ago

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 !

16th November, 2016

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

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

usama.ashraf left a reply on Basic Understanding Of Gulp, Elixir, Webpack... • 1 year ago

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

8th November, 2016

usama.ashraf left a reply on Laravel Or Lumen? • 1 year ago

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

So definitely what you want to accomplish.

3rd November, 2016

usama.ashraf left a reply on Storing Array Data In Laravel • 1 year ago

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

23rd October, 2016

usama.ashraf started a new conversation Using Redis And Pusher Simultaneously • 1 year ago

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.

18th October, 2016

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

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',

        ];
    }

17th October, 2016

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

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',

        ];
    }

13th October, 2016

usama.ashraf left a reply on Can Not Run Through A Nested Loop • 1 year ago

Try this:

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

10th October, 2016

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

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

5th October, 2016

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

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.

20th September, 2016

usama.ashraf left a reply on Forgive Me, Once Again.. • 1 year ago

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.

18th September, 2016

usama.ashraf left a reply on HasManyThrough Problems With SoftDeletes • 1 year ago

Try this:

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

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

16th September, 2016

usama.ashraf left a reply on What Is Diffrence Between Thease Imports And Requires • 1 year ago

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.

12th September, 2016

usama.ashraf left a reply on Process JSON Data From User Auth MySQL • 1 year ago

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

usama.ashraf left a reply on Process JSON Data From User Auth MySQL • 1 year ago

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? • 1 year ago

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

11th September, 2016

usama.ashraf left a reply on Composer Not Installing Latest Version • 1 year ago

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 • 1 year ago

Ok. Your PHP version is probably < 5.6.4.

Update your PHP first.

usama.ashraf left a reply on Composer Not Installing Latest Version • 1 year ago

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 • 1 year ago

"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 • 1 year ago

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 • 1 year ago

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();
       });
}

10th September, 2016

usama.ashraf left a reply on Store User Session In Redis • 1 year ago

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 • 1 year ago

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 • 1 year ago

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 • 1 year ago

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

9th September, 2016

usama.ashraf started a new conversation Any Argument For Extremely Lengthy Stored Procedures? • 1 year ago

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 • 1 year ago

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 • 1 year ago

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

8th September, 2016

usama.ashraf left a reply on Redirect Request PRIOR To Login • 1 year ago

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 • 1 year ago

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 • 1 year ago

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 • 1 year ago

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 • 1 year ago

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 • 1 year ago

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 • 1 year ago

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 • 1 year ago

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 • 1 year ago

Use this signature: setProjectIdAttribute($value)

7th September, 2016

usama.ashraf left a reply on Retweet/Reblog Setup • 1 year ago

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 • 1 year ago

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? • 1 year ago

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 year ago

  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 • 1 year ago

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 • 1 year ago

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

Edit Your Profile
Update

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