swalker

swalker

Developer at ebusiness4us

Member Since 3 Years Ago

Experience Points 101,450
Experience
Level
Lessons Completed 969
Lessons
Completed
Best Reply Awards 7
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.

16 Jul
4 months ago

swalker left a reply on Laravel 5.3+, JSON Column With SQLite

@patrikw1 it works for a while now whereJsonContains('name->en', 'name')no support for sqlite unfortunatelly

10 Jul
5 months ago

swalker left a reply on Homestead.yaml

Not sure what you want, but if you got parse errors, be sure to use spaces (two each level), never tab. Also, I think this: ``` sites: - map: homestead.test to: /home/vagrant/code/public

should really be like: ```
sites:
  - map: homestead.test
    to: /home/vagrant/code/public

swalker left a reply on Running My Tests Empties My Database

I had the same problem a while ago.

The issue was that I was running my tests througt PhpStorm, and it was not using the phpunit config on the project

Are you running phpunit in your vendor folder from the console like so: vendor/bin/phpunit?

05 Jul
5 months ago

swalker left a reply on Laravel Worker And Storage Permissions

Hi there

What I normally do is to change nginx and php-fpm users to an actual user on my system, and then run any deployment, cron jobs and processes with the same user. Also, I change the npm global bin folder to a folder like ~/.npm/bin and put it on my PATH

I dont know if this aproach is correct but it is a breeze to manage everything

31 Mar
8 months ago

swalker left a reply on How To Create Likes??

If I'm not mistaken, hasMany relationships will always return a collection object, even an empty one when there are no registers, wich will result in true when converted to boolean

One solution is to count the results like so:

@if ($post->likes->count())
    You liked this post!
@else
30 Jan
10 months ago

swalker left a reply on Single Login & Registration Form, Bad Idea?

You should never edit files in the vendor folder like the RegistersUsers trait because it will be lost once you update or reinstall your composer dependencies.

The right way is to override the register method on the RegisterController, it will be executed instead of the trait's method.

About the design pattern, I think that if it satisfies what your client need and it makes sense to do so, then it is ok go for it

swalker left a reply on Testing Sequence Order For Laravel Dusk

Tests work like this. Prepare, act and assert

You can fearlessly replicate the data you need for testing a specific action

Lets say you make a test that tests the article creation and verifies that it created a draft article and that it is not published

Then you make another test that, before anything, creates a draft article from factory, and then tests the publishing action and verifies that the article is published

There is no point in keeping data between tests

04 Nov
1 year ago

swalker left a reply on Change The Div With Ajax And Multiple [email protected]

Hello there,

I'm sorry to say tha there is no pocket sorcery for this.

Alternatively, you can try Turbolinks: https://github.com/turbolinks/turbolinks

swalker left a reply on Posting Data To View

