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

Drfraker

Experience

66,070

8 Best Reply Awards

  • Member Since 4 Years Ago
  • 837 Lessons Completed
  • 3 Favorites

5th December, 2017

Drfraker started a new conversation Queue Worker Constantly Restarting • 1 week ago

I have a server that I manage with forge. I'm seeing a few things that don't make sense to me.

Server Info: I have an application server, a redis server for queues, sessions, and caching and a database server for MySql. These are all set up in a network on Forge so they can communicate with eachother. My cache, session and queues are all using the default settings that laravel provides out of the box. My application server is using opcache.

First: The queue worker is restarting constantly. When I view the progress it is always at a runtime of 14 seconds or less, or restarting. This can't be right.

Seconde. The queue is still processing event listeners that don't exist in my application anymore. Like it's picking up jobs from old code still.

Some things that I did that might be a problem:

  1. I ran php artisan queue:work and php artisan queue:listen on my application server while also having a daemon on forge that is running the same queue.
  2. I ran php artisan queue:flush on my application server to try to get rid of old jobs that were running the code that doesn't exist anymore.

Thoughts?

29th November, 2017

Drfraker left a reply on Guards Don't Work. • 2 weeks ago

Does the Kod Class have a password column in the table? It appears that it does not based on the error you are receiving.

21st November, 2017

Drfraker left a reply on Avoiding Dynamic Calls • 3 weeks ago

This is exactly what form validation is for.

request()->validate([
    'email' => 'unique:users,email_address'
]);

You should also enforce this at the database layer:

// in migration
$table->string('email')->unique();

Drfraker left a reply on How To Compare A Date In A Retrieved Model? • 3 weeks ago

If you are using expire_at you will need to set that in $dates array on your model in order to cast it to a carbon instance when you retrieve it.

protected $dates = [
    'expires_at',
]

Otherwise do this:

$expired = Carbon::parse($model->expires_at) <= Carbon::now();

Drfraker left a reply on Eager Loading With Field Filters • 3 weeks ago

From the docs: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

Eager Loading Specific Columns

You may not always need every column from the relationships you are retrieving. For this reason, Eloquent allows you to specify which columns of the relationship you would like to retrieve:

$users = App\Book::with('author:id,name')->get();

When using this feature, you should always include the id column in the list of columns you wish to retrieve.

Drfraker left a reply on How To Compare A Date In A Retrieved Model? • 3 weeks ago

Timestamps in Laravel are cast to instances of Carbon. http://carbon.nesbot.com/

You can check the carbon website for documentation on comparing dates. Make sure you watch the vscode series on Laracasts as it covers packages that might help you identify types etc.

Drfraker left a reply on Need Help With Pulling Data. • 3 weeks ago

If there isn't a config setting within the original package that allows the package to do this, you will probably have to copy the package files into your own app or create a version of the package from the existing one and require that instead of the original. Then find in the package where it is getting those config settings and write the functionality to get it from the database instead.

Should be pretty straightforward.

Drfraker left a reply on Constructor In Model Class • 3 weeks ago

I think it should be

public function __construct()
{
    parent::__construct();
    // your constructor stuff
}

Or am I missing something?

Drfraker left a reply on Cookie::get Returns Encrypted Value • 3 weeks ago

Is it possible that you are encrypting your cookies somewhere in your code when you set them? In that case you would be setting an encrypted value that in turn, gets encrypted, and retrieving an enctypted-encrypted value. Therefore, you get an encrypted value after it's decrypted the by the framework the first time. This seems inception-like, right!

Drfraker left a reply on Need Help With Pulling Data. • 3 weeks ago

Rather than bending the package to your needs, you might scrap the package and write the logic specific to your own needs. I've found that going down the package modification rabbit hole is usually a lot more time consuming than writing something custom in the first place.

Drfraker left a reply on How Do You Store The Wysiwyg In The Database? • 3 weeks ago

Create a migration for the table:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateSomeContentTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('some_content', function(Blueprint $table) {
            $table->increments('id');
            $table->longText('wysiwyg_text');
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('some_content');
    }

}

Store the content from the wysiwyg editor in the wysiwys_text column.

Drfraker left a reply on Refactoring Messy Store Method - Need Help Understanding Use Cases From Tutorial Lesson 2 • 3 weeks ago

If the class BookClubEvent has dependencies, you can put a constructor in that class. Then when you call

new BookClubEvent(Dependency $dependency) 

you can pass the dependencies to it. Better yet if you use the container to create a new instance of BookClubEvent it can build the class with it's dependencies for you.

