dimanche 30 avril 2017

Laravel 5.1 package to read email from Gmail, Yahoo, Outlook and other email accounts

I have noticed that there are some individual packages to fetch email from various email accounts. Is there one package that will get email from Gmail, Yahoo, Outlook and other email accounts?



via Chebli Mohamed

laravel 5.1 BelongsTo Reverse call

What i know:

$this->$parent->childs(); //we get childs data

what i want to know how:

$this->child->find($id)->parent(); //how to get childs parent without including model in controller | by just using eloquent

heres my sample code of employee and employeeDependent model:

trait EmployeeRelationships{

    public function dependents(){
        return $this->hasMany(\App\DB\EmployeeDependent\EmployeeDependent::class);
    }

}

trait EmployeeDependentRelationships{

    /**
     * @return mixed
     */
    public function employee(){
        return $this->belongsTo(\App\DB\Employee\Employee::class, 'employee_id');
    }
}



via Chebli Mohamed

vendredi 28 avril 2017

How to send the password to a new user to his\her email in laravel 5.1?

following the question, i am trying this in my AuthController,

    protected function create(array $data)
{
    $randomPassword = Hash::make(str_random(8)); // generating random password
    return $user = User::create([
        'name' => $data['name'],
        'apellido' => $data['apellido'],
        'cedula' => $data['cedula'],
        'usuario' => $data['usuario'],
        'telefono' => $data['telefono'],
        'cargo' => $data['cargo'],
        'email' => $data['email'],
        'password' => bcrypt($randomPassword), // encrypting the password.
    ]);
        Mail::send('auth.Contraseña_NuevoUsuario', $randomPassword, function($message) {
        $message->to($data['email'], $data['usuario'])
        ->subject('Verify your email address');
    });  }

The register is doing well, but for some reason is not sending the email with the password to the new user, my .env and mail.php are already configured to send emails and is working fine for the password recovery, But here in this problem is not sending email, what can be??? please a need some help with this.



via Chebli Mohamed

Adding replyTo in mail.php not working in Laravel 5.1

I have a laravel 5.1 app. I am sending emails in several places. When I add replyTo like below it works.

Mail::queue('emails.password_update', ['user' => $user, 'password' => $password], function($message) use ($user){
            $message->to($user->email, $user->name)->subject('Account Password Updated');
            $message->replyTo('noreply@divostar.com', 'DivoStar');
            $message->priority(1);
        });

But, given that emails are sent in several places and the replyTo email is same. I don't want to repeat it everywhere. What I have done is add an entry in mail.php like below:

'replyTo' => ['address' => 'noreply@divostar.com', 'name' => 'DivoStar'],

and send the mail as such:

 Mail::queue('emails.password_update', ['user' => $user, 'password' => $password], function($message) use ($user){
                $message->to($user->email, $user->name)->subject('Account Password Updated');
                $message->priority(1);
            });

When I do this, it doesn't work. There is no Reply-To in the mail. Why is the entry in mail.php not read?



via Chebli Mohamed

jeudi 27 avril 2017

Can i read my messages on social networks and reply to them on another website

Is there any way to build a common website to read messages and reply to them on that website so user has not to visit the facebook,twitter,or any other if he does not want. I mean in common website he creates special pages for every social network by inserting login/passwords.



via Chebli Mohamed

in laravel soap give me wrong version error once in a while?

I try to use soap and connect to wsdl file. I don't know why 2 from 10 request send but other give me wrong version error. I defined version in call soap by

'soap_version'=>        SOAP_1_1,

wsdl start with this :

<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions xmlns:tm="http://ift.tt/L9w5lv" xmlns:soapenc="http://ift.tt/wEYywg" xmlns:mime="http://ift.tt/L9w8xG" xmlns:tns="http://tempuri.org/" xmlns:soap="http://ift.tt/KIQHA2" xmlns:s="http://ift.tt/tphNwY" xmlns:soap12="http://ift.tt/1fBjFB5" xmlns:http="http://ift.tt/1fBjHsH" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://ift.tt/LcBaVt">

error show me like this :

 "message": "Wrong Version",
  "status_code": 500,



via Chebli Mohamed

mercredi 26 avril 2017

MongoDB\Driver\Exception\ConnectionTimeoutException: No suitable servers found

I got this error when i make unit test for function in controller laravel

MongoDB\Driver\Exception\ConnectionTimeoutException: No suitable servers found (`serverSelectionTryOnce` set): [connection timeout calling ismaster on '10.0.0.106:27017']

how i can solve this?



via Chebli Mohamed

how to send the password to a new user to the email in Laravel 5.1 LTS

Hello to all the community, i want to send to a recently created user by an admin, a ramdonly password to the email. Do someone know a method to do this?



via Chebli Mohamed

Get column names to show and store in another table Error Undefined Index [duplicate]

In laravel 5.1 it is giving en error UNDEFINED INDEX::cost_group i want to show courses table's coulumn name by frop down in another payments view page and store it into another table(payments) when one of them is selected My PaymentsController.php