Hello, I think it throws an error beacause the variable is not initialized sometimes... try:

    // ...
    $users = [];
    if (isset($min_age) && isset($max_age))
    {
    // ...
29 Jun
1 year ago

swalker left a reply on Static Method Within Model To Save And Return Instance Of Itself

Hi, this happens because findOrNew() will return a new empty object

public static function saveObjToModel($apiObj) {
    $myModel = new static;
    $myModel->id = $apiObj->id;
    $myModel->name = $apiObj->name;
    $myModel->save();
    return $myModel;
}
´´´
this should work

swalker left a reply on Get Attribute From Relationship If Is Null

Hi, you can use DB::raw() for this.

$results = ModelA::select(
    'model_a.*',
    \DB::raw(
        '(CASE WHEN model_a.name is null 
            THEN model_b.name 
            ELSE model_a.name 
        END) AS name'))
    ->leftJoin('model_b', 'model_a.id', 'model_b.model_a_id')
    ->get();
03 May
1 year ago

swalker left a reply on NPM Issues With Laravel 5.4.21

try

npm install node-sass

not sure why it works, I dont need this on linux

29 Apr
1 year ago

swalker left a reply on How To Test Symfony Process Inside A Queued Job?

For this test I made a mock of Process inside the job

    private function getProccess($cmd,$cwd)
    {
        if (app()->environment() != 'testing'){
            return new Process(trim($cmd), $cwd);
        }
        
        $process = \Mockery::mock(Process::class);
        $process->shouldReceive(
            'setTimeout', 'run', 'wait', 'stop', 'getCommandLine',
            'getExitCode', 'getExitCodeText', 'getWorkingDirectory',
            'isOutputDisabled', 'getErrorOutput'
        );
        $process->shouldReceive('isSuccessful')->andReturn(config('command-should-succeed'));
        $process->shouldReceive('getOutput')->andReturn('sent for execution');
        
        return $process;
    }

and my runCommand method calls for

        $process = $this->getProcess($cmd, $cwd);

then in my test I set a config parameter

        config(['command-should-succeed' => true]);

not sure if it is the best solution but works perfectly (:

23 Apr
1 year ago

swalker left a reply on Problem In Showing Errors In Right Place

I think it is a better idea to say "Hey, you typed something that doesn't match" instead of "Hey, you typed the username right, but the password is wrong". It is half way done to someone that have bad intentions.

17 Apr
1 year ago

swalker started a new conversation How To Test Symfony Process Inside A Queued Job?

Hello there,

I am relatively new to testing and so... I have this inside a queued job:

    public function handle()
    {
        ...

        $output .= $this->runCommand("ls -la");
        ...
    }
    /**
     * Runs a command
     *
     * @param        $cmd
     * @param string $cwd
     *
     * @return string
     */
    private function runCommand($cmd, $cwd = '')
    {
        
        $process = new Process(trim($cmd), $cwd);
        $process->setTimeout(300);
        $process->run();
        $process->wait();
        
        if ( ! $process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }
        
        return trim($process->getOutput());
    }

How can I test this without actually running the command?

Is it ok if I mock the Proccess class inside my code?

12 Apr
1 year ago

swalker left a reply on Am I Just Stupid?

You are not stupid, you are awesome! You are here seeking knowledge just like us all. Don't give up it pays off.

09 Apr
1 year ago

swalker left a reply on Error While Testing File Uploads

Try generating a fake disk: Storage::fake('local');

swalker left a reply on Test Doesnt Display Errors Correctly

I am confused, you said you don't have the method in your controller and the error says exactly that you don't have the method in your controller... it seems correct.

08 Apr
1 year ago

swalker left a reply on Caching API Requests

Laravel has a Cache facade, you can especify the time the cached data will be remembered, of course you wont know when the incoming data has changed unless the cache has expired.

To bypass this limitation I sugest using a queued job that runs in the background every X minutes

an exemple of caching data would be something like this:

$cachedData = Cache::remember('rssfeed-' . $this->feed->id, 10, function () {
     $rssfeed = new SimplePie();
     $rssfeed->set_feed_url($this->feed->url);
     $rssfeed->enable_cache(false);
     $rssfeed->init();
     $rssfeed->updated = Carbon::now();
     return $rssfeed;
});

you use it like Cache::remember('key', $timeToRemember, $callback) in the example, it will remember the data for 10 minutes, you can forcefully forget the data using Cache::forget('key')

swalker left a reply on How To Retrieve A Value In A Route From A Controller

view:

{{ route('sujet.index', $jeu) }}

web.php

Route::get('jeus/{jeu}', ['as'=>'sujet.index','uses'=>'[email protected]']);

this will become something like: Http:// localhost/multigaming/public/jeus/1

in your controller you use

public function show(Jeu $jeu) {
    return $jeu;
}

note that $jeu in the controller must be the same as the {jeu} in the route, so, if you use {somethingElse} in the route, the variable in the controller must be $somethingElse

swalker left a reply on Using Factory In PHPUnit Provider Fails

Hi there,

did you change your user model's definition in database/factories/ModelFactory.php? if so, can you share it please?

19 Mar
1 year ago

swalker left a reply on Can I Modify A Model's Values On A Relationship Before Returning The Results?

@mmacdonald yeah, it is wonderful if you want to just display it, for sorting I would make a custom query

swalker left a reply on Change Auth::user Values After Logged In Laravel 5

Hi, not sure why it throws MethodNotAllowed... try changing

<form class="form-horizontal" role="form" method="POST" action="{{ route('clientes.update',$user) }}">
    <input name="_method" type="hidden" value="PATCH">
    <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

to

<form class="form-horizontal" role="form" method="POST" action="{{ route('clientes.update',$user) }}">
    {!! method_field("PATCH") !!}
    {!! csrf_field() !!}

@Snapey route('name',$model) works since 5.4 ;)

swalker left a reply on Can I Modify A Model's Values On A Relationship Before Returning The Results?

Just an idea

In model ´´´php function present(){ return new App\Presenters\StudentPresenter($this); } ´´´ Presenter.php ´´´php

09 Mar
1 year ago

swalker left a reply on Store In Session The Last Value Of The Column Updated_at

You just want to display it once right?

You can redirect from your login with a message

redirect()->to('/home's)->withMessage("Last login {$lastLogin->diffForHumans()}");

Or simply flash a session message

$request->session()->flash('message', "Last login {$lastLogin->diffForHumans()}")j

Then you can display it in your view

@if(session('message'))
    {{session('message')}}
@endif
08 Mar
1 year ago

swalker left a reply on Store In Session The Last Value Of The Column Updated_at

Hi, the simplest way is to just make a new column in the users table $table->dateTime('last_login') and update it on every successful login ;)

swalker left a reply on Why Can't I Have My Variable In My View?

Hi there,

if I am not terribly mistaken, when you redirect() you are passing session variables, if you want to inject variables in the view you should use view('view.path',['devices'=>$myDevicesArray])

If you want to pass it as session variables, then ok but call it with the session helper like

 @if(session('devices'))
      @foreach(session('devices') as $d)
           <li><a href="#">{{ $d->alias }}</a></li>
      @endforeach
 @else
       <li><a href="{{ route('appdevices.show') }}"></a></li>
 @endif 
16 Feb
1 year ago

swalker left a reply on Model Helper

What I like to do is make some helper classes to handle this kind of methods

And then inject a instance of it in a service provider

public function boot()
{
    view()->share('transaction', new TransactionHelper);
}

And in the view I use

{{ $transaction->currency(1)->total }}

in case you use it in just one or two views its better to new it up when you callthe view

15 Feb
1 year ago

swalker left a reply on Upgrading From 5.3 To 5.4 Lumen Request

Hello

This change might be related to this: https://laravel-news.com/request-object-changes-in-lumen-5-4

So, if you were using request('token') or so in a service provider you need to change it to somewhere else

swalker left a reply on 500 Internal Server Error On Forge Using Ngingx

Hello you can check for error in 2 places:

  • /var/log/nginx/<yourdomain.com>.log
  • /storage/logs/laravel.log

Usually, when you use windows you get errors with file permissions you can fix it with

$ find $PWD -type d -print0 | xargs -0 chmod 0755
$ find $PWD -type f -print0 | xargs -0 chmod 0640
$ sudo chown -R forge:www-data $PWD
$ chmod -R 0775 $PWD/{database,storage}

Best regards swalker

14 Feb
1 year ago

swalker left a reply on Injection Dependency In An Update Method From The Router

Humm... Is it injecting the EmergencyContact correctly? does it have anything in the attributes property when you dd?

public function editEmergencyContact(EmergencyContactRequest $request, EmergencyContact $emergencyContact)
{
    dd($emergencyContact);
}

note that you must use the variable with the same name that you have in your route like:

Route::patch('emergency/update/{emergencyContact}','[email protected]');

if you are using a resource route you can check it with the command php artisan route:list

swalker left a reply on Injection Dependency In An Update Method From The Router

Hello, try using the model's update method like:

try {
    $input = $request->all();
    $input['updated_by'] = Auth::id();
    // $input['updated_at'] = Carbon::now(); // you dont need this, its automatic

    $emergencyContact->update($input); //it will update and save

} catch (\Exception $e) {
    return response()->json(['error' => $e->getMessage() ], 400);
}

swalker left a reply on Polymorphic Relationship

You can use it like any other model:

$form->submissions()->create([
    'foo' => 'bar'
]);

note that you use a function instead of a property

10 Feb
1 year ago

swalker left a reply on MethodNotAllowedHttpException Not Found When I Paginate In Laravel

Hello,

Try changing the form to GET and change your links to:

{{ $products->appends(Input::except('page'))->links() }}

swalker left a reply on Polymorphic Relationship

Hi, I guess that in your Form model you should use morphMany too...

and then remove the form() method in your Submissions model that should not be necessary

swalker left a reply on Polymorphic Relationship

Hi, in you Form model you should use

// Form.php
public function submissions()
{
    $this->morphMany('App\Submission');
}

swalker left a reply on Store Data From Laravel Form To Database

Hello, inside database/migrations you can find the files you use to create/alter/remove your database tables.

Details can be found here: https://laravel.com/docs/5.4/migrations

Good learning

swalker left a reply on DomPDF Download()

Hello, maybe you have a route pointing to a similar path. It is the only cause that comes to mind right now. Make sure the folder you are saving your file dont match some route like ´Route::get('pdf',...);´

06 Aug
2 years ago

swalker left a reply on DB_HOST For ENV File.

I think I get what you are doing wrong... the correct port is DB_PORT=3306 33060 is used when you need to access your Homestead database from outside programs you can execute artisan comands from inside Homestead using the vagrant ssh command to access it if you are executing artisan commands from outside the virtual machine you need change the port to 33060 but if you execute it from inside you dont need to change anything

18 Jul
2 years ago

swalker left a reply on Password Encrpytion

in the case you cant afford to change everyone's password you could "temporarily" create a new method for authentication like

public function dummyLogin(Request $request)
{
    $user = User::where('login',$request->get('login'))->first();//find by login or email or whatever
    if (md5($request->get('password')) == $user->password) {
        //save a new password to a temporary table field like new_password
        $user->new_password = bcrypt($request->get('password'));
        $user->save();
        
        auth()->loginUsingId($user->id);

        return redirect()->to('/');
    }

    return redirect()->back()->withError('Something went really wrong!!');
}

and later when you got everyone a bcrypt password you can simply adapt your VB code to use bcrypt, rename the table fields and remove this method

16 Jul
2 years ago

swalker left a reply on Prevent Accidental Recursive Nesting In HasMany/belongsTo

you could do something like this:

public function userProfileComplete()
    {
        return $this->hasOne(User::class)->where('something');
    }

and then:

public function complete()
    {
       
        if (empty($this->someField)) {
            return false;
        }
    
        if ( ! array_key_exists('userProfileComplete', $this->relations)) {
            $this->load('userProfileComplete');
        }
    
        if ( ! $this->getRelation('userProfileComplete')) { //calls select * from `users` where `users`.`id` = '1'
            return false;
        }
        
        return true;
    }

now it will execute the query only once and you dont need eager loading anymore...

08 Jul
2 years ago

swalker left a reply on Is There Simpler Way To Update Pivot Table Fields

Well.. thank you! It will work too but, its already working and looks like I would need to add a new line searching for whatever member is the admin first, then get his id to pass to the updateExistingPivot method It just dont look cleaner

07 Jul
2 years ago

swalker started a new conversation Is There Simpler Way To Update Pivot Table Fields

Hello,

so, this is the context: user can be in many teams teams can have many members(users) une of the members is the team's admin

and then I want to change the admin

I got it working like this but its kind of nasty: in my Team model

    public function setAdmin(User $user)
    {
        $this->members()->wherePivot('is_admin', 1)->pivot->update(['is_admin' => false]);
        $this->members()->wherePivot('user_id', $user->id)->first()->pivot->update(['is_admin' => true]);
    }
    ```
This feels just wrong
I couldn't find a better way I swear I searched a lot