app(BookClubEvent::class)

If the dependencies are resolvable by the container this will be done automatically.

Drfraker left a reply on Authentication,authorisation • 3 weeks ago

use artisan make:auth and make one user for the admin. Redirect any requests to the register route so other people are not able to create accounts.

16th November, 2017

Drfraker left a reply on Multiple Currencies • 4 weeks ago

@amjadkhan896 You need to have some way to know where a user is from, like a profile setting. Then check that and convert money to their currency. Use the language stuff I linked to above to show currency indicators and names in the correct language for the user who is viewing it. With the information you provided it is tough to get too specific about implementation. Hope that helps :)

15th November, 2017

Drfraker left a reply on Get All With Count Of Specific Condition. • 4 weeks ago

@RonaldGJ That is correct, it will not run another query. Once you call the get() method on query you get an eloquent collection. So manipulation of that data is not hitting the database anymore.

Drfraker left a reply on Route Not Defined. In 2 Subpages • 4 weeks ago

After more digging I see the problem. The Route::resource method does not accurately name your routes when you nest them like you are in prefix callbacks. If you want the name convention you are trying get, it looks like you have to do this:

Route::resource('emp/lavo', 'EmpController');

Your route names will be more accurate too: lavo.create, lavo.store etc.

Drfraker left a reply on Route Not Defined. In 2 Subpages • 4 weeks ago

It doesn't look like the route is getting named 'emp.lavo.create'. When you do artisan route:list the name is not listed.

In your view try:

// emp/lavo/index.blade.php

<div class="pull-right">
      <a class="btn btn-success" href="/emp/lavo/create"> Create New Lavo</a>
</div>

Drfraker left a reply on Multiple Currencies • 4 weeks ago

You'll want to make use of localization: https://laravel.com/docs/5.5/localization

Drfraker left a reply on Get All With Count Of Specific Condition. • 4 weeks ago

If you want to stick to depending on the subscriptions collection, you should be able to do something like:


$subscriptions->filter(function($subscription){
    return $subscription->paid();
})->count();

It might be better to move this logic out of the view though.

Drfraker left a reply on Load Balancer: Can Someone Explain Me How To Replicate The Database? • 4 weeks ago

I don't understand why you think having a separate server for your MySql is less secure. You set up the Database server to only allow traffic from the IP address of the application server. This is a cinch with laravel forge. I'd suggest checking that out.

14th November, 2017

Drfraker left a reply on Passing A Url Through An Html Form. • 1 month ago

Put it in a hidden field and serialize it. The unserialize it in your controller. Why are you adding this data to a placeholder? Do you want to view it in the textarea?

17th October, 2017

Drfraker left a reply on Fatal Error: Call To Undefined Method • 1 month ago

$this->get(route('route-name'));

16th October, 2017

Drfraker left a reply on Relationship Between Two Models/Tables • 1 month ago

Many to many relationships require a pivot table. The convention is brand_user. The singular name of each table in alphabetical order. You'll have to create a migration for the brand_user table and give it a user_id and a brand_id column. Once that is done, the other recommendations will work.

11th October, 2017

Drfraker left a reply on Task Runs On My Local Machine But Not Production Laravel Lumen • 2 months ago

@djarrin if my answer saved the problem please mark it as the best answer. It helps other people find solutions to their problems.

3rd October, 2017

Drfraker left a reply on Observers Or Event Triggers • 2 months ago

In the example you gave I'd opt for a DiscussionWasCreated event. The logic that is performed after the discussion is created is happening in other parts of the system, so an observer makes less sense to me. In your case when a discussion is created, users need to participate in the discussion. So the logic belongs with a user and you would fire an event and pass the Discussion model to the constructor for any listeners to use. Then the logic would happen in the appropriate place in your app.

I would consider an observer in cases where the logic that happens in reaction to the event is related to the model itself. For example, if you have an Image model and when you upload a new image your application needs to pass it through an AI service to make sure that it isn't offensive. Since the logic happens on the model it is observing the observer makes more sense.

I know the example is contrived but you can get the gist of what I'm saying.

Drfraker left a reply on Testing Queued Code Vs Inline • 2 months ago

What is the extension of file1? The issue might be that you are asking if file1 exists, but it might be called file1.jpg or something.

Drfraker left a reply on Task Runs On My Local Machine But Not Production Laravel Lumen • 2 months ago

You might have to run php artisan queue:restart. If you worker is not restarted before you try to run a queued job it won't have the newest code changes.

Drfraker left a reply on How To Mock A Predis Client For Testing Redis Operations • 2 months ago

