mercredi 31 janvier 2018

Laravel - Async Ajax Requests are blocked

I tried the whole day to get a problem with two ajax requests solved.

The purpose of my script is to start a process by an ajax call while another ajax call is getting the status/progress of this process.

My script is based on PHP Ajax Progress Bar.

I am using Laravel for this.

This my index view.

<!DOCTYPE html>
<html lang="">
<head>
    <meta name="csrf-token" content="">
</head>
<body>
<div id="progress"></div>
<div id="message"></div>

<!-- Scripts -->
<script src=""></script>
<script type="text/javascript">
    var timer;
    var index=0;

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    function refreshProgress() {
        $("#message").text("Refreshing...." + (index++)); //debug line
        $.ajax({
           url: "/status",
           async: true,
           success: function(data){
               $("#progress").html(data)
            if(data >= 100) {
                window.clearInterval(timer);
                timer= window.setInterval(completed, 1000);
            }},
            error: function (xhr, ajaxOptions, thrownError) {
               console.log(xhr.status);
                window.clearInterval(timer);
                timer= window.setInterval(completed, 1000);
            }
        });
    }

    function completed() {
        window.clearInterval(timer);
    }

    $(document).ready(function() {
        $.ajax({url: "/start", async: true});
        timer= window.setInterval(refreshProgress, 1000);
    });

</script>
</body>
</html>

After the document is loaded the url start is called by an ajax request.

Every second another ajax call is initiated to call the url status.

Inside the controller nothing special is happening.

public function start(Request $request) {

        Log::info("Start....");

        foreach(range(0, 20) as $number) {

            sleep(1);

        }
    }

    public function status(Request $request) {

        return json_encode(112);
    }

The start method is running a loop, while the status method is simply returning a number.

I liked to prevent anything that might block the process like this Solving Concurrent Request Blocking in PHP.

But what I see in my browser is that after the start URL is called all requests to status are queued. As soon as the start method finished all status requests are processed.

I am not able to get the result of the status request while the start method is running.

Pending network traffic

I am not getting the problem. What did I missed?



via Chebli Mohamed

Laravel Nginx GPGME PGP error, gnupg found but dont work

I have installed the GPGME on Debian with nginx, for Laravel 2FA Login PGP Encryption.

After i have used this, all works fine

./Configure
make
make install

but if i make an Test with sudo make test i get this error:

FAILED TEST SUMMARY
---------------------------------------------------------------------
encrypt and decrypt a text [tests/gnupg_oo_encrypt.phpt]
encryptsign and decryptverify a text [tests/gnupg_oo_encryptsign.phpt]
export a key [tests/gnupg_oo_export.phpt]
sign a text with sigmode SIG_MODE_CLEAR [tests/gnupg_oo_sign_clear.phpt]
sign a text with mode SIG_MODE_DETACH [tests/gnupg_oo_sign_detach.phpt]
sign a text with mode SIG_MODE_DETACH and without armored output [tests/gnupg_oo_sign_detach_nonarmor.phpt]
sign a text with mode SIG_MODE_NORMAL [tests/gnupg_oo_sign_normal.phpt]
sign a text with mode SIG_MODE_NORMAL and without armored output [tests/gnupg_oo_sign_normal_noarmor.phpt]
encrypt and decrypt a text [tests/gnupg_res_encrypt.phpt]
encryptsign and decryptverify a text [tests/gnupg_res_encryptsign.phpt]
export a key [tests/gnupg_res_export.phpt]
sign a text with sigmode SIG_MODE_CLEAR [tests/gnupg_res_sign_clear.phpt]
sign a text with mode SIG_MODE_DETACH [tests/gnupg_res_sign_detach.phpt]
sign a text with mode SIG_MODE_DETACH and without armored output [tests/gnupg_res_sign_detach_nonarmor.phpt]
sign a text with mode SIG_MODE_NORMAL [tests/gnupg_res_sign_normal.phpt]
sign a text with mode SIG_MODE_NORMAL and without armored output [tests/gnupg_res_sign_normal_noarmor.phpt]

Can someone help me please?

Thanks



via Chebli Mohamed

Laravel external app login session does not persist

Hi I'm trying to do a login function in a external app, its works but the session does not persists when refresh.

function laravelLogin($id)
{
    require $_SERVER['DOCUMENT_ROOT'].'../laravel/vendor/autoload.php';
    $app = require_once $_SERVER['DOCUMENT_ROOT'].'../laravel/bootstrap/app.php';

    $app->make(Illuminate\Contracts\Http\Kernel::class)
        ->handle(Illuminate\Http\Request::capture());

    $user = $app->make('App\Models\User')
                    ->where('id',$id)
                    ->first();

    $app->Auth::login($user);

}

Thanks!



via Chebli Mohamed

Laravel automatize routes

I am using some routes in my laravel App like this:

Route::get('/structure', 'Superuser\StructureController@index'); 

So if I go to localhost/myproject/structure I am using StructureController and it's method "index". Now I would like to use another features, like add, update, delete, reorder etc... Is there any simple way, that I needn't to write:

Route::get('/structure/add', 'Superuser\StructureController@add');
Route::get('/structure/update/{url}', 'Superuser\StructureController@update');
Route::get('/structure/delete/{url}', 'Superuser\StructureController@delete');

If is this possible, I would like to use ::get for everything. Thank you a lot.



via Chebli Mohamed

php artisan migrate. Multiple primary key defined

My Problem

I'm building my first api using laravel and am getting a multiple primary key defined error while trying to run php artisan migrate I don't understand how I have defined multiple primary keys. Every time I run a migrate I get these errors php artisan migrate error.

My Troubleshooting

I thought since autoIncrementing() can only be used for a primary key that maybe that defined it as a primary key, so I altered $table->increments('bus_id')->autoIncrement()->primary(); to $table->increments('bus_id')->autoIncrement(); and $table->increments('bus_id')->autoIncrement();

Every time I had tried to run my migrations I dropped my database and re-created it and tried to run my migrations again (so it was a new database every time with no corrupt data) but still didn't make a difference.

I checked my Connection.php that was mentioned in the picture of my error code above but didn't see anything pertaining to any primary keys.

My Question

My code is below, can someone help me understand how I'm making double primary keys?

<?php

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

class CreateBusinessTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('business', function (Blueprint $table) {
            $table->increments('bus_id')->autoIncrement()->primary();
            $table->string('bus_name');
            $table->string('bus_address');
            $table->string('bus_city');
            $table->string('bus_prov');
            $table->string('bus_postal');
            $table->string('bus_phone');
            $table->string('bus_email');
            $table->string('bus_password');
            $table->double('max_donatable', 10, 2);
            $table->integer('cashback_percent');
            $table->binary('bus_cover_photo'); 
            $table->binary('bus_profile_pic'); 
            $table->timestamps();
            $table->rememberToken(); 
            $table->engine = 'InnoDB';   
        });
    }

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

Please note there are similar questions here on Stack overflow which I have also tried their solutions without any success



via Chebli Mohamed

Unable to soft delete record when primaryKey column name is set to anything other than 'id'

I'm trying to solve this error since yesterday. My primary key column name is 'departmentId'

Whenever I try to delete the record by the code:

$department = departments::find($departmentId);
$department->delete();

It gives me a "converstion to string" error. As soon as I changed the Primary key column name to "id", it is working properly.



via Chebli Mohamed

Laravel ,font-family works on Ubuntu but not on Debian

I have an Problem.

I have coded an Laravel 5 Script on Ubuntu 17 and want use it now on Debian.

But the font font-family is not the same and it looks not good.

On Ubuntu i have installed on my Machine all Fonts i need and add it in my Body CSS:

body {
  font-family: "Roboto Mono", Helvetica, Arial;

Now i have installed also on Debian the Font files for the System and restart the Browser but the Laravel script dont use it, why? Or have i forget something?

Thanks



via Chebli Mohamed

Adding flags and switches to Artisan commands, Laravel 5.5+

I am fairly new to the command line but have successfully used php artisan make:command MyCommand. I have also added a command in a vendor package I've created.

What I'm not clear on is how to do things like this:

php artisan mypackage:mycommand -f --user="jhendrix@gmail.etc" --label "This is Jimmy Hendrix"

Where -f is a defined switch, and --user or --label are longer tags which take an argument in themselves.

In other words, how do I configure/map these options and flags, and how do I fetch them in my handle() function?



via Chebli Mohamed

pulling down the .git folder with a package

I now have and maintain a package on Packagist.org, which I've specified in my Laravel 5.5 project's composer.json file. It's my first package and is pulling down successfully.

I have also specified automated update hook between GitHub and Packagist (which is pretty cool), but there is one thing which would make the process more convenient:

Is it possible to pull the .git folder with the package as well? This way I can test and develop my package in a project real-time, do a git commit and git push, and I'm done.



via Chebli Mohamed

Laravel ignore_user_abort() not working

I want to run a function in background, that doesn't stop until process completes.

In core PHP i was using ignore_user_abort() function and file kept running in background.

But now i am converting my site to laravel, i tried adding ignore_user_abort(true) in my controller below namespace, But file is only getting executed for few seconds.

I tried increasing max_execution_time in php.ini file but nothing happened.



via Chebli Mohamed

Laravel 5 upload files to s3 on wrong url

I implements uploads files to s3 in Laravel 5, when upload file it give error message: Error executing \"PutObject\" on ......, I found it happen because the url try to access is wrong, the url is :

https://{buckets}.{s3 domain}/{buckets}/{filename}

, before s3 domain why laravel put buckets name on url? the correct url should be

https://{s3 domain}/{buckets}/{filename}

, so how to fix it?



via Chebli Mohamed

set images using flexbox css issue

I tired to set images(size are different) using flexbox css. Please check screenshot below and let me know what is going wrong.

blade template

         <div class="parent-block">
            <div class="parent">
                @forelse($portfolios as $portfolio)
                    <div class="view view-tenth child-block">
                      <img src="" class="img-responsive">
                        <div class="mask">
                            <h2></h2>
                            <p></p>
                            <a href="" target="_blank" class="info">SEE DETAILS</a>
                        </div>
                    </div><!-- /.flex-block__area -->
                @empty
                    <p class="text-center">No Portfolio found!</p>
                @endforelse
            </div><!-- /.parent -->
        </div><!-- /.parent-block -->

CSS

 .parent-block {
     margin: 0 auto;
     overflow: hidden;
 }
 .parent {
    width: auto;
    display: flex;
    flex-wrap: wrap;
  }
  .parent img {
     width: 100%;
  }
  .child-block{
     margin: 5px;
  }

Current Output enter image description here

I need this output enter image description here



via Chebli Mohamed

How to use MySQL built-in functions in Laravel DB::raw()

I am using an sql query like the following with the MySQL built in ADDDATE() function in Laravel Query Builder to increment the date by 1 day.

$sql = "UPDATE my_table
        SET date_col = ADDDATE(date_col, INTERVAL 1 DAY)
        WHERE id = {$the_id}";

DB::update($sql);

This is working fine and there is no reason to really change it. However, I first tried to use Query Builder with DB::raw as follows.

DB::table('my_table')
   ->where('id',$the_id)
   ->update(['date_col'=> DB::raw(ADDDATE(date_col, INTERVAL 1 DAY)]);

Is it possible to use the MySQL functions in this way? Is my syntax wrong or what?



via Chebli Mohamed

validate all arrayitems except last in laravel

With the asterisk I can validate all array items, like this:

'event_time_start.*' => 'required|date_format:G:i',

But I want apply this validation rule on all items, except the last one. How can I achive this?



via Chebli Mohamed

How to develop auto callback functionality for clickatell SMS in Laravel 5.5?

I've developed Auto responder functionality for clickatell SMS API in Larvel 5.5 but it's not working !

Can anyone help me to find out how can i make it working ?



via Chebli Mohamed

Laravel 4 Carbon trailing data error

I am getting the following error when retrieving a timestamp field from my database and converting it to json for response.

InvalidArgumentException Trailing data

the table has a created_at field which is a postgres timestampz field i.e timestamp with timezone I guess.

and even if I access the field via $column->created_at

it's throwing that error.



via Chebli Mohamed

Attach flash message to file download response in Laravel

In my code, I am returning a zip file as a streamed response:

return response()->stream(function() use ($zip){
            $zip->finish();
        });

I would like to also return a status message saying "Your zip download has started" along with the response, but I can't find a way of doing it properly in Laravel.

I am using Laravel 5.2



via Chebli Mohamed

API Gives Header 400 & Angular Stops Working

I have an API built on Laravel 5.0 that communicates with Angular on the front end. Whenever a user enters wrong data, API gives an error response with a status code of 400 (Bad Request), an error appears on the Developer's Console and this causes Angular to stop working anymore.

This is a sample error response from the API side:

$response = array();
$response['error'][] = $error;
$response['status'] = 400;
return (new Illuminate\Http\Response($response, $response['status']))
    ->header('Content-Type', 'application/json');

Angular gets the error as follows:

sampleRequest(sample_var: number){
    const url = `${this.apiUrl}`;

    return this.http
        .post(url, JSON.stringify({var: sample_var}), {headers: this.headers})
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);
}

private handleError (error: Response | any) {
    let errMsg: string;

    if (error instanceof Response) {
        const body = error.json() || '';

        errMsg = (body.error) ? body.error || JSON.stringify(body) : $.map(body, function(value, index){ return [value]; });
    }

    else
        errMsg = error.message ? error.message : error.toString();

    return Observable.throw(errMsg);
}

To be clear, I have a validation on the API side that checks whether variable var is number or not, for instance. User enters a string on the associated input field and API gives an error response as mentioned at the beginning.

An error as below appears on the developer's console:

zone.js:1990 POST example.com/api/sample-request 400 (Bad Request)

After that error, Angular stops working, like when javascript stops working if a javascript error occurs.

Interestingly, it does not stop working if the thrown error has a status code of 500 (Internal Server Error).

Any help is appreciated.



via Chebli Mohamed

Laravel Auth Controller Change code for redirect

I want change in my AuthController, after the user sign in, he redirect to an 2fa site before he can visit home.

My code now:

        if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {

          $user = Auth::user();

          $user->last_seen = date('Y-m-d H:i:s', time());

          $user->save();

          return redirect()->route('home');



        } else {

          session()->flash('errormessage','Invalid password ');

          return redirect()->back();

        }

}

After the $user->last_seen = date('Y-m-d H:i:s', time()); saved he must redirect to return redirect('messagedecrypt');

Like this code:

   if (!Hash::check($request->password,$user->password) && !Hash::check($request->username,$user->username)) 
    {
      session()->flash('errormessage','Your Login Credential Are Wrong');
      return redirect()->back();
    } 
    else 
    {
      session()->flash('user_name',$request->username);
      session()->flash('user_password',$request->password);
      return redirect('messagedecrypt');
    }

}

How can i change my code now with also saving last seen?

Thanks



via Chebli Mohamed

“Unauthenticated” when consuming own API with passport?

I have installed passport as the documentation instructed and added this line the 'web' middleware:

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

and now , Iam trying to get some data using datatable ( datatables.net ) with ajax:

api.php

Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function()
{
  Route::get('/itemsData', 'DataController@getItemsData')->name('api.getItemsData');

});

in blade:

<script>
    $(document).ready(function() {
        $('#Table').DataTable({
            "order": [],
            "processing": true,
            "serverSide": true,
            "ajax": "",
            "columns": [{
                "data": "name"
            }, {
                "data": "created_at"
            }],
        });
    });
</script>

but Iam getting this as a response:

{"message":"Unauthenticated."}



via Chebli Mohamed

Laravel 5.5 "Class 'PDO' not found"

Here is the actual error

enter image description here

Actually, I have successfully run php artisan migrate:refresh, and there is no error.

Already tried the following command.

php artisan cache:clear
php artisan config:clear

composer install
composer clearcache
composer dump-autoload
php artisan clear-compiled

I also checked if pdo is installed, thru php -m and its already installed

enter image description here

I'm using CentOS.



via Chebli Mohamed

cannot load jquery datatable from controller?

This is my laravel controller to return data in jason format.data returns perfectly.but cannot load the datatable with return value.please help. i am stuck here for 2 days.

    public function doctors_appointment(Request $request){
    $doctor_id=$request->input('doctorid');
    $serial_date=Carbon::today()->toDateTimeString();
    $query = DB::table('serial_in_queues')
        ->select([DB::raw('MAX(patient_serial_no) AS patient_serial_no'), 
    DB::raw('MAX(patient_serial_time) AS patient_serial_time')])
        ->where([['doctors_id', '=', $doctor_id],
               ['patient_serial_date','=','2018-01-25']])
             ->groupBy('doctors_id')->get()->first();$data=array(array('patient_serial_time'=>$query>patient_serial_time,'dt'=>0));return json_encode($data);
}

my Ajax:

        $(document).ready(function () {
        $('#autocomplete-custom-append').autocomplete({
            serviceUrl: '',
            onSelect: function (suggestions) {
                $('#doctors_id').val(suggestions.data);

                var doctor_id = suggestions.data;
                var table = $('#time-slot').DataTable({
                    retrieve: true,
                    paginate: false,
                    sort: false,
                    info: false,
                    filter: false,
                    serverSide: true,
                    ajax: {
                        type: 'GET',
                        url: 'doctorAppointment',
                        dataType: 'json',
                        data: {doctorid: doctor_id},
                        success:function (data) {
                            console.log(data);
                            alert(data[0].patient_serial_time);
                            columns:[
                                {"data":"data[0].patient_serial_time"}
                            ]
                        }
                    },
                })
             }
        })
    })



via Chebli Mohamed

How to develop Nexmo SMS callback functionality in Laravel 5.5?

I've integrated Nexmo SMS API with Laravel 5.5. Now I have developed auto callback functionality when some one reply to the From number,but when some one try to reply to received SMS, it countinueously call auto callback API link as bescribed by below steps:

[1.] After Login in Nexmo account, go to the "Numbers" at the top & set "My site URL" in Webhook URL for preferred from numbers.

OR

