Buy your loved one the ultimate gift. Lifetime gift certificates are $100 off.

kfirba

Experience

211,115

118 Best Reply Awards

  • Member Since 3 Years Ago
  • 1194 Lessons Completed
  • 20 Favorites

13th November, 2017

kfirba left a reply on Processing Chunked Uploads Help Please • 1 month ago

@NotAGoodCoder glad it helped you :).

kfirba left a reply on Processing Chunked Uploads Help Please • 1 month ago

@NotAGoodCoder hey!

I think that instead of “reinventing the wheel” you can use a native OS api such as the he command. The he command will read the files in small chunks and append them together. It will leave a very small memory footprint.

The command may look like:

cat file1 file2 file3 file4 > fullFilze

Just make sure you use the absolute file path so the command can find the files.

You can use Symfiny’s `Proce class to execute the command above.

Good luck!

4th November, 2017

kfirba left a reply on User Specified Download Link • 1 month ago

@sadiss There is a public folder in your application. Everything in that folder is basically user-accessible content. Say you have images/some-image.jpg file in the public folder, anyone could access that image by visiting: example.com/images/some-image.jpg.

As you noticed, the storage folder is not inside the public folder, hence no one should be able to access it directly. But sometimes we do want to make some content in that folder user-accessible. To do so, we create a symlink. What does that mean? A symlink is a nickname for any file that contains a reference to another file or directory. So say I create a symlink from public/some-symlink-name to storage/public when someone visits example.com/some-symlink-name, he will be presented with the contents of the storage/public directory. If we have a file in the path storage/public/my-image.jpg and symlink to that folder, the file will be accessible under example.com/some-symlink-name/my-image.jpg.

To create such symlink, you may do something like:

ln -s path/to/application/storage/public path/to/application/public/my-symlink-name

Laravel has a command: php artisan storage:link that creates a symlink automatically between your storage/public folder and the public/storage folders.

Well basically, if you don't know if you have a symlink, you probably don't have one. Otherwise, you can simply check that by going into your public directory and type: ls -la and see if the file type is l (symlink) instead of d (directory) or - (file).

kfirba left a reply on User Specified Download Link • 1 month ago

@sadiss As long as you don't symlink that folder to the public folder, then yea, no one can access that.

kfirba left a reply on User Specified Download Link • 1 month ago

@sadiss The storage folder is an internal storage. Unless you symlink it to somewhere in your public directory, no one can access that folder directly. There is a public directory in the storage folder that you can symlink but if your files are directly under the storage path, no one should be able to access them directly.

kfirba left a reply on User Specified Download Link • 1 month ago

@sadiss Hey.

You can make the request go through your app and determine whether the request is valid or not. What I would do is expose an endpoint to download files, maybe something like:

example.com/downloads/{hash}

Now you are going to associate any file in your database with some kind of a hash. You would then create a controller to respond to that URI and determine whether the user should have access to the file or not:

public function show($hash)
{
    // Perform the authorization here
    abort_unless(optional(auth()->user())->canDownload($hash), 404);
    
    return response()->file($pathToFile);
}

3rd November, 2017

kfirba left a reply on Encrypt Frontend Api Post Data & Decrypt Laravel Backend • 1 month ago

@makapaka Hey.

Symmetric encryption (what Laravel offers out of the box) uses a single key to encrypt and decrypt the data. In order to encrypt something on the frontend and be able to decrypt it at the backend, both the frontend and the backend need to share the same key. Okay, that's not hard to do, however, when you have your key in your frontend, anyone with basic skills can look for that key through your source code which makes it really useless to encrypt any data using that key.

If you wanna go down that route, you will need to use asymmetric cryptography - Public-Private key encryption where your frontend encrypts your data with a public key and your backend use the private key to decrypt the data.

Simply generate a key pair on your machine/server and use PHP's openssl functions.

28th October, 2017

kfirba left a reply on Contact Form Validation Error • 1 month ago

@kavi Can you format your code so it is actually readable? Use a triple backtick (```) before and after the code block.

kfirba left a reply on Preventing An Event Being Queued Twice • 1 month ago

test

alert('works');

kfirba left a reply on Testing Uploaded File • 1 month ago

Test

alert('works');

kfirba left a reply on Run A Custom Artisan Command In Browser And Display Progress With Progress Bar • 1 month ago

@khizer1030 Hey.