Well the issue here is not that I must mock it, but that I need to test the Redis >functionality without having an actual Redis server available to serve the test >- in other words, I want to be able to run the unit tests anywhere.

This makes sense to me in the context of mocking an external API call where you need internet or something. However, with redis you can install it on your VM or local machine that your tests are running on. For instance I have redis installed on my Macbook Pro locally and use Valet to serve the application. But that could just as well be a Virtual machine running a vagrant setup. In any case you can install Redis so that your testing environment has access to it. There is no reason I can think of that would prevent you from running your tests if you were not mocking Redis calls.

Let me know if I'm missing something obvious here.

In the case of mocking Redis, did the example I outlined make sense?

Drfraker left a reply on How To Mock A Predis Client For Testing Redis Operations • 2 months ago

Have you considered not mocking it? If you feel that you have to mock Redis, why do you feel that way? Redis is so fast I don't think you can make a case for mocking it for speed reasons. The mocking library you are referring to claims to have un-mocked Redis features that could be a hangup. Consider using Redis instead of the mocking library, unless you have a specific reason why you can't.

If you cannot use Redis, can you extract the parts of the class that are calling redis to another class or repository and then mock that?

class SomeClassThatCallsRedis {
    public function doSomething($params){
        // do some stuff

        $this->store($params);
        
        return $value;
    }

    private function store($params) 
    {
        // store some things using redis commands here...
    }
}

becomes

class SomeClassThatCallsRedis {

    private function store($params) 
    {
        $redis = app(RedisRepository::class);
        return $redis->store($params);  
    }
}

In your test

public function test_some_stuff() {
    $subject = new SomeClassThatCallsRedis();
    $redis = Mockery::mock(RedisRepository::class);
    app()->instance(RedisRepository::class, $redis);

    $redis->shouldReceive('store')
            ->with($params)
            ->once()
            ->andReturn(true);

    $subject->doSomething($params);

    
}

Obviously this is pseudo code but you get the general idea. Architect your class so you can mock the Redis store.

2nd October, 2017

Drfraker left a reply on How To Mock A Predis Client For Testing Redis Operations • 2 months ago

You could take look at this: https://github.com/M6Web/RedisMock

However redis is so fast why not just use redis itself? Mocking it for speed reasons seems unwarranted.

Drfraker left a reply on Laravel 5.5 Auth Middleware, Redirect To Login Page, Can Show Some Message? • 2 months ago

In the exception handler which is found in App\Exceptions\Handler you can add a flash message when AuthenticationExcpetion is thrown.

public function report(Exception $exception)
{
    if ($exception instanceof AuthenticationException) {
        Session::flash('login-error', 'You must be logged in to do that...');
    }
return parent::report($exception);
}

Then in your login view, check for that error in the session and display a message when it is present.

30th September, 2017

Drfraker left a reply on Get The Of An Register From Other Table Using Its ID • 2 months ago

I think it's possible you are trying to model a car version that can have any number of shifts. So the method names are right. It the relationships are backwards. Is that accurate?

Drfraker left a reply on Laravel 5.3 Sanitize Validation • 2 months ago

Your sanitize function isn't returning anything.

Drfraker left a reply on Get The Of An Register From Other Table Using Its ID • 2 months ago

It should be:

public function carversion () {
    return $this->hasMany(‘App\Car’);
}

Drfraker left a reply on Laravel With Vuejs Authentication • 2 months ago

All routes inside the api.php file are already inside a route groups with the auth:api middleware defined on it. Try this with the auth middleware removed, that is for web.php routes.

25th September, 2017

Drfraker left a reply on What Is The Best Way To Show Custom Exceptions (laravel 5.4) • 2 months ago

Ultimately, I think you would want to have your app handle exceptions before any end user see the whoops something went wrong page. But if you would like a custom page there do this:

In the App/Exceptions/Handler.php file you can remove the line where it calls

return parent::render($request, $e);

and replace it with your own view

return view('some-custom-error-view')->withStuff($e->stuff);

Drfraker left a reply on Creating "Microsoft Like" Sign In Experience • 2 months ago

You could store a token in the local storage of the browser of the user. Also store this token on a table in the database where it belongs to a user. When a user visits a page of your site, determine if a token exists in local storage on the browser. If so, automatically log-in the user that the token belongs to.

You will want to make the token a long random string, also you will want to run a job that will remove user tokens automatically, say 1 hour after creation. Alternatively you could store the tokens in a redis database and set them to automatically expire.

There would obviously be more edge case things you would want to cover, like making sure they weren't on a shared browser etc.