[2.] In settings add "My site URL" in Webhook URL for Inbound Message of 'API settings'.

Can you please help me to find out how can i make to trigger webhook URL only once by each reply to SMS ?



via Chebli Mohamed

Getting value from many to many relationship in Laravel

I'm trying to get value from my tables with many to many relationship. My relation are: User:

public function roles()
    {
        return $this->belongsToMany('App\Role',"users_roles","usersid","rolesid");
}

Role:

public function users()
    {
        return $this->belongsToMany('App\User',"users_roles","usersid","rolesid");
}

I did this in my view:

@foreach($users as $user)
                    <?php $i++; ?>
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        <tr>

@endforeach

I'm getting following error: Undefined index: role

But when i do , I get following:

[{"id":1,"role":"Administrator","created_at":null,"updated_at":null,"pivot":{"usersid":4,"rolesid":1}}]

Can anyone tell me where did i go wrong?



via Chebli Mohamed

Laravel 5.5 using Scope in model returns error for undefined method

When I try to use scope in this situation, returns me this error:

Call to undefined method Illuminate\Database\Query\Builder::isPromotionTypeIdScope() (View: C:\MAMP\htdocs\mysite\resources\views\site\home.blade.php)

Logic is:

If I replace isPromotionTypeIdScope() with all of the clauses (from the scope), works, but if I use scope gives me error, any suggestions?

Something about the structure is not working. I'm using scopes in another models and have no issues with them. Cannot find what's wrong.

is it possible to be, because I'm trying to add scope (Example: ->promotion()->isPromotionTypeIdScope($promotion_type_id))?

    public function product()
{
    return $this->belongsTo('App\Models\Product', 'product_id');
}

public function promotion(){
    return $this->belongsToMany('App\Models\Promotion', 'promotion_product_prices', 'product_price_id', 'promotion_id');
}



public function single_promotion($promotion_type_id = 0){ 

    return $this->promotion()->isPromotionTypeIdScope($promotion_type_id)->first() ?? false;

}

public function category_promotion($promotion_type_id = 0){
    return $this->product()->first()
                            ->category()
                            ->first()
                            ->promotion()
                            ->isPromotionTypeIdScope($promotion_type_id)
                            ->first() ?? false;

}


public function full_promotion($promotion_type_id = 0)
{
      return Promotion::where('full', 1)->isPromotionTypeIdScope($promotion_type_id)->first() ?? false;
}



public function hasPromotion($promotion_type_id = 0){
    if($this->full_promotion($promotion_type_id) !== false){
        return $this->full_promotion($promotion_type_id);
    }elseif($this->category_promotion($promotion_type_id) !== false){
        return $this->category_promotion($promotion_type_id);
    }elseif($this->single_promotion($promotion_type_id) !== false){
        return $this->single_promotion($promotion_type_id);
    }else{
        return false;
    }

}

public function scopeIsPromotionTypeIdScope($query, $promotion_type_id=0){

    if($promotion_type_id != 0){
        return $query->where('promotion_type_id', $promotion_type_id)
                                        ->where('validity_from', '<=', date('Y-m-d H:i:s'))
                                        ->where('validity_to', '>=', date('Y-m-d H:i:s'))
                                        ->where('active', 1)
                                        ->orderBy('updated_at', 'DESC')->limit(1);
    }else{
        return $query;
    }
}



via Chebli Mohamed

how to store values ​of a multiple select in a field as a string of characters in laravel

{!! Form::open(['route'=>'diagnostic.store']) !!} 
this is my sight:

<select class="form-control" multiple="multiple" name="diagnóstico_rela" id="person3">
  <option selected="selected">orange</option>
  <option>white</option>
  <option selected="selected">purple</option>
</select>
<script>


$("#person3").select2({

    tags: true,


})


</script>

{!! Form::close() !!}

this is my controller:

$diagnosticRear_segment = new Rear_segment;
$diagnosticRear_segment->conducta = $request->conducta;
 $diagnosticRear_segment->principal_diagnostic_id = $request->principal_diagnostic_id;
 $diagnosticRear_segment->diagnóstico_rela = $request->diagnóstico_rela;
 $diagnosticRear_segment->ultimo_ontrol = $request->ultimo_ontrol;
 $diagnosticRear_segment->próximo_control = $request->próximo_control;
                 $diagnosticRear_segment->save();

I am new in this I thank you for the help provided.

In the controller, I show all the fields that I keep in that table in the single that in the view I am showing the field that causes me the problem.



via Chebli Mohamed

algolia facets automatically hiding products

I am new to algolia, vue and laravel. I am trying to build an e-commerce where I have used facets for filtering down data. The problem here is, whenever I check a specific filter, a certain product hides when I hover over the item before. I don't know what is creating the problem. Please help me. 6 products here. But if I select a filter and then hover on the last item in the previous row then

On hovering the last item, a item hides

This is my store.blade.php

@extends('layouts.search')

@section('content') @include('layouts.app') @stop

@section('scripts')

<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>



<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>

@endsection

This is my app.blade.php