The only way I can think of to do this is to have an endpoint which triggers the command you want and return a channel which you can listen on your frontend for progress. Your command then should broadcast an event to let the frontend know what is the current progress of the command.

Basically, it will take the shape of:

  1. Ping some backend link: /scrape
  2. The server responds with a channel ID: scrapingChannelId:10
  3. You listen to that channel on your frontend. You can use Laravel echo or just vanilla socket.io
  4. Your command will broadcast an event every X seconds or when on any other condition
  5. Your frontend listens to that event and updates some kind of progress bar.

Good luck!

27th October, 2017

kfirba left a reply on How To Retrieve Data In Array Object? • 1 month ago

@hemal I'm really confused as to what you are trying to achieve...

Maybe you mean something like:

public function index($slug)
{
    return Post::whereHas('user', function($query) use ($slug) {
        $query->where('slug', $slug);
    })->get();
}

kfirba left a reply on How To Retrieve Data In Array Object? • 1 month ago

@hemal Change your query:

public function index($slug)
{
    return Post::where('slug', $slug)->get();
}

26th October, 2017

kfirba left a reply on Which User Deleted What? • 1 month ago

@imposition Yea? You will need to be more specific in order for us to help you

21st October, 2017

kfirba left a reply on Eloquent Vs Query Builder, Why? • 1 month ago

@Boubou I'm not doing a regular insert, I'm doing an insert select query. Basically, it will take a table structure and insert it. You can read more about it here: https://dev.mysql.com/doc/refman/5.7/en/insert-select.html

kfirba left a reply on Eloquent Vs Query Builder, Why? • 1 month ago

@Boubou well, it's gonna be a bit vague, but, it depends.

I try to keep everything super simple. If it's some simple query, I will definitely do that in the controller itself. If I need to some a bit more complex query I might offload that to a method on the model itself and if it is a complex query, I might extract a query object to do that.

For example, I have built some kind of an online shopping site for a customer, and for that very specific project, the user's cart had to be saved between sessions and never be deleted unless the user specifically emptied the cart or made an order. In order to achieve that, the cart is stored in the database for the user. Because the cart is stored in the database, its structure is very similar to what an order may look like. To me, it did not make sense to run a query for each cart item and "move" it to the orders table which is the easiest solution if you were using Eloquent to do that. Instead, I've written the following query:

DB::insert(
            "insert into order_product(order_id, product_id, quantity, price, created_at, updated_at)
            select '{$order->id}' as order_id, c.product_id, c.quantity, p.price, '{$order->created_at}' as created_at, '{$order->updated_at}' as updated_at
            from cart as c
            join price_list_product as p on p.product_id = c.product_id and p.price_list_id = '{$user->price_list_id}'
            where c.user_id={$user->id}"
        );

The query is not overly complicated but it felt a little bit disgusting keeping that query the controller so I simply extracted that query to a method on the model.

kfirba left a reply on Eloquent Vs Query Builder, Why? • 1 month ago

@Boubou Hey

Well, I find myself using both on the same project. I roll with Eloquent by default since it makes the code much more expressive than using the query builder. However, there are many cases where I find myself needing to write some custom query to achieve something (for example, using the on duplicate update feature of MySQL) that would result in many more queries if I stuck to Eloquent.

20th October, 2017

kfirba left a reply on Order By Short To Long • 1 month ago

@minions Hey.

You can just add an orderByRaw clause:

Book::where('title', 'like', '%' . implode('%', $keyword) . '%')
    ->take(10)
    ->orderByRaw('char_length(title) asc')
    ->get();

10th October, 2017

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 2 months ago

@splendidkeen Glad I could help :)

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 2 months ago

@splendidkeen If I understand correctly, in your navigation code, you check for an authenticated partner and if there is one, you try to add some navigation links.

I think that within that context, the Auth::user() call is actually returning a Business model. Can you try changing this line:

{{  Auth::user()->business->getCompanyName() }}

To:

{{  Auth::user()->getCompanyName() }}

If it does not work, can you post here what does Auth::user() returns? You should be able to figure this out by calling:

get_class(Auth::user())

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 2 months ago

@splendidkeen I'm not sure what you are trying to do but calling Auth::user() will return the currently authenticated user for the given guard or the default guard defined in your config file.

I'm assuming that there is a Business model that has a user_id column.

On your User model (or any other model you use for authentication), you should have a business relationship:

class User extends Authenticatable
{
    // ...
    