public function index(Request $request) {
        $filter = $request->input();
        $sort = $request->query();
        $payments = Payment::filter($filter)->sort($sort)->paginate(10);

        foreach(Course::all() as $course) {
            $data['courses'][$course->id] = $course->name;
            $data['courses'][$course->cost_group]=$course->course_cost;
            $data['courses'][$course->cost_minigroup]=$course->course_name;
            $data['courses'][$course->cost_individual]=$course->course_name;

        }

        return view('payments.index', compact('payments', 'data'));
    }

My form.blade.php (of payments)

<div class="ui form">
             <div class="field">
                 <div class="ui selection dropdown">
                     <input type="hidden" name="amount" id="course_val" />
                     <i class="dropdown icon"></i>
                     <div class="default text">Course type</div>
                     <div class="menu">
                         <div class="item course_val" data-value="">Group</div>
                         <div class="item course_val" data-value="">Minigroup</div>
                         <div class="item course_val" data-value="">Individual</div>
                     </div>
                 </div>
             </div>
         </div>



via Chebli Mohamed

how can call user that created in setup function in other function

this is my code

     public function setUp()
     {
        parent::setUp();
        $this->createApplication();

        $this->user = factory(App\User::class)->create([
                'email' => 'testuser@email.com',
                'password' => bcrypt($this->password)
                ]);
    }

    /** @test */
    public function funcTest()
    {   
        $this->actingAs($user);
        $this->visit('/client/ocp/profile/247')
             ->click('New ')
             ->seePageIs('/client/ocp/profile/247/create')
    }
}

i try this code and run test using phpunit i got this error

ErrorException: Undefined variable: user

how can I fix this error?



via Chebli Mohamed

how i can write test for function return json data in laravel

I have a function it return json data

return response()->json([
  'status' => 'OK',
  'data' => [
      'id' => $dataInfo->id,
  ],
]);

how I can solve this in testing for function ?



via Chebli Mohamed

mardi 25 avril 2017

Laravel 5.1 MethodNotAllowedHttpException Error

I'm using resource controller , when i submit form through ajax , it is showing method not allowed exception.

View

 {!! Form::open(array('route' => 'product.store','class' => 'form-horizontal','id' => 'productform','name' => 'productform','files' => true)) !!}
       {!! csrf_field() !!}
       <div class="form-group" style="padding-top: 20px">
            <label for="productName" class="col-sm-3 control-label">Product name</label>
            <div class="col-sm-9">
                 {!! Form::text('productName',null, array('id'=> 'productName','class'=>'form-control','placeholder'=>'Product name'))!!}
            </div>
       </div>                                                            
       <div class="form-group">
            <div class="col-sm-9 col-sm-offset-3">
                 {!! Form::submit('Save', array('class' => 'btn btn-primary btn-block')) !!}
            </div>
                </div>
 {!! Form::close() !!}

AJAX

$("#productform").submit(function () {
    var token = $('[name=_token]').val();
    $.ajax({
        type: 'POST',
        url: 'product/store',
        data: {
            id: '4',
            _token: token,
         },
        success: function (data) {
            alert('success');
            return false;
        }
    })
    return false;
});

routes.php

Route::resource('product', 'ProductController');

What is the problem here...Any help is much appreciated.



via Chebli Mohamed

How can i update a boolean type field in postgresql from a form in laravel 5.1 LTS?

i have a form from where i update the user's data, there i have a checkbox with a value as true, so when it is checked it will send a true value, if it is not checked, then it will send a false value to update if the user is active or inactive. But when i check the table in database, the status field keep true as value, it is not updating the value. So i need a little help to know how i can update the status field from the form with a checkbox from true to false and from false to true. Considering my system is being develope with laravel 5.1 LTS.

Please a i need help or suggestions, thanks.



via Chebli Mohamed

How to check another table's columns and get their values to the other table

i am struggling over this problem Shortly, i have payments page. Admin selects the user and course, then he should select course_type,which gets value from courses table's three columns(cost_group, cost_minigroup, cost_individual,one of them). If course_type is selected, the cost of course must be inserted into payments table(inside course_cost column). So what i have done

Tables:

payments{
          id,
          student_id, 
          course_id, 
          course_cost}
courses {
          id, 
          name, 
          cost_group, 
          cost_minigroup, 
          cost_individual }

My CourseController.php

>  public function get($id) {
>         $course = Course::findOrFail($id);
> 
>         return response()->json($course);
>     }

Here is my form.blade.php

<div class="field">    
   <div class="ui selection dropdown">    
   <input type="hidden" name="course_">
    <i class="dropdown icon"></i>
     <div class="default text">Course type</div>
      <div class="menu">
       <div class="item" data-value="course_group">Group</div>                  
       <div class="item" data-value="course_minigroup">Mini Group</div>
       <div class="item" data-value="individual">Individual</div>
                         </div>
                     </div>
                 </div>

My PaymentsController

 public function store() {
      $payment = new Payment;
      $payment->student_id = Input::get('student_id');
      $payment->course_id = Input::get('course_id');
      $payment->course_cost = Input::get('cost');
      $payment->save();

        return redirect('payment');
        }

so here is problem how to get this cost value in paymentscontroller. If you know how to solve or any method or advice would be great. Thank you in advance guys.