<div id="app">
    <ais-index
            app-id="Q5IYJ43XF9"
            api-key="eb9bda691044aed1d217db64608643dc"
            index-name="phones"
            :query-parameters="{
             numericFilters:['sold != 1']
           }"
    >


    <div class="top-bar">
        <div class="container">
            <nav>
                <ul id="menu-top-bar-left" class="nav nav-inline pull-left animate-dropdown flip">
                    <li class="menu-item animate-dropdown"><a title="Welcome to Worldwide Electronics Store" href="#">Welcome to Worldwide Electronics Store</a></li>
                </ul>
            </nav>

            <nav>
                <ul id="menu-top-bar-right" class="nav nav-inline pull-right animate-dropdown flip">
                    <li class="menu-item animate-dropdown"><a title="Store Locator" href="#"><i class="ec ec-map-pointer"></i>Store Locator</a></li>
                    <li class="menu-item animate-dropdown"><a title="Track Your Order" href="track-your-order.html"><i class="ec ec-transport"></i>Track Your Order</a></li>
                    @if (!Auth::guest())
                        <li class="menu-item animate-dropdown"><a title="My Account" href=""><i class="ec ec-user"></i>My Account</a></li>
                        <li class="menu-item animate-dropdown"><a title="Sign Out" href=""
                                                                  onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();" style=" font-size: 15px; color:rgb(214, 38, 38)">
                                <i class="fa fa-power-off"></i> <b>Sign Out</b>
                            </a>

                            <form id="logout-form" action="" method="POST" style="display: none;">
                                
                            </form></li>
                    @endif
                </ul>
            </nav>
        </div>
    </div><!-- /.top-bar -->

    <header id="masthead" class="site-header header-v2">
        <div class="container">
            <div class="row">

                <!-- ============================================================= Header Logo ============================================================= -->
                <div class="header-logo">
                    <a href="home.html" class="header-logo-link">
                        <svg version="1.1" x="0px" y="0px" width="175.748px"
                             height="42.52px" viewBox="0 0 175.748 42.52" enable-background="new 0 0 175.748 42.52">
                            <ellipse class="ellipse-bg" fill-rule="evenodd" clip-rule="evenodd" fill="#FDD700" cx="170.05" cy="36.341" rx="5.32" ry="5.367"/>
                            <path fill-rule="evenodd" clip-rule="evenodd" fill="#333E48" d="M30.514,0.71c-0.034,0.003-0.066,0.008-0.056,0.056
            C30.263,0.995,29.876,1.181,29.79,1.5c-0.148,0.548,0,1.568,0,2.427v36.459c0.265,0.221,0.506,0.465,0.725,0.734h6.187
            c0.2-0.25,0.423-0.477,0.669-0.678V1.387C37.124,1.185,36.9,0.959,36.701,0.71H30.514z M117.517,12.731
            c-0.232-0.189-0.439-0.64-0.781-0.734c-0.754-0.209-2.039,0-3.121,0h-3.176V4.435c-0.232-0.189-0.439-0.639-0.781-0.733
            c-0.719-0.2-1.969,0-3.01,0h-3.01c-0.238,0.273-0.625,0.431-0.725,0.847c-0.203,0.852,0,2.399,0,3.725
            c0,1.393,0.045,2.748-0.055,3.725h-6.41c-0.184,0.237-0.629,0.434-0.725,0.791c-0.178,0.654,0,1.813,0,2.765v2.766
            c0.232,0.188,0.439,0.64,0.779,0.733c0.777,0.216,2.109,0,3.234,0c1.154,0,2.291-0.045,3.176,0.057v21.277
            c0.232,0.189,0.439,0.639,0.781,0.734c0.719,0.199,1.969,0,3.01,0h3.01c1.008-0.451,0.725-1.889,0.725-3.443
            c-0.002-6.164-0.047-12.867,0.055-18.625h6.299c0.182-0.236,0.627-0.434,0.725-0.79c0.176-0.653,0-1.813,0-2.765V12.731z
            M135.851,18.262c0.201-0.746,0-2.029,0-3.104v-3.104c-0.287-0.245-0.434-0.637-0.781-0.733c-0.824-0.229-1.992-0.044-2.898,0
            c-2.158,0.104-4.506,0.675-5.74,1.411c-0.146-0.362-0.451-0.853-0.893-0.96c-0.693-0.169-1.859,0-2.842,0h-2.842
            c-0.258,0.319-0.625,0.42-0.725,0.79c-0.223,0.82,0,2.338,0,3.443c0,8.109-0.002,16.635,0,24.381
            c0.232,0.189,0.439,0.639,0.779,0.734c0.707,0.195,1.93,0,2.955,0h3.01c0.918-0.463,0.725-1.352,0.725-2.822V36.21
            c-0.002-3.902-0.242-9.117,0-12.473c0.297-4.142,3.836-4.877,8.527-4.686C135.312,18.816,135.757,18.606,135.851,18.262z
            M14.796,11.376c-5.472,0.262-9.443,3.178-11.76,7.056c-2.435,4.075-2.789,10.62-0.501,15.126c2.043,4.023,5.91,7.115,10.701,7.9
            c6.051,0.992,10.992-1.219,14.324-3.838c-0.687-1.1-1.419-2.664-2.118-3.951c-0.398-0.734-0.652-1.486-1.616-1.467
            c-1.942,0.787-4.272,2.262-7.134,2.145c-3.791-0.154-6.659-1.842-7.524-4.91h19.452c0.146-2.793,0.22-5.338-0.279-7.563
            C26.961,15.728,22.503,11.008,14.796,11.376z M9,23.284c0.921-2.508,3.033-4.514,6.298-4.627c3.083-0.107,4.994,1.976,5.685,4.627
            C17.119,23.38,12.865,23.38,9,23.284z M52.418,11.376c-5.551,0.266-9.395,3.142-11.76,7.056
            c-2.476,4.097-2.829,10.493-0.557,15.069c1.997,4.021,5.895,7.156,10.646,7.957c6.068,1.023,11-1.227,14.379-3.781
            c-0.479-0.896-0.875-1.742-1.393-2.709c-0.312-0.582-1.024-2.234-1.561-2.539c-0.912-0.52-1.428,0.135-2.23,0.508
            c-0.564,0.262-1.223,0.523-1.672,0.676c-4.768,1.621-10.372,0.268-11.537-4.176h19.451c0.668-5.443-0.419-9.953-2.73-13.037
            C61.197,13.388,57.774,11.12,52.418,11.376z M46.622,23.343c0.708-2.553,3.161-4.578,6.242-4.686
            c3.08-0.107,5.08,1.953,5.686,4.686H46.622z M160.371,15.497c-2.455-2.453-6.143-4.291-10.869-4.064
            c-2.268,0.109-4.297,0.65-6.02,1.524c-1.719,0.873-3.092,1.957-4.234,3.217c-2.287,2.519-4.164,6.004-3.902,11.007
            c0.248,4.736,1.979,7.813,4.627,10.326c2.568,2.439,6.148,4.254,10.867,4.064c4.457-0.18,7.889-2.115,10.199-4.684
            c2.469-2.746,4.012-5.971,3.959-11.063C164.949,21.134,162.732,17.854,160.371,15.497z M149.558,33.952
            c-3.246-0.221-5.701-2.615-6.41-5.418c-0.174-0.689-0.26-1.25-0.4-2.166c-0.035-0.234,0.072-0.523-0.045-0.77
            c0.682-3.698,2.912-6.257,6.799-6.547c2.543-0.189,4.258,0.735,5.52,1.863c1.322,1.182,2.303,2.715,2.451,4.967
            C157.789,30.669,154.185,34.267,149.558,33.952z M88.812,29.55c-1.232,2.363-2.9,4.307-6.13,4.402
            c-4.729,0.141-8.038-3.16-8.025-7.563c0.004-1.412,0.324-2.65,0.947-3.726c1.197-2.061,3.507-3.688,6.633-3.612
            c3.222,0.079,4.966,1.708,6.632,3.668c1.328-1.059,2.529-1.948,3.9-2.99c0.416-0.315,1.076-0.688,1.227-1.072
            c0.404-1.031-0.365-1.502-0.891-2.088c-2.543-2.835-6.66-5.377-11.704-5.137c-6.02,0.288-10.218,3.697-12.484,7.846
            c-1.293,2.365-1.951,5.158-1.729,8.408c0.209,3.053,1.191,5.496,2.619,7.508c2.842,4.004,7.385,6.973,13.656,6.377
            c5.976-0.568,9.574-3.936,11.816-8.354c-0.141-0.271-0.221-0.604-0.336-0.902C92.929,31.364,90.843,30.485,88.812,29.55z"/>
                        </svg>
                    </a>
                </div>
                <!-- ============================================================= Header Logo : End============================================================= -->

                <div class="primary-nav animate-dropdown">
                    <div class="clearfix">
                        <button class="navbar-toggler hidden-sm-up pull-right flip" type="button" data-toggle="collapse" data-target="#default-header">
                            &#9776;
                        </button>
                    </div>

                    <div class="collapse navbar-toggleable-xs" id="default-header">
                        <nav>
                            <ul id="menu-main-menu" class="nav nav-inline yamm">
                                <li class="menu-item menu-item-has-children animate-dropdown dropdown"><a title="Home" href="shop.html" data-toggle="dropdown" class="dropdown-toggle" aria-haspopup="true">Home</a>

                                </li>
                                <li class="menu-item animate-dropdown"><a title="About Us" href="about.html">About Us</a></li>

                                <li class="menu-item menu-item-has-children animate-dropdown dropdown"><a title="Blog" href="#" data-toggle="dropdown" class="dropdown-toggle" aria-haspopup="true">Blog</a>

                                </li>
                                <li class="yamm-fw menu-item menu-item-has-children animate-dropdown dropdown">
                                    <a title="Pages" href="#" data-toggle="dropdown" class="dropdown-toggle" aria-haspopup="true">Pages</a>

                                </li>
                                <li class="menu-item"><a title="Features" href="#">Features</a></li>
                                <li class="menu-item"><a title="Contact Us" href="#">Contact Us</a></li>
                            </ul>
                        </nav>
                    </div>
                </div>

                <div class="header-support-info" style="
    margin-top: 1%;
">

                    <div class="media">
                        <span class="media-left support-icon media-middle" style="margin-right:0px;"></span>
                        <div class="media-body">
                            @if (Auth::guest())
                                <div class="top-right links">
                                    <a href="" style="font-size: 16px; color:#a3d133"><b>Login</b></a> &nbsp; &nbsp;
                                    <a href="" style="font-size: 16px; color:#a3d133"><b>Register</b></a>
                                </div>
                            @else

                                <a href="#" class="nav-link" data-toggle="dropdown" role="button" aria-expanded="false" style="font-size: 16px; color:#a3d133">
                                    <b> </b>
                                </a>

                            @endif
                        </div>
                    </div>
                </div>
            </div>

        </div><!-- /.row -->

</header><!-- #masthead -->