    public function business()
    {
        return $this->hasOne(Business::class); 
    }
}

Now when you access the property business on Auth::user(), Laravel will detect that there is a business relationship defined and will automatically fetch that relationship for you.

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 2 months ago

@splendidkeen Hey.

Well, you can indeed check if the user is authenticated. However, it seems like your issue is not with the user not being authenticated but with your authenticated user not being associated with a business.

Since your error message indicate that you call getCompanyName() method on a null, it means that Auth::user()->business is returning null which means that the authenticated user does not have a business relationship.

Also, if you are using Laravel 5.5, you can use the optional() method which will act as a null object pattern:

{{ optional(Auth::user()->business)->getCompanyName() }}

You can read more about the optional() method here: https://laravel.com/docs/5.5/helpers#method-optional

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit In your createInvoice() method you have this line of code:

$data['details'] = '';

Which means you initialize the details key within the $data array to an empty string. Then somewhere else in that method, you call:

$data['details'][] = $details;

And you get your error. The reason for the error is that what you are calling the shorthand array_push() on a string. Usually in PHP you can do:

// initialize an array
$array = [];
// push items to the array
$array[] = 'Item A';
$array[] = 'Item B';
// Now the array looks something like:
// -> ["Item A", "Item B"]

// The above code is a shorthand for:
$array = [];
array_push($array, 'Item A');
array_push($array, 'Item B');
// -> ["Item A", "Item B"]

What happens in your code that you try to use the $data['details'] value as if it was an array when it is actually a string (remember the $data['details'] = ''; line of code).

What you need to do is change this line of code:

$data['details'] = '';

To:

$data['details'] = [];

Also, it is better if you try to debug your code by yourself. You will learn a lot. Try going through the stack trace whenever you have an error. I know it looks long and intimidating but once you get used to it, it is a breeze to do so :) Also, don't forget the Google is any developer's best friend!

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit No, that's too much information. I just need to know what is the code at line 275 and in which functions it exists within

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 2 months ago

@eDesignary Well, I'm not sure why it's happening.

Can you try running the query manually from PHP using the raw PDO object?

You can get the PDO object like so:

DB::connection()->getPdo();

If you don't remember how to interact with PDO directly, check out the docs for PDO's statements

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit I'd suggest you learn how to read those stack traces for your own benefit.

Anyway, it seems like your issue is with some code in your Invoice model class at line 275. What does line 275 looks like? Paste the full method code which line 275 resides in.

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit try running the command in verbose mode:

php artisan invoices:generate -vvv

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit Show me the full stacktrace of the error. I need to see on which line this error occurs

9th October, 2017

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 2 months ago

@splendidkeen There is no business method on the Auth facade. Are you actually trying to do something like:

Auth::user()->business->getCompanyName();

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit

Look at your failed method. You are trying to pass the $exception object to the debug() method when it only accepts an array.

Change this line:

Log::debug('[Generate Invoice] Failure - ',$exception);

to:

Log::debug('[Generate Invoice] Failure - ', [$exception]);

Or just pass the $exception message:

Log::debug('[Generate Invoice] Failure - ', ['error' => $exception->getMessage()]);

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 2 months ago

@eDesignary When you view your database using the console or some other program, does the data seem to be valid? Does it show the proper date as you expect?

Also, try running the query manually against your database using the console or some other program and see what the returned data looks like.

I'm trying to see where exactly the data corruption is happening.

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 2 months ago

@eDesignary That's weird...

Does the data for the receipt_date seem to be valid on your database side?

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 2 months ago

@splendidkeen Hey

You called your variable company_name and not business:

->with('company_name', $business);

You should use it as follows:

{{ $company_name->getCompanyName() }}

Or just change the way you refer to your variable:

return view('partner.profile.index')->with('business', $business);

// or yet better (in my opinion):
return view('partner.profile.index', compact('business'));

kfirba left a reply on Split URL Like /intranet/Useful Resources/Test Folder/test 3/ • 2 months ago

@northplanet You can explode the string, remove the last item and implode it again:

$segments = explode('/', trim($url, '/'));
array_pop($segments);

return '/' . implode('/', $segments) . '/';

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit I can't see it. Try pasting it again

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 2 months ago

@eDesignary What is the scheme for the receipt_date?

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit I can't help you any further unless I see some code

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 2 months ago

@eDesignary Seems like it. It looks corrupted. What does this field should look like?