23rd September, 2017

Drfraker left a reply on Upgrade Php From 7.0.5 To Latest Stable Version 7.0.23 • 2 months ago

@36864 Yea, I restarted. What I ended up doing was creating an entirely new server, pushing code to it. Setting my machines /etc/hosts file to point to the new server IP address. Once I had everything set up, I changed my DNS to direct traffic to the new server. Worked much better than worrying about the version of PHP I had and possible bringing down the app while making server changes.

21st September, 2017

Drfraker left a reply on Upgrade Php From 7.0.5 To Latest Stable Version 7.0.23 • 2 months ago

Hey @Cronix thanks for the reply. I would want to make sure that php-fpm and php-cli are the same and that I can run the update without any downtime. I did run php -i on the server, which I think outputs the same thing as phpinfo() and saw that it is still php 7.0.5.

Any advice on performing the upgrade? I'm sure a ubuntu ninja could do this in 10 seconds. I'm just afraid that I'll screw something up and have a ton of calls because the app is down.

Drfraker started a new conversation Upgrade Php From 7.0.5 To Latest Stable Version 7.0.23 • 2 months ago

I have a production application that I've upgraded from Laravel 5.3 to 5.4. A few of the dependencies will not run on php 7.0.5, which is what is installed on my production server. I would like to update php to the latest stable version 7.0.23. Since it is a live application on a production server it would be best if this update could be done without any downtime.

I have searched on the web and read that running apt-get install php7.0 --only-upgrade is the command I need to run. However, after running that command when I run php -v from the cli it still returns php 7.0.5.

Drfraker left a reply on HOW TO USE 2 COLUMN AS UNIQUE IN VALIDATOR • 2 months ago

What version of Laravel are you using?

Drfraker left a reply on Load Latest Posts To Footer Area • 2 months ago

Assuming your posts model is post you can try the following:

$posts = Post::take(3)->latest()->get();

Then loop through the posts with a foreach and display them as you wish.

Sorry on phone and can't figure out back ticks for code block formatting.

Drfraker left a reply on Testing Delete Method In Phpunit, "Expected Status Code 200 But Received 419." • 2 months ago

Is your environment being set to testing when you run tests? Have you recently run php artisan config:cache? That bit me once, my tests were running with the cached config settings. Try running php artisan config:clear and see if you get past the csrf middleware.

29th August, 2017

Drfraker left a reply on Query JSON Column On MariaDB? • 3 months ago

According to the MariaDb website, JSON columns are not available unit version 10.2. It appears that your version is below that. Is it possible that is the problem? https://mariadb.com/

Drfraker left a reply on PDF With VueJS2 And Laravel • 3 months ago

I think this will get the job done, https://github.com/barryvdh/laravel-dompdf

I'm using it in one of my apps and it seems to work well.

28th June, 2017

Drfraker left a reply on Validation Of An Array And Custom Message. Help Me! • 5 months ago

What does the form look like?

Drfraker left a reply on Search An Array Nested In A Laravel Collection • 5 months ago

Is the API response json?

Try the following to convert the json to an array that the collect function can use. It's difficult to tell if this will solve your problem without having a real example of the API response.

$data = collect([json_decode('{
   "id":97423,
   "visitor_id":231505,
   "domain_sessionidx":1,
   "session_start":"2017-06-01 04:40:07",
   "session_end":"2017-06-01 05:22:45",
   "session_length":2558,
   "count_pages":11,
   "count_pings":7,
   "created_at":null,
   "updated_at":"2017-06-12 18:59:51",
   "pages":[
      1829,
      1811,
      1829,
      1501,
      1829,
      1889,
      1762,
      1686,
      1825,
      1825,
      1825
   ]
}')]);

    $data->filter(function($item){
        return in_array(1764442, $item->pages);
    });

15th June, 2017

Drfraker left a reply on Before I Begin Asking Questions • 5 months ago

"editor: format blocks"

~obviously.

8th May, 2017

Drfraker left a reply on Where Inside Blade L5.4 • 7 months ago

@nam_co your $user->created_at is coming back as a string for some reason. It should be a carbon instance. Are you casting it to a string in the model?

Drfraker left a reply on Can I Turn A Base64 String Into An UploadedFile Object? • 7 months ago

Could you do something like this:

use Illuminate\Http\File;

// Automatically generate a unique ID for file name...
Storage::disk('s3')->putFile('photos', base64_decode(request('file'));

I didn't try running this code, but it seems like it should be able to be done like that or something similar.

Edit Your Profile
Update

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