<nav class="navbar navbar-primary navbar-full">
    <div class="container">
        <ul class="nav navbar-nav departments-menu animate-dropdown">
            <li class="nav-item dropdown ">

                <a class="nav-link"  href="#"  >Shop by Department</a>

            </li>
        </ul>


        <div class="navbar-search">
        <div class="input-group">
            <ais-search-box>
                    <ais-input
                            placeholder="Search product by name or reference..."
                            :class-names="{
                'ais-input': 'form-control navbar-search search-field',
                }"
                    ></ais-input>

            </ais-search-box>
            <div class="input-group-addon search-categories">
                <select name='product_cat' id='product_cat' class='postform resizeselect' >
                    <option value='0' selected='selected'>All Categories</option>
                    <option class="level-0" value="laptops-laptops-computers">Laptops</option>
                    <option class="level-0" value="ultrabooks-laptops-computers">Ultrabooks</option>
                    <option class="level-0" value="mac-computers-laptops">Mac Computers</option>
                    <option class="level-0" value="all-in-one-laptops-computers">All in One</option>
                    <option class="level-0" value="servers">Servers</option>
                    <option class="level-0" value="peripherals">Peripherals</option>
                    <option class="level-0" value="gaming-laptops-computers">Gaming</option>
                    <option class="level-0" value="accessories-laptops-computers">Accessories</option>
                    <option class="level-0" value="audio-speakers">Audio Speakers</option>
                    <option class="level-0" value="headphones">Headphones</option>
                    <option class="level-0" value="computer-cases">Computer Cases</option>
                    <option class="level-0" value="printers">Printers</option>
                    <option class="level-0" value="cameras">Cameras</option>
                    <option class="level-0" value="smartphones">Smartphones</option>
                    <option class="level-0" value="game-consoles">Game Consoles</option>
                    <option class="level-0" value="power-banks">Power Banks</option>
                    <option class="level-0" value="smartwatches">Smartwatches</option>
                    <option class="level-0" value="chargers">Chargers</option>
                    <option class="level-0" value="cases">Cases</option>
                    <option class="level-0" value="headphone-accessories">Headphone Accessories</option>
                    <option class="level-0" value="headphone-cases">Headphone Cases</option>
                    <option class="level-0" value="tablets">Tablets</option>
                    <option class="level-0" value="tvs">TVs</option>
                    <option class="level-0" value="wearables">Wearables</option>
                    <option class="level-0" value="pendrives">Pendrives</option>
                </select>
            </div>
            <div class="input-group-btn">
                <button class="btn btn-secondary" type="submit">
                    <i class="ec ec-search"></i>
                </button>
            </div>
        </div>
        </div>
        <ul class="navbar-mini-cart navbar-nav animate-dropdown nav pull-right flip">
            <li class="nav-item dropdown">
                <a href="cart.html" class="nav-link" data-toggle="dropdown">
                    <i class="ec ec-shopping-bag"></i>
                    <span class="cart-items-count count">4</span>
                    <span class="cart-items-total-price total-price"><span class="amount">&#36;1,215.00</span></span>
                </a>
                <ul class="dropdown-menu dropdown-menu-mini-cart">
                    <li>
                        <div class="widget_shopping_cart_content">

                            <ul class="cart_list product_list_widget ">


                                <li class="mini_cart_item">
                                    <a title="Remove this item" class="remove" href="#">×</a>
                                    <a href="single-product.html">
                                        <img class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" src="assets/images/products/mini-cart1.jpg" alt="">White lumia 9001&nbsp;
                                    </a>

                                    <span class="quantity">2 × <span class="amount">£150.00</span></span>
                                </li>


                                <li class="mini_cart_item">
                                    <a title="Remove this item" class="remove" href="#">×</a>
                                    <a href="single-product.html">
                                        <img class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" src="assets/images/products/mini-cart2.jpg" alt="">PlayStation 4&nbsp;
                                    </a>

                                    <span class="quantity">1 × <span class="amount">£399.99</span></span>
                                </li>

                                <li class="mini_cart_item">
                                    <a data-product_sku="" data-product_id="34" title="Remove this item" class="remove" href="#">×</a>
                                    <a href="single-product.html">
                                        <img class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" src="assets/images/products/mini-cart3.jpg" alt="">POV Action Cam HDR-AS100V&nbsp;

                                    </a>

                                    <span class="quantity">1 × <span class="amount">£269.99</span></span>
                                </li>


                            </ul><!-- end product list -->


                            <p class="total"><strong>Subtotal:</strong> <span class="amount">£969.98</span></p>


                            <p class="buttons">
                                <a class="button wc-forward" href="cart.html">View Cart</a>
                                <a class="button checkout wc-forward" href="checkout.html">Checkout</a>
                            </p>


                        </div>
                    </li>
                </ul>
            </li>
        </ul>

        <ul class="navbar-wishlist nav navbar-nav pull-right flip">
            <li class="nav-item">
                <a href="wishlist.html" class="nav-link"><i class="ec ec-favorites"></i></a>
            </li>
        </ul>
        <ul class="navbar-compare nav navbar-nav pull-right flip">
            <li class="nav-item">
                <a href="compare.html" class="nav-link"><i class="ec ec-compare"></i></a>
            </li>
        </ul>
    </div>
</nav>
        <div id="content" class="site-content" tabindex="-1">
            <div class="container">

                <nav class="woocommerce-breadcrumb" ><a href="home.html">Home</a><span class="delimiter"><i class="fa fa-angle-right"></i></span>Smart Phones &amp; Tablets</nav>
                <div id="updateDiv">
                    <div id="primary" class="content-area">
                        <main id="main" class="site-main">

                            <header class="page-header">
                                <h1 class="page-title">Smart Phones &amp; Tablets</h1>
                                <p class="woocommerce-result-count"> <ais-stats></ais-stats></p>
                            </header>

                            <div class="shop-control-bar">
                                <ul class="shop-view-switcher nav nav-tabs" role="tablist">
                                    <li class="nav-item"><a class="nav-link active" data-toggle="tab" title="Grid View" href="#grid"><i class="fa fa-th"></i></a></li>
                                    <li class="nav-item"><a class="nav-link " data-toggle="tab" title="List View Small" href="#list-view-small"><i class="fa fa-th-list"></i></a></li>
                                </ul>
                                <form class="woocommerce-ordering" method="get" action="">
                                    <select name="orderby" class="orderby" action="/store/sort">
                                        <option value="menu_order" >Default sorting</option>
                                        <option value="price" >Sort by price: low to high</option>
                                        <option value="price-desc" >Sort by price: high to low</option>
                                    </select>&nbsp;&nbsp;
                                </form>
                            </div>

                            <div class="tab-content">
                                <div role="tabpanel" class="tab-pane active" id="grid" aria-expanded="true">
                                    <ul class="products columns-3">

                                            <ais-results>
                                                <template scope="{ result }">
                                            <li class="product col-md-4">
                                                <div class="product-outer">
                                                    <div class="product-inner highlight">
                                                        <span class="loop-product-categories"><a href="product-category.html" rel="tag">Smartphones</a></span>

                                                        <a :href='result.url'>

                                                            <h3><ais-highlight :class-names="{'ais-highlight': 'highlight'}" :result="result" attribute-name="company"></ais-highlight> <ais-highlight :result="result" attribute-name="model"></ais-highlight> -  @ GB</h3>
                                                            <div class="product-thumbnail">

                                                                <img :src="result.photo" alt="" style="height:200px">

                                                            </div>
                                                        </a>

                                                        <div class="price-add-to-cart">
                            <span class="price">
                                <span class="electro-price">
                                    <ins><span class="amount">₹ @</span></ins>

                                </span>
                            </span>
                                                            <a rel="nofollow" href="single-product.html" class="button add_to_cart_button">Add to cart</a>
                                                        </div><!-- /.price-add-to-cart -->

                                                        <div class="hover-area">
                                                            <div class="action-buttons">

                                                                <a href="#" rel="nofollow" class="add_to_wishlist">
                                                                    Premium Quality Phone</a>

                                                            </div>
                                                        </div>
                                                    </div><!-- /.product-inner -->
                                                </div><!-- /.product-outer -->
                                            </li>
                                                </template>
                                            </ais-results>
                                        <ais-no-results></ais-no-results>

                                    </ul>
                                </div>

                            </div>

                            <div class="shop-control-bar-bottom">
                                <p class="woocommerce-result-count"> <ais-stats></ais-stats></p>
                                <nav class="woocommerce-pagination">
                                    
                                </nav>
                            </div>

                        </main><!-- #main -->
                    </div><!-- #primary -->
                </div>

                @include('layouts.sidebar')

            </div><!-- .container -->
        </div><!-- #content -->



    </ais-index>

> </div>
>     </div>
> </div><!-- .container -->
> 
> <script src=""></script>

This is my sidebar.blade.php

<div id="sidebar" class="sidebar" role="complementary">

    <aside class="widget widget_electro_products_filter">
        <h3 class="widget-title">Filters</h3>

            <aside class="widget woocommerce">
                <h3 class="widget-title">Brands</h3>
                <ul>
                    <div class="companies" id="company">
                        <ais-refinement-list attribute-name="company" :class-names="{
            'ais-refinement-list__count': 'badge',
            'ais-refinement-list__item': 'checkbox'
            }">
                        </ais-refinement-list>
                    </div>
                </ul>

            </aside>
            <aside class="widget woocommerce">
                <h3 class="widget-title">Storage</h3>
                <ul>
                    <div class="storages">
                        <ais-refinement-list attribute-name="storage" :class-names="{
            'ais-refinement-list__count': 'badge',
            'ais-refinement-list__item': 'checkbox'
            }">
                        </ais-refinement-list>
                    </div>
                </ul>

            </aside>

    </aside>
    <aside class="widget widget_text">
        <div class="textwidget">
            <a href="#">
                <img src="assets/images/banner/ad-banner-sidebar.jpg" alt="Banner"></a>
        </div>
    </aside>

</div>

And finally app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

import InstantSearch from 'vue-instantsearch';
Vue.use(InstantSearch);



/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */


Vue.component('Search', require('./components/Search.vue'));

const app = new Vue({
    el: '#app'
});

const app2 = new Vue({
    el: '#appli'
});

const app3 = new Vue({
    el: '#applic'
});



via Chebli Mohamed

How to join 2 tables with group by query using laravel

i have a users and chats table in my database. Here are some sample data in my tables:

users table:

id  |   name  |    avatar
1       john     default.png
2       mark       picture.jpg

chats table:

   id  |   user_id  |  friend_id | message | status
    1        1           2           hello     0
    2        1           2           hi        1

the purpose of the status column is to determine whether the message is already read.

  status 0 = unread message
  status 1 = read message

Here is my code to group and count all the unread messages:

        $chat = DB::table('chats')
             ->join('users', 'users.id', '=', 'chats.user_id')
             ->select('user_id', DB::raw('count(*) as total'))
             ->where('friend_id', Auth::user()->id)
             ->where('status',0)
             ->groupBy('user_id')
             ->get();

What i want is to also get the avatar of the user who sent the messages. I don not know how to structure my query to get the avatar column. Any help would be appreciated. Thanks.



via Chebli Mohamed

Call to member function getClientOriginalExtension() in laravel?

try multiple file upload in Laravel so my code for view is

<input type="file" name="photos">