via Chebli Mohamed

lundi 24 avril 2017

laravel test issue-> for index controller function

how be the unit test format for this type of code in laravel ? this is belong to function index in controller

$data = Data
      ::where('client_id', $this->client->id)
        ->paginate(10);

how i can do test for this part of code ?

i did this

// public function testIndex()
// {     

// $response = $this->call('GET', '/backend/route-data'); // $this->assertEquals(302, $response->status());

// }

but i dont know how to do upper code



via Chebli Mohamed

Error: Call to undefined method Illuminate\Http\Response::assertViewHas()

i have this test for create function of controller

public function createTest()
{   
    $user = factory(App\User::class)->create([
        'email' => 'testuser@arabiaweather.com',
        'password' => bcrypt($this->password),
        'type' => 'admin'
    ]);
    $this->be($user);
    $response = $this->call('GET', '/client/1/profile/2/data');
    var_dump($response);

    $response->assertViewHas('client', 1); 
    $response->assertViewHas('clientProfile', 2);

    $this->visit('/client/1/profile/2/data/create')

    ->seePageIs('/client/1/profile/2/data/create');
     $this->user->delete();

}

I got this error

 Error: Call to undefined method Illuminate\Http\Response::assertViewHas()

how i can solve it?



via Chebli Mohamed

InvalidArgumentException: Unable to locate factory with name [default] [App\Routedata]

This is my function

public function create($alias, $profileId)
    {
        $this->setClientAndClientProfile($alias, $profileId);

        return view('client.data.map')->with('client', $this->client)->with('clientProfile', $this->clientProfile);
    }

and this is test that i write it

public function createTest()
    {
        $this->Data = factory(App\Data::class)->create([
            'id' => '1',
            'client' => 'first',
            ' name' => 'name1',
            'Status' => ''

        ]);
       $this->be($this->$RouteForecast);
       $this->visit('/backend/data')

        ->seePageIs('/backend/data');

    }

when i run i got this error

InvalidArgumentException: Unable to locate factory with name [default] [App\Data].

how i can solve this problem ?



via Chebli Mohamed

dimanche 23 avril 2017

laravel index method test The response was not a view. Failed asserting that false is true

this is my test function for index function

/** @test */

public function testIndex()
{
    $this->call('GET', '/backend/route-data');

    $this->assertViewHas('routedata');
    $this->assertViewHas('client');
    $this->assertViewHas('clientProfile');

    $routedata = $response->original->getData()['routeData'];
    $client = $response->original->getData()['client'];
    $clientProfile = $response->original->getData()['clientProfile'];

    $this->assertInstanceOf('\Illuminate\Database\Eloquent\Collection', $routeData);
    $this->assertInstanceOf('\App\Client', $client);
    $this->assertInstanceOf('\App\ClientProfile', $clientProfile);

}

this is the index function

public function index($alias, $profileId) { $this->setClientAndClientProfile($alias, $profileId);

$routeData = RouteData
                    ::where('client_id', $this->client->id)
                    ->paginate(10);

return view('client.route_data.index', compact('routeData'))->with('client', $this->client)->with('clientProfile', $this->clientProfile);

}

I got this error RouteIndex::testIndex The response was not a view. Failed asserting that false is true. how I can fix this :)



via Chebli Mohamed

laravel unit test index function in controlller

this is my index function

public function index($alias, $profileId)
{
    $this->setClientAndClientProfile($alias, $profileId);

    $routeData = Routedata
                        ::where('client_id', $this->client->id)
                        ->paginate(10);

    return view('client.route_data.index', compact('routedata'))->with('client', $this->client)->with('clientProfile', $this->clientProfile);
}

setClientAndClientProfile is function just to check type of user and bring his profile

so how to write a test for this function?



via Chebli Mohamed

jeudi 20 avril 2017

laravel , error not find in migrate:rollback

in laravel 5.1 , vagrant, when I run

php artisan migrate 

Migrated: 2017_04_20_205912_alter_3_discounts_table

but when I run

php artisan migrate:rollback

show this message :

[Symfony\Component\Debug\Exception\FatalThrowableError]
  Class 'Alter3DiscountsTable' not found

I Have this class but I don't know why show this message!

any body can help?

** I run composer dumpautoload and show this :

[RuntimeException]                                                                                                                                               
File at "/vendor/phpunit/php-code-coverage/src/CodeCoverage/Report/Node/Directory.php" does not exist, check your classmap definitions



via Chebli Mohamed

Reading URL #hastag in Laravel controller

I have a URL that has a #hashtag on it. For example

http://ift.tt/2pFS60F

In my routes I would have

Route::get('/foo/{loc}', ['uses' => 'FooController@show']);

In my controller I would have

public function show($loc)

What I want to be able to do is read the # value 'tab2' in my controller, but the value of $loc will always be 'location1'. How can I extract the hash value?



via Chebli Mohamed

mercredi 19 avril 2017

Merge two hasOne relation in laravel - Eloquent

public function relationWithId()
{
   return $this->hasOne('App\RelatedProduct', 'product_id', 'id');
}

public function relationWithParent()
{
    return $this->hasOne('App\RelatedProduct', 'product_id', 'parent_id');
}

