swalker

Developer at ebusiness4us

Experience

96,450

7 Best Reply Awards

  • Member Since 2 Years Ago
  • 919 Lessons Completed
  • 15 Favorites

16th July, 2018

swalker left a reply on Laravel 5.3+, JSON Column With SQLite • 1 month ago

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

10th July, 2018

swalker left a reply on Homestead.yaml • 1 month ago

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

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?

5th July, 2018

swalker left a reply on Laravel Worker And Storage Permissions • 1 month ago

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

31st March, 2018

swalker left a reply on How To Create Likes?? • 4 months ago

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

30th January, 2018

swalker left a reply on Single Login & Registration Form, Bad Idea? • 6 months ago

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 • 6 months ago

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

4th November, 2017

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

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 • 9 months ago

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

    // ...
    $users = [];
    if (isset($min_age) && isset($max_age))
    {
    // ...

29th June, 2017

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

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

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

3rd May, 2017

swalker left a reply on NPM Issues With Laravel 5.4.21 • 1 year ago

try

npm install node-sass

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

29th April, 2017

swalker left a reply on How To Test Symfony Process Inside A Queued Job? • 1 year ago

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 (:

23rd April, 2017

swalker left a reply on Problem In Showing Errors In Right Place • 1 year ago

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.

17th April, 2017

swalker started a new conversation How To Test Symfony Process Inside A Queued Job? • 1 year ago

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?

12th April, 2017

swalker left a reply on Am I Just Stupid? • 1 year ago

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

11th April, 2017

9th April, 2017

swalker left a reply on Error While Testing File Uploads • 1 year ago

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

swalker left a reply on Test Doesnt Display Errors Correctly • 1 year ago

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.

8th April, 2017

swalker left a reply on Caching API Requests • 1 year ago

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

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

Hi there,

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

19th March, 2017

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

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

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

Just an idea

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

9th March, 2017

swalker left a reply on Store In Session The Last Value Of The Column Updated_at • 1 year ago

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

8th March, 2017

swalker left a reply on Store In Session The Last Value Of The Column Updated_at • 1 year ago

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

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 

16th February, 2017

swalker left a reply on Model Helper • 1 year ago

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

15th February, 2017

swalker left a reply on Upgrading From 5.3 To 5.4 Lumen Request • 1 year ago

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

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

14th February, 2017

swalker left a reply on Injection Dependency In An Update Method From The Router • 1 year ago

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

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

You can use it like any other model:

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

note that you use a function instead of a property

10th February, 2017

swalker left a reply on MethodNotAllowedHttpException Not Found When I Paginate In Laravel • 1 year ago

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

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

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

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

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',...);´

6th August, 2016

swalker left a reply on DB_HOST For ENV File. • 2 years ago

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

18th July, 2016

swalker left a reply on Password Encrpytion • 2 years ago

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

16th July, 2016

swalker left a reply on Prevent Accidental Recursive Nesting In HasMany/belongsTo • 2 years ago

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

8th July, 2016

swalker left a reply on Is There Simpler Way To Update Pivot Table Fields • 2 years ago

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

7th July, 2016

swalker started a new conversation Is There Simpler Way To Update Pivot Table Fields • 2 years ago

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
Edit Your Profile
Update

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