but i facing this problem to cant exact type .. ?

   $img = $request->file('photos');
  $fileExtension=$img->getClientOriginalExtension();



via Chebli Mohamed

mardi 30 janvier 2018

Laravel customize file size error message and file size upload

how can i set a max size of image file to be upload on my laravel, and how can i customize the error message that will come return if the maximum size of the file was not met.

Here is my sample code but this doesn't work.

 $validator = Validator::make($request->all(), [            
            'fname' => 'required',
            'lname' => 'required',
            'mname' => 'required',
            'parentnum' => 'required|min:12|numeric',
            'prodsubcat' => 'required',
            'datetimepicker2' => 'required',
            'files.*' => 'image|size:2000|mimes:jpeg,png,jpg',

        ], [
            'fname.required' => 'First name is required.',
            'lname.required' => 'Last name is required.',
            'mname.required' => 'Middle name is required.',            
            'parentnum.required' => 'Parent contact number is required.',            
            'parentnum.min' => 'Parent contact number must be 12 digits.',                        
            'parentnum.numeric' => 'Parent contact number must be numeric.',            
            'prodsubcat.required' => 'Course is required.',
            'datetimepicker2.required' => 'Birthdate is required.',
            'files.*.image' => 'Selected file must be image.',
            'files.*.mimes' => 'Selected file must be jpeg,png,jpg.',
            'files.*.size' => 'Image size must not greater 2MB.'
        ]);
        if ($validator->fails()) {    
            return response()->json(['error'=>$validator->errors()->all()]);
        } else {
            $input=$request->all();
            $images=array();
            if($files=$request->file('files')){
            $i = 0;
            foreach($files as $file){
                $name=$file->getClientOriginalName();
                $file->move('image_files',$name);
                $images[]=$name;
                $i++;
                }
            } 

Any suggestions? i put max size from the code and also make it as max size in validation and the message i put doesn't come out, it will show error like this:The files.0 failed to upload.



via Chebli Mohamed

Ionic 2 send base64 image to SQL

I want to ask :

I want to sending image with base64 decode from my ionic 2 mobile application to SQL server database with laravel service. I have a problem when base64 value in database, and i decode using https://www.base64decode.org/ that image not full display like this half image

I test with remote device, and i console log my base64 encode before sending to SQL. And that image is full. I dont know what is the problem. Can you help me?

thanks



via Chebli Mohamed

Allowed memory size of *** bytes exhausted even after adjusting php.ini

Suddenly this line

$data_to_send = @file_get_contents($source);

giving me an error

{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Allowed memory size of 536870912 bytes exhausted (tried to allocate 353912831 bytes)","file":"/home/forge/site/app/commands/ExportProductsDiff.php","line":157}}

I already upgrade my Linode VM to this plan already and still didn't seeing the error.

enter image description here


ExportProductsDiff.php

<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class ExportProductsDiff extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'products:exportdiff';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Export all products to Diff.';

    /**
     * The system export message.
     *
     * @var string
     */
    protected $system_message = '[System Diff Export]';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {

        // Export the products by calling the ExportProducts Command
        $options = [
            '--format'          => "distributor",
            '--encoding'        => "standard csv",
            '--categories'      => "all categories",
            '--conjugate'       => 1,
            '--export_notes'    => $this->system_message
        ];

        if($this->option('interval') == 'daily'){
            $options['--date_range'] = date('Y-m-d');
            $options['--include_disabled'] = 1;

        }else if($this->option('interval') == 'daily active'){

            $options['--date_range'] = date('Y-m-d H:i:s');
            // $options['--include_disabled'] = 0; //active only
            // $options['--date_range'] = date('Y-m-d H:i:s',strtotime("-1 days"));
            $options['--include_disabled'] = 1; //include_disabled requested by Xixi on 6/6

        }else if($this->option('interval') == 'weekly active'){

            $options['--include_disabled'] = 0; //active only

        }else if($this->option('interval') == 'weekly'){

            $options['--include_disabled'] = 1;

        }else{

        }

        // Run the export
        $this->call('products:export', $options);

        $last_run_export = ProductExport::where('notes', '=', $this->system_message)
            ->where('status', '=', 'finished')
            ->where('format', '=', 'distributor')
            ->orderBy('id', 'desc')
            ->firstOrFail();
        $this->info('Export created successfully. Export ID is ' . $last_run_export->id);

        $env = $this->option('env');

        if ($env == NULL ){
            $localdomain = 'site.com';
        }else{
            $localdomain = 'site';
        }

        $sftp_server = '1.1.1.1';
        $sftp_user_name = 'site';
        $sftp_user_pass = '######!';

        // Open the SFTP connection
        $connection = @ssh2_connect($sftp_server);
        if (!$connection)
        {
            throw new Exception("Could not connect to $sftp_server.");
        }

        // Login to the SFTP server
        if (! @ssh2_auth_password($connection, $sftp_user_name, $sftp_user_pass))
        {
            throw new Exception("Could not authenticate with username $sftp_user_name " .
                "and password $sftp_user_pass.");
        }
        $sftp = @ssh2_sftp($connection);
        if (!$sftp)
        {
            throw new Exception("Could not initialize SFTP subsystem.");
        }

        // Prepare the files
        $source = '/home/forge/' . $localdomain . '/files/product-exports/' . $last_run_export->file_name;


        if($this->option('interval') == 'daily'){
            $destination = '/inbound/products/include_disabled_product' . $last_run_export->file_name;
        }else if($this->option('interval') == 'daily active'){
            $destination = '/inbound/products/active_only_product' . $last_run_export->file_name;
        }else if($this->option('interval') == 'weekly active'){
            $destination = '/inbound/products/weekly_active_only_full_product_' . $last_run_export->file_name;
        }else if($this->option('interval') == 'weekly'){
            $destination = '/inbound/products/weekly_include_disabled_full_product_' . $last_run_export->file_name;
        }else{}


        $this->info('Source: ' . $source);
        $this->info('Destination: ' . $destination);

        if (!file_exists('/inbound/products/')) {
            ssh2_sftp_mkdir($sftp, '/inbound/products/', 0775, true);
        }

        if (file_exists($source)) {
            chmod($source, 0775);
        }else{
            $this->info('$source NOT exist !');
        }

        // Upload the file
        $stream = @fopen("ssh2.sftp://$sftp$destination", 'w');

        if (!$stream)
        {
            throw new Exception("Could not open file: $destination");
        }

        $data_to_send = @file_get_contents($source);
        if ($data_to_send === false)
        {
            throw new Exception("Could not open local file: $source.");
        }

        if (@fwrite($stream, $data_to_send) === false)
        {
            throw new Exception("Could not send data from file: $source.");
        }

        @fclose($stream);

        // Delete the export when finished
        if (file_exists(base_path() . ProductExport::path . $last_run_export->file_name))
        {
            unlink(base_path() . ProductExport::path . $last_run_export->file_name);
        }
        $last_run_export->delete();
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array();
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('interval', 'daily', InputOption::VALUE_REQUIRED,
                'Export interval from option selected to now. Options are "daily", and "weekly".', 'daily'),
            );
    }

}


I checked my php.ini, and have updated to

└── cat php.ini | grep _max                                                                                                         
log_errors_max_len = 1024
post_max_size = 2000M
upload_max_filesize = 2000M
session.gc_maxlifetime = 1440
;       setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
┌──[root@iggy]──[/etc/php5/fpm] 
└── 

As you can see, I increase the memory allow to 2000M already.

I also reboot my php-fpm right that

service php5-fpm restart

I still face the same issue, did I change the wrong file?

How do I double check ?


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

Laravel search isset error

I try to get my search result, where my search form work with 2 conditions, search in products and search in posts.

If I search in products i will get results, but if search in posts I will get error Trying to get property of non-object which comes from products brand name in my products result part.

Here is my blade code summarized :

    @if(isset($posts))
      @forelse($posts as $post)
        
      @empty
        No Result! Try another keywords
      @endforelse
    @endif


    @if(isset($products))
      @forelse($products as $product)
        
      @empty
        No Result! Try another keywords
      @endforelse

    @endif

my controller:

<?php

namespace App\Http\Controllers\frontend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Session;
use DB;
use Carbon\Carbon;
use App\Product;
use App\Post;
use App\Brand;

class SearchController extends Controller
{
    //header search (used in all pages header part)
    public function search(Request $request) {
        $search = request('search');
        $searchType = request('searchType');

        if(strcmp($searchType, "posts") == 0){
          $posts = Post::where('title', 'like', "%{$search}%")
          ->orWhere('description', 'like', "%{$search}%")
          ->get();
        }elseif(strcmp($searchType, "products") == 0){
          $products = Product::where('title', 'like', "%{$search}%")
          ->orWhere('description', 'like', "%{$search}%")
          ->get();
        }

        return view('front.search', compact('posts', 'products'));
    }
}

my route:

//Header Search
Route::any('/search', 'frontend\SearchController@search')->name('search');



via Chebli Mohamed

Fetching near-realtime data from external API

I'm looking for a sustainable solution to fetch data every x seconds (let's say 20) and store it in a relational database using PHP. After doing some research I found a few options:

1) Cronjobs (with shell scripts)

See https://askubuntu.com/questions/800/how-to-run-scripts-every-5-seconds for more information. This basically comes down to run a shell script (looping/sleeping)

This doesn't feel right as I could not catch exceptions and/or race conditions might occur. Also, cronjobs itself are not made for this kind of tasks.

2) Web-worker (with queued jobs)

Laravel provides a queue worker that can process new jobs (asynchronously) as they are pushed onto the queue. I could push multiple (say a lot) of jobs to the queue at once which should processed every x seconds consecutively.

This sounds like a more robust solution as I could catch exceptions and make sure the worker is running (using observers). The downside; it's slower and it might be overengineered.

3) Web socket

I could use node.js to run a websocket client like socket.io and implement some kind of timing mechanism to store the data every x seconds.

This solution feels odd as I was taught that sockets are used to push data to clients (realtime), but I have never seen that they were used to insert data.


All help is appreciated.



via Chebli Mohamed

Exception in mail queue send function

In my app I am trying to send an email using Mail::queue().

I get an exception saying that serialization of closure failed.

ErrorException in SerializableClosure.php line 93: Serialization of closure failed: Serialization of 'Closure' is not allowed

I have a this as the send function:

public function send()
{
    $view = view('emails.welcome');
    $data = [
        'user' => Auth::user()
    ];

    return $this->mailer->queue($view, $data, function($message){
        $message->to($this->to)->subject($this->subject);
    });
}

I've only recently begun using Laravel so any help would be great.



via Chebli Mohamed

Laravel Clone blade and edit dont work. Edit = No changes

I have write an Laravel script and want now clone an blade/page.

I have copy and paste the blade with an other name and in my route file i rename all other also, and Controller. Nothing is the same as the default one ,only the same construction.

The new site with other url loads but if i change some text in my new blade theres no changes. Always the same as the original. Why that?!

I cant change anything. Whats the Problem and why it looks like the original file overwrite it or display the original page?

Thanks



via Chebli Mohamed

Laravel multilevel menu doesn't work

I have created multilevel menu by this example (first reply): How to create a database-driven multi-level navigation menu using Laravel