I have two table one is product and secound is RelatedProduct where related product is connected with products.id and sometime with product.parent_id

so need a third relation where I can merge about both like this

public function relationProduct()
{
   /*****/
}

thanks in advance



via Chebli Mohamed

Entrust on Laravel5.1 - Database Relationship

I followed the documentation and I think the data that has been save into my database is going to be a link and if I click it, I will be redirected in a specific record. Please see the image below.

enter image description here

..The two encircled with red has to be clickable, but it wasn't. Why is that? Please take a look at my code below:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class EntrustSetupTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return  void
     */
    public function up()
    {
        // Create table for storing roles
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('display_name')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });

        // Create table for associating roles to users (Many-to-Many)
        Schema::create('role_user', function (Blueprint $table) {
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();

            $table->primary(['user_id', 'role_id']);
        });

        Schema::table('role_user', function(Blueprint $table){
            $table->foreign('user_id')->references('id')->on('users')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')
                ->onUpdate('cascade')->onDelete('cascade');
        });

        // Create table for storing permissions
        Schema::create('permissions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('display_name')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });

        // Create table for associating permissions to roles (Many-to-Many)
        Schema::create('permission_role', function (Blueprint $table) {
            $table->integer('permission_id')->unsigned();
            $table->integer('role_id')->unsigned();

            $table->foreign('permission_id')->references('id')->on('permissions')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')
                ->onUpdate('cascade')->onDelete('cascade');

            $table->primary(['permission_id', 'role_id']);
        });
    }

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



via Chebli Mohamed

Repeatitive loops within foreach

I have a problem with the looping that iterates three times.Its been hours that i am looking solution why it loops trice.It might be the best idea to find help here to speed up my project.See the sample results below the expected output and the result with incorrect output.Hope anyone could help me here.Thank you in advance.

array:5 [▼
   "1.4" => 40 
   "1.401" => 42 
   "1.5" => 38 
]

array:5 [▼
    "40" => 1.4
    "42" => 1.4
    "38" => 1.5
   ]
    $count1 = 0;

    $percentage = 1.1;
    $last_scholar_gpa = 0;
    foreach ($scho as $scholar_id2) {
    foreach ($all_list_GPA as $scholar_GPA) {
        $scholar = Scholar::find($scholar_id2);
        $crits = New Criteria;
        $crits->scholar_id = $scholar->scholar_id;
        $crits->scholarship_id = $scholarship_id;
            if ($last_scholar_gpa != $scholar_GPA) {
                $percentage = $percentage - 0.1;
                $total_points_two = $scholarship->scholarship_points_two * $percentage;
                $crits->criteria_gpa = $total_points_two;

            $last_scholar_gpa = $scholar_GPA;
            }else{
                $percentage = $percentage;
                $total_points_two = $scholarship->scholarship_points_two * $percentage;
                $crits->criteria_gpa = $total_points_two;

            $last_scholar_gpa = $scholar_GPA;
            }

        $crits->save();
        }   

        $count1++;
    } 

This is supposed to be the result:

id    criteria_gpa
40          25.00
42          25.00
38          22.50

The current result which were saved in the database (but wrong computation)

id    criteria_gpa
40          25.00
40          25.00
40          22.50
42          20.00
42          20.00
42          17.50
38          15.00
38          15.00
38          12.50



via Chebli Mohamed

laravel model factory remove variable name from factory

Can I remove the name from this model factory?

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

because i write unit test and create user in it and i get this error PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'field list' my user model is consist of firstname and lastname



via Chebli Mohamed

Computation inside foreach loop

I have a problem within the loop with correct computation.Right below is the original array which is to flipped.See result of second dd of the array. As you can see,the value is already sorted.Here comes the problem inside the foreach loop.My logic seems confusing even if my expected result is simple. See the following results below.Hope anyone could help me figuring it out the most easy way just come up the expected output.

array:5 [▼
   "1.4" => 40 
   "1.4" => 42 
   "1.5" => 38 
   "1.5" => 39 
   "1.6" => 41 
]

    $count1 = 0;
    foreach ($scho as $scholar_id2) {
        $scholar = Scholar::find($scholar_id2);
        $crits = New Criteria;
        $crits->scholar_id = $scholar->scholar_id;
        $crits->scholarship_id = $scholarship_id;
        $crits->save();
        $count1++;
    }

result of flipped array of index and value

array:5 [▼
    "40" => 1.4
    "42" => 1.4
    "38" => 1.5
    "39" => 1.5
    "41" => 1.6
]
    $list1 = Criteria::where('scholarship_id','=',$scholarship->scholarship_id)->get();
    $all_id = [];
    foreach ($list1 as $id) {
        array_push($all_id, $id->criteria_id);
    }

        $last_scholar_gpa = 0;
        $percentage = 1.2;
        foreach ($all_id as $id2) {
        $crits = Criteria::find($id2);
        foreach ($all_list_GPA as $scholar_GPA) {

        if($percentage > 0.5 && $last_scholar_gpa != $scholar_GPA)
        $percentage = $percentage - 0.1;

        $total_points_two = $scholarship->scholarship_points_two * $percentage;
        $crits->criteria_gpa = $total_points_two;
        }

        $crits->save();

        $last_scholar_gpa = $scholar_GPA;

    }