Anyway, try to exclude the receipt_date from the response and see if you get that error

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit I'm gonna need to see your code to help with that. Please share your job class here. Paste the code between triple backticks so it gets formatted nicely:

``` // code here ```

kfirba left a reply on Is It Possible To Get Title And Thumbnail Image From Youtube Video Using Laravel ? • 2 months ago

@wardaddy Sure. It shouldn't be complicated at all. Let me know if you need help.

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 2 months ago

@eDesignary I believe the source of this error message is when Laravel tries to convert the $receipts to JSON. What does the $receipts variable looks like? Can you try and post a dd() here?

Please ensure that your database driver is using some kind of utf8 encoding.

kfirba left a reply on Is It Possible To Get Title And Thumbnail Image From Youtube Video Using Laravel ? • 2 months ago

@wardaddy You can just use (Youtube Data API)[https://developers.google.com/youtube/v3/docs/videos].

It seems like someone has created a wrapper for Laravel: https://github.com/alaouy/Youtube

Good luck!

kfirba left a reply on Why I Can't Get All Details According To User From Database? • 2 months ago

@hemal You have user_id column on your profiles table right?

It seems you got your relationships mixed a bit. It should be:

User -> HasOne -> Profile
Profile -> BelongsTo -> User
// User.php

public function profile()
{
    return $this->hasOne(Profile::class); // assumes there is a `user_id` column in the `profiles` table
}

// Profile.php

public function user()
{
    return $this->belongsTo(User.php);
}

kfirba left a reply on Getting Error When Run A Command • 2 months ago

@Lalit Hey.

My guess is that you forgot to import the Exception class at the top of the GenerateInvoice class which means that every reference to the Exception class in that file will actually result in an attempt to use the App\Jobs\Exception.

The fix should be rather easy, simply add this to the use statements in your job file:

Use Exception;

kfirba left a reply on Why I Can't Get All Details According To User From Database? • 2 months ago

@hemal Hey.

You need to tell Eloquent that you also want to load the relationship profile for the authenticated user. You can do it by calling the load method or just try to access the profile property off of the user object:

Auth::user()->load('profile'); // Now the user has a `profile` attribute
Auth::user()->profile; // will detect that `profile` is a relationship and will fetch it for you.

Please read more about relationships in Eloquent here: https://laravel.com/docs/5.5/eloquent-relationships

I would also suggest to carefully read this: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

kfirba left a reply on Prevent Laravel_session Before Authentication • 2 months ago

@Kolorbon You can certainly be less harsh. I believe @Snapey was just trying to point you to the default middlewares that are attached to every route in the web group (a.k.a the routes/web.php file)

Anyways, I think you can do that by overriding the StartSession middleware.

If you take a look at the App\Http\Kernel class there is a $middlewareGroups variable that has middlewares configured for the web and api groups. One of the web middlewares is the \Illuminate\Session\Middleware\StartSession class I mentioned before.

This middleware is responsible for generating Laravel's session and sending it with the response. What you can do is create your own session middleware which will extend that middleware and override the handle method to only add the cookie to the response in case the user is authenticated.

It may look something like:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Middleware\StartSession;

class CustomStartSession extends StartSession
{
    public function handle($request, Closure $next)
    {
        // The `terminate` method of StartSession checks on that value.
        $this->sessionHandled = true;

        // Delegates to the parent's `handle` method if we should enable sessions for the current reuqest.
        if ($this->shouldEnableSession()) {
            parent::handle($request, $next);
        }
    }

    protected function shouldEnableSession()
    {
        return auth()->check();
    }
}

Make sure you replace the original StartSession middleware with our CustomStartSession middleware in the Kernel class.

13th September, 2017

kfirba left a reply on Find The Number Of Change Rows • 3 months ago

@young_artisan Hey

It may not answer your question but you may be interested in my answer for another thread where I suggest a better way to import bulks of data while inserting new rows and updating old ones: https://laracasts.com/discuss/channels/eloquent/performant-way-to-mass-update-or-create/replies/365924

As for your question, the easiest way to calculate that is to run a simple select count on your database prior to inserting/updating:

$newRows = count($values) - Model::whereIn('your_primary_key', $values)->count();

kfirba left a reply on Performant Way To Mass "update Or Create" • 3 months ago

@pilat ORM is great but sometimes it's not the most performant solution.

Don't be afraid to "stray off" the ORM way. I LOVE ORM but many times I find myself writing custom queries in order to squeeze more performance from my application.

As for the max query length, you can just run: show variables like 'max_allowed_packet' to see what the max query length is set on your server. Of course, you can change this setting. To increase the max_allowed_packet, open the my.ini/my.cnf under [mysqld] section and alter the setting. Once the change is done you would have to restart the server.

kfirba left a reply on Performant Way To Mass "update Or Create" • 3 months ago

@pilat Hey.

TL;DR I've written a class that utilizes MySQL's on duplicate key update feature (see code below).

I've actually had a case where I needed to load massive Excel files into my database (The excel file was exported from another CRM program). The thing is that the customer required that if a record that already exists in my database also appears in the Excel file, he wants to update my local database with the new data from the Excel file.

So I've gone ahead and implemented that very naively: loop through the Excel rows and for each row if it exists update it, otherwise create it.

Well, it worked but it was really slow when the Excel file had like 2k rows or even more (Don't forget the constraints that the database has to check every time we insert or update a record).

So I started thinking what can I do in order to improve that? I ended up using MySQL's on duplicate key update feature.

So to get you familiar with this feature, just as the name suggests, it attempts to insert the rows into the database. When it encounters a duplicate UNIQUE constraint or duplicate PRIMARY KEY, it will automatically run an update statement for that row. Sounds good right? However, you might wonder: "Oh well, MySQL still internally does all that checking behind the scenes, why would it be significantly faster"?

There is a short answer for that. Usually, the time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:

  • Connecting: 3
  • Sending query to server: 2
  • Parsing query: 2
  • Inserting row: 1 × size of row
  • Inserting indexes: 1 × number of indexes
  • Closing: 1

(The information above was taken from MySQL's website)

So basically, there is a cost we can't do anything about which is connecting, sending the query, parsing it and terminating the connection. This cost is as high 8. it takes 80% of the time (Given we are inserting 1 row with 1 index only)!

So the code is pretty straightforward:

namespace App\Support;

use Illuminate\Support\Facades\DB;

class ResourceImporter
{
    /**
     * Inserts or updates the given resource.
     *
     * @param       $table
     * @param       $rows
     * @param array $exclude The attributes to exclude in case of update.
     */
    public function insertOrUpdate($table, $rows, array $exclude = [])
    {
        // We assume all rows have the same keys so we arbitrarily pick one of them.
        $columns = array_keys($rows[0]);

        $columnsString = implode('`,`', $columns);
        $values = $this->buildSQLValuesFrom($rows);
        $updates = $this->buildSQLUpdatesFrom($columns, $exclude);
        $params = array_flatten($rows);

        $query = "insert into {$table} (`{$columnsString}`) values {$values} on duplicate key update {$updates}";

        DB::statement($query, $params);

        return $query;
    }

    /**
     * Build proper SQL string for the values.
     *
     * @param array $rows
     * @return string
     */
    protected function buildSQLValuesFrom(array $rows)
    {
        $values = collect($rows)->reduce(function ($valuesString, $row) {
            return $valuesString .= '(' . rtrim(str_repeat("?,", count($row)), ',') . '),';
        }, '');

        return rtrim($values, ',');
    }

    /**
     * Build proper SQL string for the on duplicate update scenario.
     *
     * @param       $columns
     * @param array $exclude
     * @return string
     */
    protected function buildSQLUpdatesFrom($columns, array $exclude)
    {
        $updateString = collect($columns)->reject(function ($column) use ($exclude) {
            return in_array($column, $exclude);
        })->reduce(function ($updates, $column) {
            return $updates .= "`{$column}`=VALUES(`{$column}`),";
        }, '');

        return trim($updateString, ',');
    }
}

The usage is as follows:

$resourceImporter->insertOrUpdate(
                'users', // table name
        $rows, // array represenation of the rows to insert (assoc array where the key is the same as the DB column name)
                $excludeFromUpdate // Fields you want to exclude (excluded from the $rows parameter above) when a row is being updated. For example, if each row has a default `created_at` set to now, you may want to exclude the `created_at` update field when you update a row since it was created somewhen else in the past.
            );

Note that the class returns the generated query right after it executes it.

As you can see, this class isn't limited to a specific resource type. You can import users, products, articles or anything else you want with it.

Hope it helps.

11th September, 2017

kfirba left a reply on Why Does Factory Double The Count Of Records I Entered And Expect? • 3 months ago

@ejobity Glad it helped you :).

Edit Your Profile
Update

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