I'm always getting empty array. Here's my database structure (database's name is also "structure")

enter image description here

structure_id and parent_id are relevant.

Here's my code:

App/navigation.php

<?php
namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;

class Navigation extends Model {

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

    public function parent() {

        return $this->hasOne('structure', 'structure_id', 'parent_id');

    }

    public function children() {

        return $this->hasMany('structure', 'parent_id', 'structure_id');

    }

    public static function tree() {

        return static::with(implode('.', array_fill(0, 4, 'children')))->where('parent_id', '=', NULL)->get();

    }

}

and the Controller:

app/http/controllers/structurecontroller.php

<?php

namespace App\Http\Controllers\Superuser;

use App\Http\Controllers\Controller;
use App\Navigation;
use App\Structure as Model;

class StructureController extends Controller
{
    /**
     * Allow only for logged in
     * DashboardController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }


    public function index()
    {
        //$model = new Model();
        //$items = $model->getStructure();

        $items = Navigation::tree();
        var_dump($items);exit;



        return view('superuser.structure', ['items' => $items]);
    }
}

I'm pretty sure, I have some data in database. So, what's the problem there? I'm getting always empty array from database. Thank for help



via Chebli Mohamed

Change subscription interval for subscription with multiple subscription items in Stripe

I'm using Stripe (PHP Client, Laravel) to handle our subscriptions. We both have subscription and addons which Stripe doesn't seem to support nativly - however I've found a workaround but I encounter a problem.

Set up
We have some different subscription available to our users.

Monthly:

  • 1 Entity ($10/month)
  • 5 Entities ($40/month)
  • 10 Entities ($80/month)

Yearly:

  • 1 Entity ($100/year)
  • 5 Entities ($400/year)
  • 10 Entities ($800/year)

Addons:

  • 1 Entity ($10/month)
  • 1 Entity ($100/year)

Imagine a user is subscribed to a monthly 5 entities plan ($40/month) with 2 extra addons a month ($20/month). Total of $60/month.

The addons are added as SubscriptionItem using Stripe's PHP Client Library.

How would I go about upgrading the user to a yearly subscription like this:

  • 1x 5 Entities ($400/year) subscription
  • 2x 1 Entity ($200/year) addons

As you can see, the only difference is the billing interval and the price but the same access to our system.

I've tried to just upgrade the subscription plan (not the addon) but I got an error which seems logical due to the different billing intervals.

Would I have to remove all of the subscription addons (SubscriptionItems), then make the upgrade and when add the subscription addons again with their new billing interval? I don't like this approach since I would have to delete the initial subscription and then no where to return the user incase the charge fails...

Another way would be to create a entirely new subscription with the addons seperat from the initial. Then I could assign the new subscription to the customer and remove the old subscription.

All of this seems a bit weird since Stripe is so easy and flexible. I might me missing something? Am I?

What is the best way for me to switch between monthly and yearly plans when I have other subscription items in the subscription?

Hope you understand my question. Thanks!



via Chebli Mohamed

I am trying to hit a certain local MPESA Payment API but am getting an error

I am trying to get a response from MPESA payment API using laravel but I am getting an error . My code is as below

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MPESA_AUTH extends Controller
{
    public function Authorize(){

        $url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
        $CONSUMER_KEY= 'mF7Dfci1bb35yurArrUAnbyRR0A41nmG';
        $CONSUMER_SECRET= '3QJqx0iQ9QJ6TK5R';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        $credentials = base64_encode($CONSUMER_KEY,$CONSUMER_SECRET);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic '.$credentials)); //setting a custom header
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $curl_response = curl_exec($curl);

        $curl_json=json_decode($curl_response);
        return $curl_json;
    }
}

The error am getting is as below enter image description here



via Chebli Mohamed

Get a element inside in a Array

i have some question and i dont know if exist a method for this but ... i have a Array of arrays like that

"JOAO DA SILVA"=> Collection {#172 ▼
   #items: array:2 [▼
    PropostaCliente {#183 ▼
     "NomeCliente" => "JOAO DA SILVA"
     "NumeroPoposta" => "59a9739e25cee-1"
   ]}
   PropostaCliente {#184 ▼
     "NomeCliente" => "JOAO DA SILVA"
     "NumeroPoposta" => "59a9739e25cee-2"
   ]}
"TERESINHA PIRES DALESSE" => Collection {#171 ▼
  #items: array:3 [▶]
}

and with that i am dealing , so ... i need to catch the values ,NomeCliente and NumeroPoposta ... and i know i can do it with two "foreach" but i need the first foreach to catch these values,and that is my question , have some way to catch then ?



via Chebli Mohamed

Laravel local insists PHP 7.1.5 even though WAMP running PHP 5.6.32

I have a WAMP installation and selected PHP 5.6.32 as the version to run. When I run php artisan serve, the phpinfo() call returns PHP 7.1.5 Development Server

My host has PHP version 5.6.32 installed and I'd like to get Laravel working locally with something other than PHP 7.

What can I do here as the deployment to my host isn't working.

I'm running Laravel version 5.5.32



via Chebli Mohamed

how to use laravel auth for external api

we have created a restful api using laravel which is working fine for andriod now my boss want me to create web application using the same api now i want to create another auth for web application but username and password will match to api. Api will create a token and i want to use that token in the application.

my authention code

protected function authenticated(Request $request)
{

if(strtolower(auth()->user()->status) == strtolower('active')) {
       $this->get_menu($request);
        return redirect('/home');

    }
  else{
auth()->logout();
return redirect('login');
    }

}

if any one have any better solution then please guide me.



via Chebli Mohamed

Laravel foreign key creation fails

I am using laravel 5.4. I want to create relationship with two table. one is users table and another is sir table. users table is already created. here is my sir table migration code

public function up()
{
    Schema::create('sir', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->timestamps();
    });
}
public function down()
{
    Schema::dropIfExists('sir');
}

now when I try to migrate it shows me this error

`  SQLSTATE[HY000]: General error: 1005 Can't create table 
`finalproject`.`#sq
l-9cc_98` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL:
alter table `available_sir` add constraint `available_sir_user_id_foreign`
foreign key (`user_id`) references `users` (`id`))`

I have followed some tutorial but those are not working and also tried with laravel documentation, but still it is not working. anyone please help me to find a solution for this. thanks in advance.



via Chebli Mohamed

Laravel: Reactivating listeners after flushEventListeners()

I have some functionality that is being enacted by my model's event handler that I need to prevent from firing under a specific circumstance.

protected static function bootLogSubject()
{
    static::created(function ($subject) {
        $subject->logContent('create', Auth::user());
    });

I am aware that I can use flushEventListeners() to stop the event firing. This works fine, but is it possible to switch the listeners back on again (unflush? bind?) once I have finished what I need to do?



via Chebli Mohamed

Laravel - Disable option value after selecting it once

I have a form in my project that a user is using to fill up an application. In this form I have a table with details about user's language skill. Also, in my project I have a seeder with all the languages that are shown in an option select in the table.

How can I disable one of the languages after it has been selected once?

This are some samples of my code:

HTML:

<td id="resource_profile_languages">
  <select  class="form-control form-select" id="resource_profile_language_" name="resource_profile_language_" placeholder="Language">
    @foreach($languages as $r=>$language)
      <option  value="" ></option>
    @endforeach
  </select>
</td>

this is my script way of adding a new language in the table:

function addNewLanguage(){
    var count = $('#resource_profile_language_table').children('tr').length;

    var select_language = $('#resource_profile_languages')
                            .children([CONST_ENGLISH_ID])
                            .clone()
                            .attr('id', idResourceProfileLanguage.concat(count))
                            .attr('name', idResourceProfileLanguage.concat(count));


    $('#resource_profile_language_table').append($('<tr>').append( $('<td id="resource_profile_languages_' + count + '" name="resource_profile_languges_' + count + '">').append(select_language)));
  }



via Chebli Mohamed

get all likes agains an answer laravel eloquent

i trying to get all likes against an answer. this is what i have come with soo far. but now i don't know what should i do.

    return DB::table('answers')
                    ->join('member','answers.answer_member_fk','=','member.member_id')
                    ->select('answers.*','member.full_name','member.user_name','member.profile_photo',DB::raw('count(ans_likes.ans_like_id) as total_likes '))
                    ->leftjoin('ans_likes','answers.answer_id','=','ans_likes.ans_like_answer_fk')
                    ->where('answers.answer_question_fk','=',$question_id)
                    ->groupBy('answers.answer_id')
                    ->get();

it is giving me Syntax error or access violation: 1055error according to this error i have to add all the selected columns to groupby. which i think is not a good idea to do so. kindly guide me.



via Chebli Mohamed

curl request from restful Api laravel

i am working on laravel i have created laravel restful api now i want to use it for web and get the api response using curl but restful api not responding.

     // Make Post Fields Array

    $data2 = [
        'data1' => 'value_1',
        'data2' => 'value_2',
    ];

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "url/api/v1/oauth/token",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30000,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($data2),
        CURLOPT_HTTPHEADER => array(
            // Set here requred headers
            "accept: */*",
            "accept-language: en-US,en;q=0.8",
            "content-type: application/json",
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        print_r(json_decode($response));
    }

i am posting and getting json response



via Chebli Mohamed

displaying values from json file on a table on laravel

I am trying to display information from a json file to a table on blade template. the problem is, the value i need to display is a result of two values eg

@if($data['categoryOptionCombo'] == 'nehCW5s6Hx4') @else 0 @endif

{ "dataSet": "Hwcn7ajwZ1p", "completeDate": "", "orgUnit": "100097-5", "period": "2016Q4", "dataValues": [ { "dataElement": "G1Xh1qsVqKJ", "value": "244", "storedBy": "ctcUser", "timeStamp": "2017-01-04", "categoryOptionCombo": "YpFuX3wm6r8", "attributeOptionCombo": "uGIJ6IdkP7Q" }, { "dataElement": "G1Xh1qsVqKJ", "value": "339", "storedBy": "ctcUser", "timeStamp": "2017-01-04", "categoryOptionCombo": "Xns0ysCNhcv", "attributeOptionCombo": "uGIJ6IdkP7Q" }, { "dataElement": "G1Xh1qsVqKJ", "value": "5789", "storedBy": "ctcUser", "timeStamp": "2017-01-04", "categoryOptionCombo": "OKxxCNhyCrd", "attributeOptionCombo": "uGIJ6IdkP7Q" }, ... ] }

the table i want to display to:

`<table class="table table-bordered table-striped table-responsive">
   <thead>
    <tr>
       <th class="text-center">Indicator</th>
       <th class="text-center">Total</th>
       <th class="text-center" colspan="5">Males</th>
       <th class="text-center" colspan="5">Females</th>
    </tr>
    <tr>
       <th></th>
       <th></th>
       <th>Total</th>
       <th> < 1 year</th>
       <th> 1-4 years</th>
       <th> 5-14years</th>
       <th> > 15 years</th>
       <th>Total</th>
       <th> < 1 year</th>
       <th> 1-4 years</th>
       <th> 5-15 years</th>
       <th> > 15 years</th>
     </tr>
     <tr><th colspan="12"><b>HIV CARE (Pre ART and ART)</b></th></tr>                                            
   </thead>                                            
   <tbody>
     @foreach($json['dataValues'] as $data)
     <tr>
       <td># <b>1.1 Cumulative number of persons ever enrolled in care at this facility at beginning of the reporting quarter</b></td>
       <td>@if($data['value'] != '')  @else 0 @endif</td>
       <td></td>
       <td>@if($data['categoryOptionCombo'] == 'nehCW5s6Hx4')  @else 0 @endif</td>
       <td>@if($data['categoryOptionCombo'] == 'ttFf9vc6pnB')  @else 0 @endif</td>
       <td>@if($data['categoryOptionCombo'] == 'DNqn8VIZxhn')  @else 0 @endif</td>
       <td>@if($data['categoryOptionCombo'] == 'ZRSSGOzZeT0')  @else 0 @endif</td>
       <td>@if($data['categoryOptionCombo'] == 'IR5epaaFjxT')  @else 0 @endif</td>
       <td>@if($data['categoryOptionCombo'] == 'YpFuX3wm6r8')  @else 0 @endif</td>
       <td>@if($data['categoryOptionCombo'] == 'Oua3ZLWhBIg')  @else 0 @endif</td>
       <td>@if($data['categoryOptionCombo'] == 'z9VAozP1BEu')  @else 0 @endif</td>
      </tr>
   @endforeach
 </tbody>
</table>`

Currently i can pull values inside dataValues, but i cannot display the data on a single row, instead each data is being displayed on its own row:

this is how it displays now



via Chebli Mohamed

Laravel if checkbox value true, price is required

i have an checkbox in my blade where users can enable an other Payment method and now i want if someone check this box, the price is required for this Payment method.

Checkbox blade:

<div class="form-group">

        <label for="accept1"><font color="#b7b7b7"><img src="/img/accept1.png" height="20" width="20"> Accept other payment method</label>

       <input type="checkbox" value="true" name="accept1"> Yes</font>

        <hr>
</font>
      </div>

Price blade:

<div class="form-group">

        <label for="newprice"><font color="#b7b7b7"><img src="/img/newprice.png" height="20" width="20"> New Price:</font></label> 

        <input type="number" step="any" name="newprice" id="newprice" class="form" value="" >

Controller:

    if ($request->accept1== 'true') {
            $product->accept1= true;
          }


      if ($request->newprice== 'true') {
        if (!is_numeric($request->newprice) || $request->newprice<= 0.0001) {
          session()->flash('errormessage',' Price is required');
          return redirect()->back()->withInput();
        }
}

If someone click the checkbox now , he must also enter an Price or he get error Message.

How can i do this or change the code?



via Chebli Mohamed

Assign authorization middleware on entire resource laravel 5

Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');

Instead of specify each action and its correspondance middleware authorization like above or calling middleware in controller, is there any way of doing it in single line. Like specifying All gates for resource.

Gate::resource('posts', 'PostPolicy');

I am mainly concerned about Resource.



via Chebli Mohamed

Laravel whereBetween in two columns

i need to select products from DB by whereBetween. I have two double type columns in database, price and newprice. Price field is required and newprice is 0 by default. Admin writes newprice if there is any discounts on that product.

Now my problem is it that i need to select from DB with whereBetween by price if newprice == 0 and by newprice if newprice != 0. In a word filter by newprice if it is written, and by price if newprice is 0 by default.

Here is my code.

$from = (int)$request->priceFrom;
$to = (int)$request->priceTo;

$products = Product::whereIn('category_id', $childCategories)->orWhere('category_id', $category->id)->where('publish', 1)->orderBy('created_at', 'desc');
$products->whereBetween('price',array($from,$to))->orWhereBetween('newprice',array($from,$to));
$products = $products->paginate(15);

It doesn't works correctly ofc. Any ideas?



via Chebli Mohamed

Laravel @ https is not working on server where {!! forms !!} are loaded

I'm continue working with project, which was ignored by developer :(

So, website is already on Server and last thing is turn ON - HTTPS.

I checked, that on localhost everything is working, fine, BUT:

on server, also everything is fine, except {!! forms !!} they are loaded through HTTP, not HTTS

Just, short example on localhost:

<form method="GET" action="https://localhost/users" accept-charset="UTF-8" class="form form-inline executor_search" role="form">

Same example (page) on server:

<form method="GET" action="http://mywebsite/users" accept-charset="UTF-8" class="form form-inline executor_search" role="form">

:(

In config/app.php url is

httpS

In resources/view/layout.blade.php

{secure_asset} to load css and js files.

So, website is loaded over HTTPS everywhere, except pages where forms are displayed

Can anyone help me, please? :(



via Chebli Mohamed

Swaggervel publishing issue

I am new to larval and swager. I am installing it in Laravel 5+ but when I add the following code in providers list of app/config/app.php and run the command php artisan vendor:publish. It does not show swagger in providers list to publish.

Jlapp\Swaggervel\SwaggervelServiceProvider::class



via Chebli Mohamed