This is value of scholarship_points_two = 25

This is supposed to be the result:

id    criteria_gpa
40          25.00
42          25.00
38          22.50
39          22.50
41          20.00

The current result which were saved in the database (but wrong computation)

id    criteria_gpa
40          22.50
42          17.50
38          12.50
39          7.50
41          2.50



via Chebli Mohamed

Upload video from s3 to youtube

I want to upload a video from s3 to youtube. Now i am using service account and get access token but when I upload video to youtube server return error:

[Google_Service_Exception]              


{                                       
   "error": {                             
    "errors": [                           
     {                                    
      "domain": "youtube.header",         
      "reason": "youtubeSignupRequired",  
      "message": "Unauthorized",          
      "locationType": "header",           
      "location": "Authorization"         
     }                                    
    ],                                    
    "code": 401,                          
    "message": "Unauthorized"             
   }                                      
  }  

This is my code:

    $googleClient = new Google_Client();
    $googleClient->useApplicationDefaultCredentials();

    $googleClient->setApplicationName('XXX');
    $googleClient->setClientId('XXX');
    $googleClient->setClientSecret('XXXX');
    $googleClient->addScope(\Google_Service_YouTube::YOUTUBE);
    $googleClient->setAccessType('XXX');
    $googleClient->setApprovalPrompt('auto');
    $googleClient->setDeveloperKey('XXX');

    $stringAccessToken = $googleClient->fetchAccessTokenWithAssertion()['access_token'];


    $googleClient->setAccessToken($stringAccessToken);


    $youtube = new \Google_Service_YouTube($googleClient);
....

I don't know Can use service account to upload a video to youtube api V3?

Please help me . thank you so much.



via Chebli Mohamed

mardi 18 avril 2017

Ranking retrieved data using loop in laravel

I have a collection of data $all_scholar_grade that hold values of grades.These grades in the second collection are not arrange from the highest order.This cant be done in ascending order because it is not a query.How do i arrange it or rank from the highest to lowest using loop or foreach? I'd tried figuring it out but i cant get the logic.Hope anyone could help me here.

    $all_scholar_id = array();
    $all_scholar_grade = array();
    $count = 0;
    foreach ($card_id as $id) {

        $card = ScholarCard::find($id);
        if ($card->scholar_grade_level == 12) {
            if ($card->scholar_GPA == 100 || $card->scholar_GPA == 99 || $card->scholar_GPA == 98 || $card->scholar_GPA == 97 || $card->scholar_GPA == 96 || $card->scholar_GPA == 95 ) {
             $card_gpa = 1.0;
            }elseif ($card->scholar_GPA == 94) {
                $card_gpa = 1.1;
            }elseif ($card->scholar_GPA == 93) {
                $card_gpa = 1.2;
            }elseif ($card->scholar_GPA == 92) {
                $card_gpa = 1.3;
            }elseif ($card->scholar_GPA == 91) {
                $card_gpa = 1.4;
            }elseif ($card->scholar_GPA == 90) {
                $card_gpa = 1.5;
            }elseif ($card->scholar_GPA == 89) {
                $card_gpa = 1.6;
            }elseif ($card->scholar_GPA == 88) {
                $card_gpa = 1.7;
            }elseif ($card->scholar_GPA == 87) {
                $card_gpa = 1.8;
            }elseif ($card->scholar_GPA == 86) {
                $card_gpa = 1.9;
            }elseif ($card->scholar_GPA == 85) {
                $card_gpa = 2.0;
            }elseif ($card->scholar_GPA == 84) {
                $card_gpa = 2.1;
            }elseif ($card->scholar_GPA == 83) {
                $card_gpa = 2.2;
            }elseif ($card->scholar_GPA == 82) {
                $card_gpa = 2.3;
            }elseif ($card->scholar_GPA == 81) {
                $card_gpa = 2.4;
            }elseif ($card->scholar_GPA == 80) {
                $card_gpa = 2.5;
            }elseif ($card->scholar_GPA == 79) {
                $card_gpa = 2.6;
            }elseif ($card->scholar_GPA == 78) {
                $card_gpa = 2.7;
            }elseif ($card->scholar_GPA == 77) {
                $card_gpa = 2.8;
            }elseif ($card->scholar_GPA == 76) {
                $card_gpa = 2.9;
            }elseif ($card->scholar_GPA == 75) {
                $card_gpa = 3.0;
            }elseif ($card->scholar_GPA <= 74) {
                $card_gpa = 5.0;
            }
        }else{
            $card_gpa = $card->scholar_GPA;
        }
        if ($card_gpa >= $scholarship->scholarship_gpa_to || $card_gpa <= $scholarship->scholarship_gpa_from) {
            $all_scholar_grade[] = $card_gpa;

            $all_scholar_id[] = $card->scholar_id;
        }

        $count++;         
    }

Output of my dd($all_scholar_id, $all_scholar_grade)

array:3 [▼
  0 => 29
  1 => 34
  2 => 35
]

array:3 [▼
  0 => 1.5
  1 => 2.1
  2 => 1.3
]   



via Chebli Mohamed

Unknown column in database by eloquent query

I am creating a criteria for Señor high and tertiary. Im trying to retrieve data that meets the condition but my query resulted to an error.

Example:

If this child is grade 12 and his final grade point average is 85 then this should be converted to college grading system(see conditions).

See the error below.Anyone knows why im getting this error and why saying unknown column even if i dont have such column?

SQLSTATE[42S22]: Column not found: 1054 Unknown column '1.5' in 'where clause' (SQL: select * from scholar_cards where scholar_card_id = 93 and 1.5 between 1.2 and 1.9)

    $count = 0;
    foreach ($card_id as $id) {

        $card = ScholarCard::find($id);
        if ($card->scholar_grade_level == 12) {
            if ($card->scholar_GPA == 100 || $card->scholar_GPA == 99 || $card->scholar_GPA == 98 || $card->scholar_GPA == 97 || $card->scholar_GPA == 96 || $card->scholar_GPA == 95 ) {
             $card_gpa = 1.0;
            }elseif ($card->scholar_GPA == 94) {
                $card_gpa = 1.1;
            }elseif ($card->scholar_GPA == 93) {
                $card_gpa = 1.2;
            }elseif ($card->scholar_GPA == 92) {
                $card_gpa = 1.3;
            }elseif ($card->scholar_GPA == 91) {
                $card_gpa = 1.4;
            }elseif ($card->scholar_GPA == 90) {
                $card_gpa = 1.5;
            }elseif ($card->scholar_GPA == 89) {
                $card_gpa = 1.6;
            }elseif ($card->scholar_GPA == 88) {
                $card_gpa = 1.7;
            }elseif ($card->scholar_GPA == 87) {
                $card_gpa = 1.8;
            }elseif ($card->scholar_GPA == 86) {
                $card_gpa = 1.9;
            }elseif ($card->scholar_GPA == 85) {
                $card_gpa = 2.0;
            }elseif ($card->scholar_GPA == 84) {
                $card_gpa = 2.1;
            }elseif ($card->scholar_GPA == 83) {
                $card_gpa = 2.2;
            }elseif ($card->scholar_GPA == 82) {
                $card_gpa = 2.3;
            }elseif ($card->scholar_GPA == 81) {
                $card_gpa = 2.4;
            }elseif ($card->scholar_GPA == 80) {
                $card_gpa = 2.5;
            }elseif ($card->scholar_GPA == 79) {
                $card_gpa = 2.6;
            }elseif ($card->scholar_GPA == 78) {
                $card_gpa = 2.7;
            }elseif ($card->scholar_GPA == 77) {
                $card_gpa = 2.8;
            }elseif ($card->scholar_GPA == 76) {
                $card_gpa = 2.9;
            }elseif ($card->scholar_GPA == 75) {
                $card_gpa = 3.0;
            }else {
                $card_gpa = 5.0;
            }
        }else{
            $card_gpa = $card->scholar_GPA;
        }
        $scholar_id2s = ScholarCard::where('scholar_card_id','=',$card->scholar_card_id)->whereBetween($card_gpa,[$scholarship->scholarship_gpa_to, $scholarship->scholarship_gpa_from])->get();

        $count++;         
    }



via Chebli Mohamed

dimanche 16 avril 2017

Cannot pass blade variable in onChange function in select

I have a select option as below.

 @foreach($destinations as $destination)
{!! Form::select('destination', $counts, $destination->ordering, array('onchange'=>'fetch_select(this.value,$destination->id)') !!}
@endforeach

I am trying to pass a variable called $destination->id in onchange function as above which will trigger a function in java-script later on. However, I am not able to pass this variable like i have done above. Throws a lot of errors. It says

Uncaught SyntaxError: Unexpected token >

in the inspect console.

I tried with:

 'onchange'=>'fetch_select(this.value,destination->id)'
'onchange'=>'fetch_select(this.value,"$destination->id")'
'onchange'=>'fetch_select(this.value,(destination->id))'
'onchange'=>'fetch_select(this.value,($destination->id))'

None of them works .. How can i get around this. With Regards



via Chebli Mohamed

mercredi 12 avril 2017

PHP - URL gets malformed during redirect

So, I have an image link that has this href:

http://ift.tt/2nFL0w1

This is processed like so (I use laravel):

function out (Request $request) {

    $url = $request->target;

    $qs = $request->except('target');
    if ( !empty($qs) ) {
        $url .= strpos($url, '?') !== false ? '&' : '?';
        $url .= http_build_query($qs);
    }

    return redirect($url);
}

Most of the time, this works. However, lately, we've been experiencing an issue where param1 and param2 are attached to the URL in a seemingly infinite loop causing us to hit a 414 Request URI too long Error.

The problem is that it happens so randomly that I really don't know where to check because I added a checker before the return statement.

if ( substr_count($url, 'param1') > 1 ) {
    $file = storage_path() . '/logs/logger.log';
    $log = "[ " . date("d-m-Y H:i:sa") . " ] [ {$request->ip()} ] - {$url} \n";
    file_put_contents($file, $log, FILE_APPEND);
}

And it hasn't logged a single hit. Even after our testers experienced the bug.

Is it possible that the receiving application is breaking the URL somehow? What information should I be looking out for? Have you seen an issue like this before?

Is it the http_build_query that could be causing this and that my checker just doesn't work as expected (though, I did test it and it logged my test URL).

Any help on the matter would be great.



via Chebli Mohamed

mardi 11 avril 2017

Modeling and Seeding Difference in Laravel

I am confused what's the difference of seeding and by using model in laravel which both saving data into the database. Why not just use Model? or Why not Seed? When and why they used?



Answers will be appreciated.



via Chebli Mohamed

lundi 10 avril 2017

Laravel 5.1 get Orders that have been completed

I have an Order model and an OrderStatus model. An Order can have multiple statuses but only one 'currentStatus' (this is defined by the created_at timestamp on the pivot table order_status).

Order model (orders table)

OrderStatus model (order_statuses table)

order_status pivot table (order_status table)

How can I define a query scope (or similar) to get all the Orders of a certain status; i.e. 'completed'?

The following doesn't work as it checks all statuses of the orders, even ones in the past.

public function scopeCompleted($query)
{
    return $query->whereHas('statuses', function ($q) {
        $q->where("order_statuses.status", 'complete');
    });
}



via Chebli Mohamed

vendredi 7 avril 2017

User creation does not work on laravel 5.1

actually i try to migrate some users from a excel file (.xlsx) to login in my aplication. But the code doesn't work. The strange part is that the same code it's implemented for migrate payroll from a excel file (.xlsx) and this one work. I try many options, change some code, but it doesn't work. Maybe I'm letting some error out and someone else can see it. I would appreciate the help.

My ImportController.php from users

public function cargar_datos_users(Request $request)
    {
        $file= $request->file('file');
        $original_name=$file->getClientOriginalName();
        $r1=Storage::disk('files')->put($original_name,  \File::get($file) );
        $route=  storage_path('files') ."/". $original_name;
        if($r1)
        {
            Excel::selectSheetsByIndex(0)->load($route, function($sheet)
            {
                $sheet->each(function($row)
            {
                $user = new User;
                $user->full_name = $row->nombreempleado;
                $user->user = $row->empleado;
                $user->password = bcrypt($row->empleado);
                $perfil = 1;
                $user->perfil = $perfil;
                $user->save();
            });
            return view("administrator.contracts.adminpayrolls")->with("msj","Usuarios Cargados Correctamente");             
        }
        else
        {
            return view("administrator.contracts.adminpayrolls")->with("msj","Error al subir el archivo");
        }
    }

My ImportController.php from payroll

public function cargar_datos_payrolls(Request $request)
    {
        $file= $request->file('file');
        $original_name=$file->getClientOriginalName();
        $r1=Storage::disk('files')->put($original_name,  \File::get($file) );
        $route=  storage_path('files') ."/". $original_name;
        if($r1)
        {
            Excel::selectSheetsByIndex(0)->load($route, function($sheet)
            {
                $sheet->each(function($row)
                {
                    $payroll = new Payroll;                                             
                    $payroll->lapso = $row->lapso;
                    $payroll->concept_payroll = $row->conceptonomina;
                    $payroll->payroll_concept_name = $row->nombreconceptonomina;
                    $payroll->id_employee = $row->empleado;
                    $payroll->hours = $row->horas;
                    $payroll->value = $row->valor;
                    $payroll->date_generation = $row->fechageneracion;
                    $payroll->date_from = $row->fechadesde;
                    $payroll->date_to = $row->fechahasta;
                    $payroll->balance_fee = $row->saldocuota;
                    $estado = 1;
                    $payroll->estado = $estado;
                    $payroll->save();
                });
            });
            return view("administrator.contracts.adminpayrolls")->with("msj","Usuarios Cargados Correctamente");             
        }
        else
        {
            return view("administrator.contracts.adminpayrolls")->with("msj","Error al subir el archivo");
        }
    }

My app/User.php

class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    protected $table = 'users';

    protected $fillable = ['full_name', 'user', 'password','perfil'];

    protected $hidden = ['password', 'remember_token'];
}

The plugin for migrate from excel is http://ift.tt/1n2QXpH As I said, the same structure work on payroll migrate, but don't work on users migrate, any comments will be appreciate.



via Chebli Mohamed

Datatables response 500 error internal server when return from multiple tables

i get this error when i use searchbox Datatables warning

i have join my tables with this query

$query = LoginQuarter::join('wholesalers','login_quarter.username','=','wholesalers.user_id') ->select('wholesalers.id as wholesaler_id','wholesalers.name as name', 'login_quarter.quarter','login_quarter.years', 'login_quarter.target', 'login_quarter.updated_at');

And this is the return function enter image description here

I will not get that error if i comment in line wholesaler_id (line 82) and name (line 83) but i need to display that.

This is my first post in this forum, i hope i will get more knowledge from your help. Thankyou.



via Chebli Mohamed

jeudi 6 avril 2017

Decode OpenID id_token - JWT

I have an id_token from OpenID Auth Server, when I test decode it on :

https://jwt.io/

I got

enter image description here

I'm wondering, if there a way to achive this decode programatically?

Is there a Laravel framework that will help me achieve that?



via Chebli Mohamed

Laravel 5.1 Job dispatches other jobs - how to manage and keep track?

Within one job I would like to dispatch and manage other smaller jobs. When the last child job has finished, I would like to notify the parent job that all were successful.

If for some reason the child job failed, then also notify the parent accordingly.

Currently the parent job finishes as the first child job is dispatched and therefore no longer has visibility of what happens next. Previously I didn't have child jobs and just executed the code within the single parent job however, these aren't insufficient tasks and can vary drastically in execution time so this wasn't a viable solution.

Am I missing something?



via Chebli Mohamed

lundi 3 avril 2017

ow to insert data into tables related to a single form?

Good. I would like help. I do not know how to insert data into tables related to a single form in laravel

This is my model User:

use Authenticatable, Authorizable, CanResetPassword;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['name', 'email'];

public function credencials()
{
    return $this->hasOne('App\Credencial');
}

And this is the credential model:

protected $table = 'credencials';

protected $fillable = ['clave'];

public function users()
{
    return $this->hasOne('App\User');
}

What I do not know is how I keep the data in the related tables. help me please



via Chebli Mohamed

Selecting checkbox "All" to select all underlying checkboxes in javascript

I have a checkbox with JavaScript but if click checkall, the other checkboxes wont select.What am I missing here?Hope anyone could tell me what went wrong. I must be missing something with JavaScript but really I dont have any idea.I'd already done my research and the best resort to lane on is here.Hope someone could enlighten me here.

    function checkAll(checkname, bx) {
        for (i = checkname.length; i--; )
            checkname[i].checked = bx.checked;
    }
        


    function checkPage(bx){                    
        for (var tbls = document.getElementsByTagName("table"),i=tbls.length; i--; )
            for (var bxs=tbls[i].getElementsByTagName("input"),j=bxs.length; j--; )
               if (bxs[j].type=="checkbox")
                   bxs[j].checked = bx.checked;
    }
  <table border="1" name ="table">

    <tr>
        <td name ="list00">
            <label name ="list00">
                <input type="checkbox" name="Check_ctr" value="yes" onClick="checkAll(document.list00.link, this)"><b>Check All</b><dd>
                <input type="checkbox" name="link" value="something.com">something.com<dd>
                <input type="checkbox" name="link" value="something.com">something.com<dd>
            </label>
        </td>
        <td><label name ="list01">
                <input type="checkbox" name="Check_ctr" value="yes" onClick="checkAll(document.list01.link, this)"><b>Check All</b><dd>
                <input type="checkbox" name="link" value="something.com">something.com<dd>
                <input type="checkbox" name="link" value="something.com">something.com<dd>        
            </label></td>
    </tr>
    <tr>
        <td><label name ="list10">
                <input type="checkbox" name="Check_ctr" value="yes" onClick="checkAll(document.list10.link, this)"><b>Check All</b><dd>
                <input type="checkbox" name="link" value="something.com">something.com<dd>
                <input type="checkbox" name="link" value="something.com">something.com<dd>    
            </label></td>
        <td><label name ="list11">
                <input type="checkbox" name="Check_ctr" value="yes" onClick="checkAll(document.list11.link, this)"><b>Check All</b><dd>
                <input type="checkbox" name="link" value="something.com">something.com<dd>
                <input type="checkbox" name="link" value="something.com">something.com<dd>    
            </label></td>
    </tr>
    </table>


via Chebli Mohamed

dimanche 2 avril 2017

Laravel Payment Gateway

my website would be needing a payment gateway.

Stripe is not available in my country and want to use www.2checkout.com

i was planning to use this (http://ift.tt/2nyZcTc). but its under development and i think it might give me limited functions.

i plan on using the 2checkout library and using their documentation.

can someone tell me what is the clean/proper way on including the library on laravel?

thank you.



via Chebli Mohamed

SFTP Upload Laravel 5

I’m trying to upload files to my staging server running Linux Ubuntu.

I tried follow everything in this post = http://ift.tt/1XqtqE3 . I am on Laravel 5.1.

I configured my remote.php like this :

'connections' => [
        'production' => [
            'host'      => '45.55.88.88',
            'username'  => 'root',
            'password'  => '',
            'key'       => '/Users/bheng/.ssh/id_rsa', //Try : public | private
            'keytext'   => '',
            'keyphrase' => '******',
            'agent'     => '', //Try : empty | enabled | disabled,
            'timeout'   => 10,
        ],
    ],

I tried test it like this in my project :

SSH::run('date', function($line) {dd($line); });

I kept getting :

Unable to connect to remote server.


I tried it on my Mac OS Terminal

sftp root@45.55.88.88

It’s working fine, I got

sftp> ls
Desktop       Documents     Downloads     Music         Pictures      Public        Templates     Videos        dead.letter


What did I do wrong or forget ? What elses should I try ?

Do I need to do anything on my /etc/ssh/sshd_config ?

Can someone please help me out if you’re done this before ?



via Chebli Mohamed