jeudi 31 mars 2016

In laravel how to give user rating?

This is the user story-: As an administrator I want to reward users for suggesting improvements to a submission so that I can increase their desire towards the system

I need to make user become senior according to their posts. as a example first user level is junior member then member and then senior member

Help me to figure out this!



via Chebli Mohamed

can't stop submitted form from refreshing page

The form is displayed dynamically and gives the id so I can found out which form it is coming from...

here is the php/html form

<div class="col-sm-4 text-center">
    <!-- Task Name -->
    <div><img src="{{ URL::asset('public/mealpics') }}/{{ $meal->picture }}" /></div>
    <div>{{ $meal->name }} by {{ $meal->author }}</div>
    <div>Rating: {{ $meal->rating }}</div>
    <div>Cal: {{ $meal->calories }} Fat: {{ $meal->fat }} Chol: {{ $meal->cholesterol }}</div>
    <div>Sodium: {{ $meal->sodium }} Sugar: {{ $meal->sugar }}</div>
    <div>{{ $meal->created_at }}</div>
    <div>
        <form action="/mealtrist" method="post" enctype="multipart/form-data">
            <input type="hidden" name="_token" value="{!! csrf_token() !!}">
            <input type="hidden" class="form-control" id="onPlan{{$meal->id}}" name="onPlan"
                   value="{{ $meal->id }}">
            <button id="submit_btn" data-mealid="{{$meal->id}}" type="submit" class="btn btn-default">Add To Plan</button>
        </form>
    </div>
</div>

and the jquery ajax

$(document).ready(function () {         
    $('submit_btn').click(function(event) {
        event.preventDefault();
        var diffValue = $(event.currentTarget).attr("data-mealId");
        var mealId = '#onPlan' + diffValue;
        jQuery.ajax({
            url : '<?php echo URL::to('mealtrist') ?>',
            type : 'POST',
        data : {
            onPlan: diffValue},
            });
    });
});

i've also tried this...

$(document).ready(function () {         
    $('#submit_btn').click(function(event) {
        event.preventDefault();
        var diffValue = $(event.currentTarget).attr("data-mealId");
        var mealId = '#onPlan' + diffValue;
        $('#form').submit(function (e) {
            jQuery.ajax({
                url : '<?php echo URL::to('mealtrist') ?>',
                type : 'POST',
            data : $(mealId).serialize(),               success : function( response ) {
                $('#added').empty();
                $(response).appendTo("#added");
            } 
        });

        e.preventDefault();
        });
    });
});

i've also tried the

('#form').on('submit', function (e) {
    ///i've even tried the e.preventDefault(); here but I think that prevents the code below from sending.
    ////code
    e.preventDefault();
});

none of this seems to be working. I'm using larvel 5.1 and trying to get a form to submit on a page and send the value of one input to a controller so that I can get that id and use it to store information from another table in my database. It works of course, but it also refreshes the page...that's what I'm looking for. The page turns up blank, which i understand that is happening because I'm not returning anything in my controller...that doesn't matter, because when I return the same page in my controller it still shows the page refreshing...which is what I want to get rid of. I just want the data sent through ajax so I can use it...no page refresh. I don't understand why I'm having this issue. I've read alot of other questions on here about preventing the refreshing, but none of the solutions are working. Any idea?



via Chebli Mohamed

Why showing undefined service and aliases in app file in laravel?

I am using laravel 5.1. Some files in service and aliases are showing undefined. I don't know what goes wrong here. It is showing this....enter image description here

and also in aliases.. enter image description here

I am new in laravel. I don't know what happened there. Any kinds of help will be appreciated.Thanks



via Chebli Mohamed

Laravel: Base table or view not found: 1146 Table doesn't exist

I was following the default documentation and Laracst tutorials to build an application. Here is the source, http://ift.tt/1UWlTOE

Installing a new instance form this source shows the following errors, can anyone please assist me to find the issue here?

    
[Illuminate\Database\QueryException]                                                                                                        
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel-5-starter.permissions' doesn't exist (SQL: select * from `permissions`)  

  [PDOException]                                                                                           
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel-5-starter.permissions' doesn't exist


via Chebli Mohamed

Laravel 5 reset password form not submitting if password is less than 6 characters

I am trying to reset my password but not able rest password if password length is less then 6. I am validating password filed with min:4 validation but when I enter more then 4 character form is not submitting but when I tried with more then 6 it is working.

Any Idea what is wrong in my code.

Here is my HTML:

<div class="reset_password_container">
    <div class="reset_bg">
        <form class="form-horizontal" role="form" method="POST" action="{{ url('/password/reset') }}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <input type="hidden" name="token" value="{{ $token }}">

            <div class="find_account_container">
                <div class="find_inner_logo">
                    <h5>{{ trans('messages.reset_password_form.reset_password') }}</h5>
                </div>
                <div class="find_form_dv">
                    <div class="reset_para_dv">
                        <p>{{ trans('messages.reset_password_form.text_1') }}</p>
                        <div class="reset_email_dv">
                            <p>{{ trans('messages.reset_password_form.email') }} <a href="javascript:void(0);">{{ $email }}</a></p>
                        </div>
                    </div>
                    <div class="reset_form_dv">
                        <input type="hidden" class="txt" name="ID" value="{{ $email }}">
                        <input type="password" class="txt" name="password" value="{{ old('password') }}" placeholder="{{ trans('messages.reset_password_form.password') }}">
                        <p class="error"></p>

                        <input type="password" class="txt" name="password_confirmation" value="{{ old('password_confirmation') }}" placeholder="{{ trans('messages.reset_password_form.password_confirmation') }}">
                        <p class="error">
                            @if ($errors->has('password'))
                                {{ $errors->first('password') }}
                            @endif
                        </p>
                    </div>
                </div>
            </div>
            <div class="reset_footer_bg">
                <div class="rest_btn_bg">
                    <button type="submit" class="btn btn-primary">{{ trans('messages.reset_password_form.confirm') }}</button>
                </div>
            </div>
        </form>
    </div>
</div>

PasswordController.php

/**
 * Reset the given user's password.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function postReset(Request $request)
{
    $this->validate($request, [
        'token' => 'required',
        'ID' => 'required|email',
        'password' => 'required|min:4|confirmed',
        'password_confirmation' => 'required|min:4'
    ]);

    $credentials = $request->only(
        'ID', 'password', 'password_confirmation', 'token'
    );

    $response = Password::reset($credentials, function ($user, $password) {
        $this->resetPassword($user, $password);
    });

    switch ($response) {
        case Password::PASSWORD_RESET:
            return redirect($this->redirectPath())->with('status', trans($response));

        default:
            return redirect()->back()
                        ->withInput($request->only('ID'))
                        ->withErrors(['ID' => trans($response)]);
    }
}



via Chebli Mohamed

laravel 5.1 Auth::attempt() don't work after composer update

my project in laravel 5.1 and i can't login after composer update

Everything was working before i did

composer update

I'm using standard built in laravel's register and login process the function Auth::attempt() in AuthController.php always return false.

(i have tested it on a new project of laravel 5.1 and it's the same problem)

I did password reset, created new user, nothing works...

those are the plugin that was updated:

Updating dependencies (including require-dev)
- Removing giggsey/libphonenumber-for-php (7.2.6)
- Installing giggsey/libphonenumber-for-php (7.2.8)
  Downloading: 100%

- Removing symfony/var-dumper (v2.7.10)
- Installing symfony/var-dumper (v2.7.11)
  Downloading: 100%

- Removing symfony/translation (v2.7.10)
- Installing symfony/translation (v2.7.11)
  Downloading: 100%

- Removing symfony/routing (v2.7.10)
- Installing symfony/routing (v2.7.11)
  Downloading: 100%

- Removing symfony/process (v2.7.10)
- Installing symfony/process (v2.7.11)
  Downloading: 100%

- Installing symfony/polyfill-mbstring (v1.1.1)
  Downloading: 100%

- Removing symfony/http-foundation (v2.7.10)
- Installing symfony/http-foundation (v2.7.11)
  Downloading: 100%

- Removing symfony/event-dispatcher (v2.8.3)
- Installing symfony/event-dispatcher (v2.8.4)
  Downloading: 100%

- Removing symfony/debug (v2.7.10)
- Installing symfony/debug (v2.7.11)
  Downloading: 100%

- Removing symfony/http-kernel (v2.7.10)
- Installing symfony/http-kernel (v2.7.11)
  Downloading: 100%

- Removing symfony/finder (v2.7.10)
- Installing symfony/finder (v2.7.11)
  Downloading: 100%

- Removing symfony/dom-crawler (v2.7.10)
- Installing symfony/dom-crawler (v2.7.11)
  Downloading: 100%

- Removing symfony/css-selector (v2.7.10)
- Installing symfony/css-selector (v2.7.11)
  Downloading: 100%

- Removing symfony/console (v2.7.10)
- Installing symfony/console (v2.7.11)
  Downloading: 100%

- Removing psy/psysh (v0.7.1)
- Installing psy/psysh (v0.7.2)
  Downloading: 100%

- Removing paragonie/random_compat (v1.2.1)
- Installing paragonie/random_compat (v1.4.1)
  Downloading: 100%

- Removing monolog/monolog (1.18.0)
- Installing monolog/monolog (1.18.1)
  Downloading: 100%

- Removing league/flysystem (1.0.18)
- Installing league/flysystem (1.0.20)
  Downloading: 100%

- Removing symfony/polyfill-util (v1.1.0)
- Installing symfony/polyfill-util (v1.1.1)
  Downloading: 100%

- Removing symfony/polyfill-php56 (v1.1.0)
- Installing symfony/polyfill-php56 (v1.1.1)
  Downloading: 100%

- Removing propaganistas/laravel-phone (2.6.1)
- Installing propaganistas/laravel-phone (2.7.0)
  Downloading: 100%

- Removing symfony/yaml (v3.0.3)
- Installing symfony/yaml (v3.0.4)
  Downloading: 100%

- Removing phpunit/phpunit (4.8.23)
- Installing phpunit/phpunit (4.8.24)
  Downloading: 100%

- Removing phpspec/phpspec (2.4.1)
- Installing phpspec/phpspec (2.5.0)
  Downloading: 100%

any idea which plugin causing the problem? any workaround or idea how to fix this ?



via Chebli Mohamed

Best Cart Management Package Laravel

I'm developing e-commerce application in Laravel. My requirement is Cart/Coupon/Order/Wishlist/Payment management. And I have found some good packages for Laravel Cart Management! But not sure which one is good! Can anyone help me to select best one from these packages!

https://github.com/

  1. overtrue/laravel-shopping-cart
  2. lukepolo/laracart
  3. mike182uk/cart
  4. amsgames/laravel-shop (Looks Good)
  5. darryldecode/laravelshoppingcart (another good package)
  6. moltin/laravel-cart

If anyone know any good package other than this then please mention it in comments below. But make sure it is compatible with Laravel 5.1 LTS



via Chebli Mohamed

Login both admin and user in same browser at a time

I have to login both admin and user in same browser in Laravel. In Zend Frame Work it is possible using $authNamespace = new Zend_Session_Namespace('Zend_Auth'). Is there any similar approach available in Laravel?



via Chebli Mohamed

mercredi 30 mars 2016

Project with Match in aggregate not working after use substr in mongodb

I have face one use with mongodb.

below is my sample record.

{
    "_id" : ObjectId("56fa21da0be9b4e3328b4567"),
    "us_u_id" : "1459169911J4gPxpYQ7A",
    "us_dealer_u_id" : "1459169911J4gPxpYQ7A",
    "us_corporate_dealer_u_id" : "1459169173rgSdxVeMLa",
    "us_oem_u_id" : "1459169848CK5yOpXito",
    "us_part_number" : "E200026",
    "us_sup_part_number" : "",
    "us_alter_part_number" : "",
    "us_qty" : 0,
    "us_sale_qty" : 2,
    "us_date" : "20160326",
    "us_source_name" : "BOMAG",
    "us_source_address" : "",
    "us_source_city" : "",
    "us_source_state" : "",
    "us_zip_code" : "",
    "us_alternet_source_code" : "",
    "updated_at" : ISODate("2016-03-29T06:34:02.728Z"),
    "created_at" : ISODate("2016-03-29T06:34:02.728Z")
}

I have try to get all recored having unique date

So, I have made below query using aggregate

.aggregate(
            [
                {
                    "$match":{
                            "yearSubstring":"2016",
                            "monthSubstring":"03",
                            "us_dealer_u_id":"1459169911J4gPxpYQ7A"
                            }
                },
                {
                    "$project":
                            {
                            "yearSubstring":{"$substr":["$us_date",0,4]},
                            "monthSubstring":{"$substr":["$us_date",4,2]},
                            "daySubstring":{"$substr":["$us_date",6,2]}
                            }
                },
                {
                    "$group":
                            {
                                "_id":{"monthSubstring":"$monthSubstring",
                                        "yearSubstring":"$yearSubstring",
                                        "daySubstring":"$daySubstring"
                                    },
                                "daySubstring":{"$last":"$daySubstring"}
                            }
                },
                {"$sort":{"us_date":1}}
            ]
        )

I have try both way to pass year and month (as string and as int)

but I have get blank result.

if I'm remove month and year from condition then record came.

mostly I have try all the diff. diff. solution but result is same.

Thank in advance.



via Chebli Mohamed

Laravel 5 validation issue with reset password form

I am trying reset user password but facing issues with resting my password. I am validating password filed with min:4 validation but when I enter more then 4 character form is not submitting but when I tried with more then 6 it is working.

Any Idea what is wrong in my code.

Here is my HTML:

<div class="reset_password_container">
    <div class="reset_bg">
        <form class="form-horizontal" role="form" method="POST" action="{{ url('/password/reset') }}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <input type="hidden" name="token" value="{{ $token }}">

            <div class="find_account_container">
                <div class="find_inner_logo">
                    <h5>{{ trans('messages.reset_password_form.reset_password') }}</h5>
                </div>
                <div class="find_form_dv">
                    <div class="reset_para_dv">
                        <p>{{ trans('messages.reset_password_form.text_1') }}</p>
                        <div class="reset_email_dv">
                            <p>{{ trans('messages.reset_password_form.email') }} <a href="javascript:void(0);">{{ $email }}</a></p>
                        </div>
                    </div>
                    <div class="reset_form_dv">
                        <input type="hidden" class="txt" name="ID" value="{{ $email }}">
                        <input type="password" class="txt" name="password" value="{{ old('password') }}" placeholder="{{ trans('messages.reset_password_form.password') }}">
                        <p class="error"></p>

                        <input type="password" class="txt" name="password_confirmation" value="{{ old('password_confirmation') }}" placeholder="{{ trans('messages.reset_password_form.password_confirmation') }}">
                        <p class="error">
                            @if ($errors->has('password'))
                                {{ $errors->first('password') }}
                            @endif
                        </p>
                    </div>
                </div>
            </div>
            <div class="reset_footer_bg">
                <div class="rest_btn_bg">
                    <button type="submit" class="btn btn-primary">{{ trans('messages.reset_password_form.confirm') }}</button>
                </div>
            </div>
        </form>
    </div>
</div>

PasswordController.php

/**
 * Reset the given user's password.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function postReset(Request $request)
{
    $this->validate($request, [
        'token' => 'required',
        'ID' => 'required|email',
        'password' => 'required|min:6|confirmed',
        'password_confirmation' => 'required|min:6'
    ]);

    $credentials = $request->only(
        'ID', 'password', 'password_confirmation', 'token'
    );

    $response = Password::reset($credentials, function ($user, $password) {
        $this->resetPassword($user, $password);
    });

    switch ($response) {
        case Password::PASSWORD_RESET:
            return redirect($this->redirectPath())->with('status', trans($response));

        default:
            return redirect()->back()
                        ->withInput($request->only('ID'))
                        ->withErrors(['ID' => trans($response)]);
    }
}



via Chebli Mohamed

Trying to display image in Laravel 5.1 using dropzone

I am trying to display the image from the file path but it's seeing a different thing entirely, I'm vague of what to do. I am using dropzone. The images are stored in this directory laravel/public/gallery/images. so the url is thus: http://localhost:port/gallery/images. The images are saved in the db successfully but displaying them is an issue. This is the code to display:

<TR><TD>

                    <DIV class="row">
                      <DIV class="col-md-12">
                        <DIV id="gallery-images">
                            <ul>
                                @foreach($productVerificationValidation->productDocumentUpload as $productDocument)
                                  <li>
                                      <a href="{{url($productDocument->file_path)}}./.{{$productDocument->file_name}}" target="_blank">
                                        <img src="{{url($productDocument->file_path)}}">
                                      </a>
                                  </li>
                                @endforeach
                            </ul>
                        </DIV>
                      </DIV>
                    </DIV>

                  </TD></TR>

This is the controller to display the view:

   public function viewUploadedDocuments($id=null){
            $productVerificationValidation = ProductVerificationValidation::findOrFail($id);
            return view('product.verification-validation.viewDocuments')->with('productVerificationValidation', $productVerificationValidation);
}

To my surprise when i check the console on Chrome, instead of getting the properties of the images it returns wrong properties as displayed on the screenshot: wrong properties assigned to an image but the db record has a different property as displayed on the screenshot: db properties different from what's displayed on console. what wrong am I to make right, Please help out.



via Chebli Mohamed

Javascript : update input value via ajax on modal shown

I have a modal which I show it on an element click. So I want to update an input value in this modal via Ajax, I can retrieve data successfully but it doesn't update its value normally (get a value of an other article record not the current articleID), here my code :

$('#editArticle').on('show.bs.modal', function (e) {
    ...
    $articleID =  $(e.relatedTarget).attr('data-id');
    $.ajax({
            type: "POST",
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
            url : 'article/'+ $articleID +'/getData',                
            dataType : "json",
            success : function(data){                    
                document.getElementById("serial").value = data['serial'];
            }
    });  
});

Records are listed in datatable : enter image description here What's the mistake ?!



via Chebli Mohamed

Laravel with Amazon AWS SQS

I've changed the queue driver over to AWS SQS in a Laravel 5.1 project, but now whenever the queue is called I get...

Type error: Argument 1 passed to Aws\Common\Client\AbstractClient::__construct() must be an instance of Aws\Common\Credentials\CredentialsInterface, array given, called in /home/vagrant/Code/ukisug/vendor/laravel/framework/src/Illuminate/Queue/Connectors/SqsConnector.php on line 26

Any ideas?



via Chebli Mohamed

How to make ajax call in Laravel 5.1 [duplicate]

This question already has an answer here:

I have following function

function events(){
    var data = $.ajax({
        url: 'http://ift.tt/1pKm16S',
        type: 'GET'
    });

    alert(data);
}

then in my routes I have

Route::group(['prefix'=>'api/v1/'],function(){
    Route::resource('events','EventsapiController');
});

if you just put following url then it shows the json data

http://ift.tt/1pKm16S

but when I access it on my laravel using the ajax call its showing null object

Any idea



via Chebli Mohamed

Laravel Sentinel Login with Webview App

I have a web application built with Laravel 5.1.

I have opened a POST route on frontend for webview apps.

This is my app login function:

$json = array();

    $credentials = [
        'email' => $request->email,
        'password' => $request->password,
    ];

    $error = $this->auth->login($credentials, false);

    if (!$error) 
        $json['success'] = trans('user::messages.successfully logged in');

    else        
        $json['error'] = $error;

    echo json_encode($json);

However, when I redirect the mobile user to homepage after a successfull request, user is not logged in.

Interestingly, when I close and re-open the app, user is logged in.

Any ideas?



via Chebli Mohamed

Insert querry in laravel 5.1 using foeach loop

my code is:

  $store_ids=Input::get('store_inventory_ids');
        $store_product_inven_qty=Input::get('store_pro_inv_qty');
        $store_attri_ids=Input::get('store_attri_ids');
        $store_id_with_attri_id=Input::get('store_id_attri_id');

    foreach ($store_ids as $key => $store_id) { 
    ProStoreInventoryModel::insert([
    'product_id'=>'1',
    'store_id'=>$store_id,
    'attri_ids'=>'1',
    'attri_ids_with_store_id'=>'1',
    'product_qty'=>'1',
    'status'=>'1',
    'deletestatus'=>'0',
    'created_at'=>date('Y:m:d H:i:s'),
    'updated_at'=>date('Y:m:d H:i:s')
    ]);
    }

This is my model name: ProStoreInventoryModel

The below four variable haves 16 datas in array format.,

$store_ids, $store_product_inven_qty, $store_attri_ids, 
$store_id_with_attri_id.

I just looped main foreach, in that i wrote insert querry, now how can i insert the remaining values.



via Chebli Mohamed

Laravel / Php regular expression

I want to create a regular which checks if an input field has ü,ä or ö.

If the input field has for instance the letter ü I want to switch it to ue.

So far I have this:

public static $rules = [
    'email' => 'required|max:30'
    'filename' => 'required|max:30|regex:/'
    ];

But I do not know how to further go on.



via Chebli Mohamed

mardi 29 mars 2016

Laravel save image using dropzone.js into MySQL

I'm just trying out dropzone for the first time and would need assistance to set it up. I am getting error 500 thus:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

This is the controller:

public function storeDocument(Request $request){

         $file = $request->file('file');
         $fileName = uniqid().$file->getClientOriginalName();
         $file->move('gallery/images', $fileName);

         $productVerificationValidation = ProductVerificationValidation::findOrFail($request->productDocumentNameId);
         $documentsUploaded = $productVerificationValidation->productDocumentUpload()->create([
                'gallery_id'    =>  $request->productDocumentNameId,
                'user_id'       =>  Auth::user()->id,
                'company_id'    =>  $request->company_id,
                'product_id'    =>  $request->product_id,
                'file_name'     =>  $fileName,
                'file_size'     =>  $file->getClientSize(),
                'file_mime'     =>  $file->getClientMimeType(),
                'file_path'     =>  'gallery/images'. $fileName
            ]);
    }

This is the route to store the image credentials:

Route::post('product/document/upload/save', array('before'=>'csrf', 'uses'=>'ProductVerificationValidationController@storeDocument'));

This is the form for Dropzone:

<form action="{{url('product/document/upload/save' )}}" 
                        class="dropzone  first-input-div" id="addImages">{{csrf_field()}} 
                        {!!Form::hidden('productDocumentNameId', $productVerificationValidation->id)!!}
                        {!!Form::hidden('product_id', $productVerificationValidation->product_id)!!}
                        {!!Form::hidden('company_id', $productVerificationValidation->company_id)!!}</form>

This is the model setup:

public function productDocumentUpload(){
        return $this->hasMany('App\ProductDocumentUpload');
    }

I'm yet to understand what I need to do right. Please help out.



via Chebli Mohamed

Get the highest id from a specific where clause

I have 4 records on my guests database.

enter image description here

I'm trying to query to the guest that has note_display = 1 and have the highest id.


I've tried

$last_note = DB::table('guests')->where('note_display','=',1)->where('id', DB::raw("(select max(`id`) from guests)"))->first();

I got

Trying to get property of non-object


I'm a lil stuck now, any hints will be a huge helps ?



via Chebli Mohamed

InvalidArgumentException in FileViewFinder.php line 137: View [index] not found

I want to deploy my laravel App with OVH hosting. When I'm opening my website I get this, someone knows why ?

InvalidArgumentException in FileViewFinder.php line 137: View [index] not found.



via Chebli Mohamed

Laravel - Acess config() from inside config/mail.php

I have a table where I store all my configs...

Service provider:

class SettingsServiceProvider extends ServiceProvider
{
    public function boot(Factory $cache, SettingRepository $settings)
    {
        if(Schema::hasTable('settings')){
            $settings = $cache->remember('settings', 60, function() use ($settings)
            {
                return $settings->lists();
            });

            config()->set('settings', $settings);
        }
    }

    public function register()
    {
        $this->app->bind(
            \App\Repositories\SettingRepository::class
        );
    }
}

Service repository:

class SettingRepository{
    private $settings;

    public function __construct(Setting $settings)
    {
        $this->settings = $settings;
    }

    public function update($key, $value = null)
    {
        if (is_array($key))
        {
            foreach ($key as $name => $value)
            {
                $this->update($name, $value);
            }

            return;
        }

        $setting = $this->settings->firstOrCreate(['name' => $key]);
        $setting->value = $value;
        $setting->save();
    }

    public function lists()
    {
        return $this->settings->lists('value', 'name')->all();
    }
}

However when I try to use config() within the config/mail.php file is returned a null value.

What could I do?



via Chebli Mohamed

Uncaught exception 'ReflectionException' with message 'Class App\Console\Kernel does not exist'

I never have any problem running composer install

But this morning, I ran into this error :

PHP Fatal error:  Uncaught exception 'ReflectionException' with message 'Class App\Console\Kernel does not exist' in /usr/share/nginx/ssc-portal/vendor/laravel/framework/src/Illuminate/Container/Container.php:741
Stack trace:
#0 /usr/share/nginx/ssc-portal/vendor/laravel/framework/src/Illuminate/Container/Container.php(741): ReflectionClass->__construct('App\\Console\\Ker...')
#1 /usr/share/nginx/ssc-portal/vendor/laravel/framework/src/Illuminate/Container/Container.php(631): Illuminate\Container\Container->build('App\\Console\\Ker...', Array)
#2 /usr/share/nginx/ssc-portal/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(674): Illuminate\Container\Container->make('App\\Console\\Ker...', Array)
#3 /usr/share/nginx/ssc-portal/vendor/laravel/framework/src/Illuminate/Container/Container.php(220): Illuminate\Foundation\Application->make('App\\Console\\Ker...', Array)
#4 /usr/share/nginx/ssc-portal/vendor/laravel/framework/src/Illuminate/Container/Container.php(738): Illuminate\Container\Container->Illuminate\Cont in /usr/share/nginx/ssc-portal/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 741


Here is my composer.json

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "illuminate/html": "^5.0",
        "laracasts/utilities": "~2.0",
        "barryvdh/laravel-debugbar": "^2.0",
        "sammyk/laravel-facebook-sdk": "~3.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "App/",
            "Helpers\\": "App/Helpers/"
        },
        "files": ["app/Helper.php"]
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}


Did I do anything wrong ? Did I forget to run any commands ?

Any hints / suggestions on this will be much appreciated !



via Chebli Mohamed

datatable yajra laravel eloquent not working

I am using datatable yajra package in my project lravel 5.1 and wants to get data through laravel eloquent this is my suggestion model code.

public function candidate()
    {
                return $this->belongsTo('App\Candidate', 'suggested_user');
    } 

And this is controller code.

public function getBCReport()
    {
$candidates = \App\Suggestion::with('candidate')->get();
return Datatables::of($candidates)
    ->make(true);
    }

And this is my view code:

<

div class="panel-body">
        <div class="candidatereport">
            <div class="table-responsive">                             
                <table class="table display" id="table_id"  cellspacing="0" width="100%">
                    <thead>
                      <tr>
                        <th>First Name</th>
                        <th>Last Name</th>

                      </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</section>
<script>
$(function() {
    $('#table_id').DataTable({
        processing: true,
        serverSide: true,
        dataType: 'json',
        ajax: '{!! route('datatables.candidatereport') !!}',
        columns: [
            { data: 'candidate.fname', name: 'fname' },
            { data: 'candidate.lname', name: 'lname' },

        ]
    });
});
</script>

In controller when I use this code

$candidates = \App\Suggestion::with('candidate');

According to datatable yajra documentation http://ift.tt/1ojrMaw it’s not working butt when I use with

$candidates = \App\Suggestion::with('candidate')->get();

Its working butt this is not according to datatable yajra documentation. Can any one tell what is the reason behind this. Thanks



via Chebli Mohamed

How can i unset the foreach variable in laravel 5.1

In an laravel

I'm using for-each with in a for-each, in that some mistakes make by an looping.

now how can i unset the the for-each variable.



via Chebli Mohamed

how to remove this string

Hi I have an array and I want to remove this string x000D from the postaladdress how will I do it ? I have this in an array and I want to remove it. Please assist.

[1] => Maatwebsite\Excel\Collections\CellCollection Object
                (
                    [title:protected] => 
                    [items:protected] => Array
                        (
                            [email] => a22@bkonelearning.com
                            [firstname] => BK
                            [lastname] => Singh
                            [postaladdress] => C 201, Wembley Estate Apts,_x000D_
Rosewood City,_x000D_
(Opposite McDonald's),_x000D_
Sector 50
                            [city] => Gurgaon
                            [pin] => 122016
                            [state] => Haryana
                            [country] => India
                            [phoneno] => 91-9811525663
                            [street] => 
                            [mobileno] => 91-9811525663
                            [gender] => M
                            [occupation] => 
                            [industry] => 
                            [otherarea] => Sector 50
                            [othercity] => 
                            [isreceiveoffers] => 0
                        )

                )



via Chebli Mohamed

deploy laravel 5 ovh

I'm been trying with every tutorial to deploy laravel 5.1 app on OVH via Filezilla FTP. I'm always getting Internal server error or blank page.

I unzipped my project into root/ ( same level as www) then I copied public content into www.

/www

public content

/project ( has no public folder)

Done 777 chmod in storage folder.

htaccess in www folder

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteCond %{REQUEST_URI} !^www
RewriteRule ^(.*)$ www/$1 [L]

index.php in www folder

        <?php

require __DIR__.'/../bootstrap/autoload.php';


$app = require_once __DIR__.'/../bootstrap/app.php';


$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);



via Chebli Mohamed

Can anyone advice me how to treat when the table has no primary key

I have a table as follows:

| common_menus | CREATE TABLE `common_menus` (
  `menu_id` tinyint(3) unsigned NOT NULL,
  `branch_id` smallint(5) unsigned NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `price` smallint(5) unsigned NOT NULL,
  `type` tinyint(3) unsigned NOT NULL COMMENT '0 - 255',
  `order` tinyint(3) unsigned NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |

The model corresponding to this table is as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Menu extends Model
{
  use SoftDeletes;
  const TABLE = 'common_menus';

  const MENU_ID = 'menu_id';
  const BRANCH_ID = 'branch_id';
  const NAME = 'name';
  const PRICE = 'price';
  const TYPE = 'type';
  const ORDER = 'order';

  const TABLE_MENU_ID = self::TABLE . '.' . self::MENU_ID;
  const TABLE_BRANCH_ID = self::TABLE . '.' . self::BRANCH_ID;
  const TABLE_NAME = self::TABLE . '.' . self::NAME;
  const TABLE_PRICE = self::TABLE . '.' . self::PRICE;
  const TABLE_TYPE = self::TABLE . '.' . self::TYPE;
  const TABLE_ORDER = self::TABLE . '.' . self::ORDER;

  protected $table = self::TABLE;
  protected $dates = ['deleted_at'];
  protected $fillable = [self::MENU_ID, self::BRANCH_ID, self::NAME, self::PRICE, self::TYPE, self::ORDER];

  const STANDARD_MENU = 1;
  const COMBO_MENU = 2;
  const OPTION_MENU = 3;

  // static methods follows

}

I encountered an error as follow when the method to delete the model was called:

QueryException in Connection.php line 651:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `common_menus` set `deleted_at` = 2016-03-29 14:01:01 where `id` is null)

I found that I should declare as follows whenever the table has no primary key.

  protected $primaryKey = null;

Ok, I also have the different but similar table as follows:

| common_therapists | CREATE TABLE `common_therapists` (
  `therapist_id` int(10) unsigned NOT NULL COMMENT '0 - 4294967295',
  `branch_id` smallint(5) unsigned NOT NULL,
  `name` varchar(63) COLLATE utf8mb4_unicode_ci NOT NULL,
  `has_license` tinyint(1) unsigned DEFAULT NULL,
  `lmt` varchar(5) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |

The model corresponding to this table is as follows:

<?php

namespace App;

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

class Therapist extends Model
{
  use SoftDeletes;
  const TABLE = 'common_therapists';
//  const KEY = 'therapist_id';
//  const THERAPIST_ID = self::KEY;
  const THERAPIST_ID = 'therapist_id';
  const TABLE_THERAPIST_ID = self::TABLE . '.' . self::THERAPIST_ID;
  const BRANCH_ID = 'branch_id';
  const TABLE_BRANCH_ID = self::TABLE . '.' . self::BRANCH_ID;
  const NAME = 'name';
  const TABLE_THERAPIST_NAME = self::TABLE . '.' . self::NAME;
  const DELETED_AT = 'deleted_at';
  const MASSSAGE_THERAPIST = 0;
  const LICENSED_MASSAGE_THERAPIST = 1;

  protected $table = self::TABLE;
//  protected $primaryKey = self::KEY;
  protected $dates = ['deleted_at'];
  protected $perPage = 10;
  protected $fillable = ['therapist_id', 'branch_id', 'name', 'has_license', 'lmt'];

  // static methods follows
}

Before this model and table had primary key but it was removed because of requirement changes.

The table and model to treat therapists works completely even it has no declaration of primary key.

My question is whether the table and the model of menus has a problem, or the table and the model of therapists is working wrongly?

Please specify the problem or my misunderstanding. Thanks in advance.



via Chebli Mohamed

lundi 28 mars 2016

Cannot Install Laravel 5.1 via composer

Start from tommorow, I don't know why I can't install the laravel 5.1 via composer create project. Here is the error. Composer create project Laravel 5.1 Error

At first I thought there is a problem with the composer, but when I tried to install Laravel 5.2, it's successfully created.

Please help me to fix this issue. Thanks.



via Chebli Mohamed

Specify Laravel validation language

is it at all possible to tell the Laravel validator which language to use for validation?

I have an application which has its text in English, but for some of the forms, I need the validation errors for the fields to be returned in a different language.

I researched a little and found out that I can just use \App::setLocale('ro') to set the language of the app and thus the file under resources/lang/ro/validation.php will be used for the validation, but I do not want to temper with the setLocale. I could, in the worst scenario, temper with it and change the language before the validation and change it back after the validation again, but it doesn't seem like a good solution.

I am looking for something more like this:

$this->validate($request, [
    'title' => 'required',
    'short' => 'required',
], 'lang_that_I_set_in_DB');



via Chebli Mohamed

How to authenticate without database in Laravel 5.2?

I have tried the following code to authenticate in Laravel 5.2. But I don't know how to make login true. I tried Auth::login(true) after if statement but it is not working properly. I have found some articles about this topic but i couldn't find a detailed example.

public static function Login($email,$password)
{
    $fp = fsockopen ( "www.mydomain.com" , 110 );
    if (!$fp) {
        return "Bağlantı Hatası";
    }
    $trash = fgets ( $fp, 128 );
    fwrite ( $fp, "USER ".$email."\r\n" );
    $trash = fgets ( $fp, 128 );
    fwrite ( $fp, "PASS ".$password."\r\n" );
    $result = fgets ( $fp, 128 );
    if(substr ( $result, 0, 3 ) == '+OK')
        return true; //user will be logged in and then redirect
    else
        return false;
}

If it is possible, could you please add a code here that how to make auth true?

P.S. I can retrieve the user information using email with a simple query after login.



via Chebli Mohamed

Check if record exists in database using Laravel 5.1

I am inserting an xml file contents into a DB from my localstorage. However what happens is that the xml file can be updated and when its updated i need to check if the record already exists or not in my DB. If it exists i need to update the record and if it doesn't exist i need to insert a new record. I am able to do the insert but I dont seem to find a Laravel way to do this using update method.

In my xml file they is a node that doesn't change value when the xml has been updated. I am thinking I must use an if statement to check against this node's value but I cant seem to get my head around this.

Below is how I am doing my insert.

public function store(Request $request)
  {
    // Building directory path.
    $directory = storage_path('app/xmlentries/uploads');

    $files = File::allFiles($directory);

    foreach($files as $file) {

    $contents = $file->getContents();

    foreach((array) $contents as $content)
    {
        $simpleXml = simplexml_load_string($xml);

        $data = [
        'requisition' => $simpleXml->ExportData->Requisition['clientReqId'], //NODE THAT DOES NOT CHANGE VALUE
        'experience' => $simpleXml->ExportData->Requisition->EssentialFunction,
        'job_requirements' => $simpleXml->ExportData->Requisition->EssentialFunction,
        ],
        ];

        Vacancy::insert($data); //WHERE I AM INSERTING MY RECORD

    }

    }
    }   

How would I update the record if it already exists?



via Chebli Mohamed

Laravel GroupBy using database table column values

I am having the following table structure in my database table:

+---------+----------------+--------------------------------+---------------------+
| user_id | payable_amount | payment_type                   | created_at          |
+---------+----------------+--------------------------------+---------------------+
|      10 |         450.00 | order_payment                  | 2016-03-28 08:21:14 |
|       3 |          14.00 | moderator_commission           | 2016-03-28 08:21:14 |
|      10 |          17.00 | principal_moderator_commission | 2016-03-28 08:21:14 |
|       4 |          28.00 | affiliate_commission           | 2016-03-28 08:21:14 |
|      10 |         700.00 | order_payment                  | 2016-03-28 08:21:14 |
|       3 |          22.00 | moderator_commission           | 2016-03-28 08:21:15 |
|      10 |          26.00 | principal_moderator_commission | 2016-03-28 08:21:15 |
|       4 |          44.00 | affiliate_commission           | 2016-03-28 08:21:15 |
|      10 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|       8 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|      11 |         150.00 | shipping                       | 2016-03-28 08:21:17 |
|       7 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|      10 |         500.00 | deduction                      | 2016-03-28 09:59:22 |
|      10 |         200.00 | deduction                      | 2016-03-28 10:46:39 |
|      10 |        2500.00 | credit                         | 2016-03-28 10:54:32 |
+---------+----------------+--------------------------------+---------------------+

What I am trying to do is I want to display the above in tabular format only but by grouping the column payment_type NOT HAVING the value of deduction, credit of the same user_id.

Output should be like this:

+---------+----------------+--------------------------------+---------------------+
| user_id | payable_amount | payment_type                   | created_at          |
+---------+----------------+--------------------------------+---------------------+
|      10 |        1150.00 | order_payment                  | 2016-03-28 08:21:14 |
|       3 |          36.00 | moderator_commission           | 2016-03-28 08:21:14 |
|      10 |          43.00 | principal_moderator_commission | 2016-03-28 08:21:14 |
|       4 |          72.00 | affiliate_commission           | 2016-03-28 08:21:14 |
       10 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|       8 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|      11 |         150.00 | shipping                       | 2016-03-28 08:21:17 |
|       7 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|      10 |         500.00 | deduction                      | 2016-03-28 09:59:22 |
|      10 |         200.00 | deduction                      | 2016-03-28 10:46:39 |
|      10 |        2500.00 | credit                         | 2016-03-28 10:54:32 |
+---------+----------------+--------------------------------+---------------------+

The code that I have tried so far:

Controller:

public function fetchUser($userCode)
{
    $member = User::where('code', $userCode)->first();


    $allOrderUserPayments = OrderUserPayment::where('user_id', $member->id)
                            ->groupBy('payment_type')->get();

    return view('admin.orders.payments.user', compact('allOrderUserPayments'));
}

View:

<tr>
     <th>Details</th>
     <th>Total Wt</th>
     <th>Pay Wt</th>
     <th>Non - Pay Wt</th>
     <th>Total Amt</th>
     <th>Pay Amt</th>
     <th>Non - Pay Amt</th>
     <th>Credit</th>
     <th>Deduction</th>
     <th>Payment</th>
     <th>Balance</th>
     <th>Notes</th>
     <th>Created At</th>
</tr>
@foreach($allOrderUserPayments as $key => $order)
    <?php $credits = $balance = 0.00; ?>

    @if($order->payment_type === 'order_payment')
        <?php
        $totalOrderPaymentAmount = 0.00;
        $ordersOrderPayment = App\OrderUserPayment::where('order_code', $order->order_code)
                  ->where('user_id', $order->user_id)
                  ->where('payment_type', 'order_payment')
                  ->selectRaw('*, SUM(payable_amount) AS totalAmount')
                  ->first();

        $ordersPayableAmount = App\OrderUserPayment::where('order_code', $order->order_code)
                  ->where('user_id', $order->user_id)
                  ->where('payment_type', 'order_payment')
                  ->where('payment_payability_status', '!=', 'Non-Payable')
                  ->selectRaw('*, SUM(payable_amount) AS totalPayableAmount')
                  ->first();
         ?>
         <tr>
             <td>{{ $order->order_code }} / Order Payment</td>
             <td></td>
             <td></td>
             <td></td>
             <td>{{ $ordersOrderPayment->totalAmount }}</td>
             <td>{{ $ordersPayableAmount->totalPayableAmount }}</td>
             <td>{{ number_format($ordersOrderPayment->totalAmount - $ordersPayableAmount->totalPayableAmount, 2) }}</td>
             <td>{{ $ordersOrderPayment->totalAmount }}</td>
             <td></td>
             <td></td>
             <td>{{ $totalCredits += $ordersOrderPayment->totalAmount }}</td>
             <td></td>
             <td></td>
         </tr>
     @endif

     @if($order->payment_type === 'shipping')
         <?php
         $invoicer = App\OrderInvoicerShipping::where('invoicer_id', $order->user_id)->where('order_code', $order->order_code)->first();
         ?>
         <tr>
             <td>{{ $order->order_code }} / Shipping</td>
             <td>{{ $invoicer !== null ? $invoicer->weight : '' }}</td>
             <td></td>
             <td></td>
             <td>{{ $order->payable_amount }}</td>
             <td>{{ $order->payable_amount }}</td>
             <td></td>
             <td><?php $totalCredits += ($credits += $order->payable_amount); ?>{{ $credits = $order->payable_amount }}</td>
             <td></td>
             <td></td>
             @if($order->payment_payability_status !== 'Non-Payable')
                 <td>{{ $balance += $totalCredits }}</td>
             @else
                 <td></td>
             @endif
             <td></td>
             <td>{{ $order->payment_updated_at !== null ? $order->payment_updated_at->timezone('Asia/Kolkata') : '' }}</td>
         </tr>
     @endif

     @if($order->payment_type === 'principal_moderator_commission')
         <?php
         $ordersOrderPaymentPM = App\OrderUserPayment::where('order_code', $order->order_code)
                  ->where('user_id', $order->user_id)
                  ->where('payment_type', 'principal_moderator_commission')
                  ->selectRaw('*, SUM(payable_amount) AS totalAmount')
                  ->first();

          $ordersPayableAmountPM = App\OrderUserPayment::where('order_code', $order->order_code)
                  ->where('user_id', $order->user_id)
                  ->where('payment_type', 'principal_moderator_commission')
                  ->where('payment_payability_status', '!=', 'Non-Payable')
                  ->selectRaw('*, SUM(payable_amount) AS totalPayableAmount')
                  ->first();
           ?>
           <tr>
               <td>{{ $order->order_code }} / Principal Moderator</td>
               <td></td>
               <td></td>
               <td></td>
               <td>{{ $ordersOrderPaymentPM->totalAmount }}</td>
               <td>{{ $ordersPayableAmountPM->totalPayableAmount }}</td>
               <td>{{ number_format($ordersOrderPaymentPM->totalAmount - $ordersPayableAmountPM->totalPayableAmount, 2) }}</td>
               <td>{{ $ordersOrderPaymentPM->totalAmount }}</td>
               <td></td>
               <td></td>
               <td>{{ $totalCredits += $ordersOrderPaymentPM->totalAmount }}</td>
               <td></td>
               <td></td>
           </tr>
       @endif

       @if($order->payment_type === 'deduction')
           <tr>
              <td>Deduction</td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td>{{ $order->payable_amount }}</td>
              <td></td>
              <td>{{ $totalCredits -= $order->payable_amount }}</td>
              <td></td>
              <td></td>
           </tr>
       @elseif($order->payment_type === 'credit')
           <tr>
               <td>Credit</td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td>{{ $order->payable_amount }}</td>
               <td></td>
               <td></td>
               <td>{{ $totalCredits += $order->payable_amount }}</td>
               <td></td>
               <td></td>
           </tr>
       @endif
   @endforeach

How do I achieve this ?

P.S.: I know the above code is not the correct way to do fetch the desired result. I am still at the learning stage and I need some help. Kindly help me out in achieving this.

Any help is highly appreciated. Thank You.



via Chebli Mohamed

Dropzone.js failed to load resource in safari or mac

I'm using Dropzone in laravel 5.1 but it's working in firefox, chrome in windows. once run in mac it's response error with Failed to load resource: the server responded with a status of 500 (Internal Server Error)

is there any problem with php code ?

I have written following code of javascript:

var dropZone = new Dropzone($(".dropzone").get(0),{
          url: BASE_URL+'user/board/uploadimages',
          uploadMultiple: true,
          parallelUploads: 100,
          maxFiles: 100,
          maxFilesize: 5,
          dictFileTooBig: 'Image is bigger than 5MB',
          addRemoveLinks: false,
          autoProcessQueue: true,
          dictDefaultMessage: "<label class='dropzone-message-container'><i class='fa fa-cloud-upload'></i><div class='clearfix'></div> Drop images to upload</label>",
          acceptedFiles: ".jpeg,.jpg,.png,.gif,.JPEG,.JPG,.PNG,.GIF",
          init: function()
          {
              thisDropzone = this;

            this.on('sending', function(file, xhr, formData){
              hiddenBoardID = $("#dropZone .hiddenBoardID").val();
              formData.append('hiddenBoardID', hiddenBoardID);
            });
            this.on('thumbnail', function(file) {
              console.log(file.width);
                if ( file.width < 1000) {
                  file.rejectDimensions();
                }
                else {
                  file.acceptDimensions();
                }
            });
            this.on("success",function(file, response){


              if(response.success){
                 toastr.success(response.message,"Success");
                 setTimeout(function(){
                     dropZone.removeFile(file);
                     $("#dropZone").modal("hide");
                 },2000);
                $("#imageListing .image-container").empty().html(response.html);
              }else{
                toastr.warning(response.message,"Error");
              }
            });
            this.on("complete", function(file) {
            });
            this.on("queuecomplete", function (file) {
            });

          },
          accept: function(file, done) {
            file.acceptDimensions = done;
            file.rejectDimensions = function() {
              done('The image must be at least 1000 pixels in width');
            };
          },
        }); 

please check following image when I try to upload image in mac.

enter image description here

I have check code in dropzone.js official page as well but hot find out this issue.

Please help for this issue.



via Chebli Mohamed

dimanche 27 mars 2016

Post Data not working correctly Laravel

I have a Route as below that will display a profile depending on the data in the url:

Route::get('/{region}/{summonername}', function () {
    return 'Summoner Profile';
});

I have a Form on the Home page which consists of a Input Box and Region Selector. I am posting this data to:

Route::post('/summoner/data');

The problem is that i don't know how i can convert the form data eg. Summoner Name and Region into the url format where the user will be displayed with the profile page and the url would be /{region}/{summonername}. Am i supposed to use a Redirect::to inside my controller? I feel like that is a crappy way of doing it. Any Suggestions?

Right now when i post the data the url displays as '/summoner/data'.

I hope this makes sense, let me know if you need more clarification.



via Chebli Mohamed

Laravel 5: Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given

this should be working but I don't know where is the error, when I try to display the details of a patient it gives me the error

Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given

The function in my controller is:

public function show($id){
    $patient = Patient::findOrFail($id);
    return view('details.show', compact('patient'));
}

And my model:

class Patient extends Model{

protected $fillable = [
    'ci', 'name'
];

// RELATIONSHIPS!
public function user(){
    return $this->belongsTo('App\User');
}

}

However in the function show when I return $patient; it totally works. What am I missing?



via Chebli Mohamed

Laravle 5 reset password is not working when user is already logged in

I have written following code to send reset password link to user and it is working perfect when user is not logged in and getting mail too but when I try to send reset password when user is logged in it is not working.

I have checked when user is logged in postEmail method is not calling by Ajax. Any idea where I am wrong.

Here is my code

Form:

<form id="resetAccountForm" class="form-horizontal" role="form" method="POST" action="http://localhost/project-name/password/email">
    <input type="hidden" name="_token" id="_token" value="OaIG5OWKP3F5YrZwaVDN6uYbATtDqKzpgZ5S66mk">
    <input type="hidden" name="nickname" value="example">
    <input type="hidden" name="ID" value="example@gmail.com">
    <div class="find_acc_btn_contianer re_container">
        <button class="reset_pwd reset-my-account" type="submit">Reset</button>
    </div>
</form>

JS Code for Ajax submission:

$(document.body).on('submit', 'form#resetAccountForm', function(event) {
    event.preventDefault();

    var formData = $(this).serialize(); // form data as string
    var formAction = $(this).attr('action'); // form handler url
    var formMethod = $(this).attr('method'); // GET, POST

    $.ajaxSetup({
        headers: {
            'X-XSRF-Token': $('meta[name="_token"]').attr('content')
        }
    });

    $.ajax({
        type: formMethod,
        url: formAction,
        data: formData,
        cache: false,
        beforeSend: function() {
            $("#ajax-loader").show();
            $('.reset-my-account').prop('disabled', true);
        },
        success: function(data) {
            $("#ajax-loader").hide();
        }
    });
});

Routes:

Route::get('home', 'HomeController@index');
Route::controllers([
    'auth'=>'Auth\AuthController',
    'password'=>'Auth\PasswordController',
]);

Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');

PasswordController.php

/**
 * Send a reset link to the given user.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function postEmail(Request $request)
{
    $this->validate($request, ['ID' => 'required|email']);

    // Pass data to reset password mail template
    view()->composer('emails.password', function($view) {
        $view->with([
            'Nickname'   => Input::get('nickname'),
        ]);
    });

    $response = Password::sendResetLink($request->only('ID'), function (Message $message) {
        $message->subject($this->getEmailSubject());
    });

    if ($response == "passwords.sent") {
        $html = '<div class="img_left_dv"><img src="resources/assets/front/images/suggestion_2.png" alt=""/></div>
        <div class="text_right_dv">
            <h3>'.Input::get('nickname').'</h3>
            <p><a href="javascript:void(0);">'.Input::get('ID').'</a> '.trans('messages.reset_password_popup.confirmation_message').'</p>
        </div>';
        echo $html;
    }
}



via Chebli Mohamed

Can't use function from Model at Mail - laravel 5.1

I have this code which store offer and maxoffer but I can't use it into my Mail function:

 public function store(Requests\OfferRequest $request)
    {

            $offer = new Offer($request->all());

            Auth::user()->offer()->save($offer);

            $maxoffer =  Maxoffer::where('article_id', $request->input('article_id'))
                    ->where('start', Carbon::createFromFormat('m/d/Y h:i a', $request->input('start')))
                    ->first();
//dd($maxoffer);
   if($maxoffer == null)
    {
      Auth::user()->maxoffer()->create($request->all());
    }
    else
    {
      if($maxoffer->price < $request->input('price'))
      {
        $key = '';
        $newOffer = Maxoffer::where('id', $maxoffer->id)
                    ->update(['price'=>$request->input('price'),'user_id'=>Auth::user()->id, 'key'=>$key, 'provera'=>$request->input('provera')]);
      }
    }

        Alert::success('Keep looking for best rates. Good luck...', 'Thanks for bidding!')->persistent("Close");
        $user = Auth::user();

        Mail::send('emails.newoffer', compact('user', 'maxoffer'), function ($m) use ($user) {
        $m->from('info@sss.com', $maxoffer->article()->hname);
        $m->to($user->email, $user->name)->subject('Someone have the bigger offer than you');
       });

        return Redirect::back();

    }

so In Maxoffer controller I have:

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

    public function article(){
        return $this->belongsTo('App\Article');
    }

but in Mail function I cant use it. WHY?

Why $maxoffer->article()->hname inside Mail:: is a problem...

laravel error:

i get errors: ErrorException in 22b7e7ff4b942f1d8fa25f9b1c9a1748 line 6: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$hname (View: /var/www/html/resources/views/emails/newoffer.blade.php)



via Chebli Mohamed

Call a controller Action when using route group

I want to call an action of a controller in laravel blade , when using router group ..

route

  $router->group([
      'namespace' => 'Admin',
      'middleware' => 'auth',
    ], function () {
        resource('admin/adsense', 'AdsenseController');
        resource('admin/post', 'PostController');
    });

So , i want call an action of adsenseController in the blade template

{!! Form::model($var, ['method' => 'PATCH','route' => ['what should i write to call an action ']]) !!}

Example (without router groupe)

route

Route::resource('subject','SubjectController');

blade template

{!! Form::model($var, ['method' => 'PATCH','route' => ['subject.actionName']]) !!}

thanks



via Chebli Mohamed

samedi 26 mars 2016

File upload system in laravel 5.1

I am trying to upload files using laravel5.1.But i am facing error like

FatalErrorException in Handler.php line 25: Uncaught TypeError: Argument 1 passed to App\Exceptions\Handler::report() must be an instance of Exception, instance of Error given, called in E:\xampp\htdocs\mp-admin\vendor\compiled.php on line 1720 and defined in E:\xampp\htdocs\mp-admin\app\Exceptions\Handler.php:25 Stack trace: #0 E:\xampp\htdocs\mp-admin\vendor\compiled.php(1720): App\Exceptions\Handler->report(Object(Error)) #1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Error)) #2 {main} thrown

Here is my view

<div class="form-group">
 <label >Logo</label>

 <input type="file"  name="image" >
</div>

Controller:

$entry = new companyprofiles();
$file = Input::get('image');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension,     File::get($file));

$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;

$entry->save();

But first when i was trying it was storing in database and folder as well.after that continuously giving the same above error.

Please help me with this.if i do dd the value also its giving me the same error i could not able to find where is the error.Not getting stored in database.



via Chebli Mohamed

Data shows null when sending json decoded data in Blade: Laravel 5.2

Below is the class that returns Country data

class CountryData {
    public function GetCountries() {
        return response()->json(['Data' => \App\Models\CountryModel::all()]);
    }
}

I have following Json Data returned by above function

HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json 
{
    "Data":[
              {
                  "CountryID"  : 1,
                  "Country"    : "United States",
                  "CountryCode": "US"
              }
           ]
}

Below is the code in Controller.

$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));

Below is the code in View

@foreach($Countries["Data"] as $Country)
    <tr class="odd pointer">
        <td class=" ">{{$Country["Country"]}}</td>
        <td class=" ">{{$Country["CountryCode"]}}</td>
    </tr>
@endforeach

When I type echo $Countries; I get above text. When I type echo json_decode($Countries, true); It shows blank. Can you please guide me why this is happening?

Reason I am doing this because data is being passed into Blade using below code.

$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));



via Chebli Mohamed

sweetalert pop box display onSubmit form

i want to display sweetalert box onSubmit form to display some links . please advice ..

   @if (Session::has('sweet_alert.alert'))
    <script>
        swal({
        title: "Thank you for submitting the form",
         html:true,  text:'<button><a href="">>download pdf<a></button>',
        type: "success",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: true,
        closeOnConfirm: true

        });
    </script>
@endif

this is my current alert , i want to display it form onSubmit, pls advice



via Chebli Mohamed

Failed to open stream: No such file or directory for bootstrap/autoload.php

I'm trying to clone a fresh copy of a project on to my Windows machine.

I can clone the project successfully to my computer, but when I try to run composer install to install the actual dependencies and packages I am running in to the below error:

php artisan clear-compiled

Warning: require(C:\wamp\www\ucp\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\wamp\www\ucp\bootstrap\autoload.php on line 17

This is the first time I've ever experienced this error and the project works just fine when I install it on to my server or another PC.

The error seems pretty simple; there is no autoload.php file in that directory. However I have double-checked and triple-checked - it is definitely there.

Does anyone know what is causing this or how I can solve it?



via Chebli Mohamed

Laravel 5.1 error in installation on windows 7 using xampp

Hi can anyone help me to install laravel 5.1 on windows 7 using xampp? but in failed when im creating project, i already installed my composer

Error response

composer create-project laravel/laravel blog1 "5.1.*"
  Installing laravel/laravel (v5.1.11)
   - Installing laravel/laravel (v5.1.11)
   Loading from cache

Created project in blog1
  > php -r "copy('.env.example', '.env');"
  > php artisan clear-compiled

Warning:require(C:\xampp\htdocs\blog1\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\blog1\bootstrap\autoload.php on line 17

Fatal error: require(): Failed opening required 'C:\xampp\htdocs\blog1\bootstrap/../vendor/autoload.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\blog1\bootstrap\autoload.php on line 17

PHP Warning:  require(C:\xampp\htdocs\blog1\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\blog1\bootstrap\autoload.php on line 17
PHP Fatal error:  require(): Failed opening required 'C:\xampp\htdocs\blog1\bootstrap/../vendor/autoload.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\blog1\bootstrap\autoload.php on line 17
Script php artisan clear-compiled handling the pre-update-cmd event returned with an error

[RuntimeException]
Error Output: PHP Warning:  require(C:\xampp\htdocs\blog1\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\blog1\bootstrap\autoload.php on line 17

PHP Fatal error:  require(): Failed opening required 'C:\xampp\htdocs\blog1\bootstrap/../vendor/autoload.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\blog1\bootstrap\autoload.php on line 17


create-project [-s|--stability STABILITY] [--prefer-source] [--prefer-dist] [--repository REPOSITORY] [--repository-url REPOSITORY-URL] [--dev] [--no-dev] [--no-plugins] [--no-custom-installers] [--no-scripts] [--no-progress] [--keep-vcs] [--no-install] [--ignore-platform-reqs] [--] [<package>] [<directory>] [<version>]



via Chebli Mohamed

vendredi 25 mars 2016

Calculation of values from different database tables in laravel

I have 4 tables with timestamps of laravel:

  1. orders - order_code, user_id, invoicer_id, moderator_id, affiliate_id, payable_amount, product_id
  2. order_invoicer_shippings - orer_code, invoicer_id, shipping_weight, shipping_amount
  3. order_commissions - order_code, moderator_id, affiliate_id, moderator_commission_amount, affiliate_commission_amount
  4. order_payments - order_code, invoicer_id, moderator_id, affiliate_id, credit, deductions, payments

Scenario: On placing the order, order details are inserted in the orders table, shipping details are inserted in the order_invoicer_shippings table. Also the commissions on the orders and/or products are inserted in the order_commissions_table. Now admin decides to pay them (affiliate, moderator) their dues (shipping amount, commissions), for that he wants to know the balance of each user.

I want to show table data in descending order of created_at field. It should be displayed in the descending order of the event that is happening, irrespective of the order placed and/or task done by the admin.

Along with this, there is a calculation that should happen. Calculation of the current balance of the user (affiliate, moderator).

Formula for calculating the current balance is:

Available Balance + Credit - Deductions - Payments

Example: order_invoicers_table contains:

invoicer_id    shipping_weight    shipping_amount    created_at
    1                50                100         2016-03-18 03:05:32
    2                75                150         2016-03-20 11:50:05
    1               150                300         2016-03-25 06:35:30

order_commissions_table contains:

moderator_id    moderator_comm_amount    affiliate_id    affiliate_comm_amount    created_at
    1                   150                  5                   200            2016-03-18 03:05:32
    9                   350                  4                   225            2016-03-20 11:50:05
    6                   300                  3                   205            2016-03-25 06:35:30

Now in admin, it should be like this for user_id: 1:

details    payable_amt    credits    deductions    payments    balance    created_at
shipping      200            200         0            0          200    2016-03-18 03:05:32
mod_comm      150            150         0            0          350    2016-03-18 03:05:32

Admin now decides to pay the above user (id: 1) the shipping amount (Desired Output):

details    payable_amt    credits    deductions    payments    balance    created_at
payment                                              200         150    2016-03-24 08:08:10
mod_comm      150            150         0            0          350    2016-03-18 03:05:32
shipping      200            200         0            0          200    2016-03-18 03:05:32

The payments/credits/deductions gets inserted in the order_payments table.

The code that I have tried so far is:

Controller:

public function fetchUser($userCode)
{
    $member = User::where('code', $userCode)->first();

    $accountTypes = $member->getAllAccountTypes();

    $invoicerOrders = $moderatorOrders = $affiliateOrders = null;

    foreach($accountTypes as $key => $account) {
        if($account->type === 'invoicer') {
            $invoicerOrders = Order::with('invoicerShippings')
                          ->where('invoicer_id', $account->pivot->user_id)
                          ->latest()->groupBy('code')->get();
        }

        if($account->type === 'moderator') {
            $moderatorOrders = Order::where('moderator_id', $account->pivot->user_id)
                           ->latest()->groupBy('code')->get();
        }

        if($account->type === 'affiliate') {
            $affiliateOrders = Order::where('affiliate_id', $account->pivot->user_id)
                           ->latest()->groupBy('code')->get();
        }
    }

    $allOrders = [
        'invoicerOrders'           => $invoicerOrders,
        'principalModeratorOrders' => $principalModeratorOrders,
        'affiliateOrders'          => $affiliateOrders,
   ];

    return view('admin.orders.payments.user', compact('allOrders', 'member'));
}

View File:

<?php
$totalPayableWeight = $totalNonPayableWeight = $payableWeight = $nonPayableWeight = 0;
$totalPayableAmount = $totalNonPayableAmount = $payableAmount = $nonPayableAmount = 0;
$totalPayableCommissionAmount = $totalNonPayableCommissionAmount = $payableCommissionAmount = $nonPayableCommissionAmount = 0;
$totalBalance = 0;
?>
@if($allOrders['invoicerOrders'] !== null)

    @foreach($allOrders['invoicerOrders'] as $key => $order)
        <?php
        $tempInvPayOrder = App\OrderCommission::where('invoicer_id', $member->id)
                           ->orderBy('created_at', 'DESC')->get();
        $balance = 0;

        foreach($tempInvPayOrder as $ord) {
           $o = App\Order::find($ord->order_id);
           if($o->product_payability !== 'Non-Payable') {
               $payableCommissionAmount = $ord->seller_total_commission_amount;
               $totalPayableCommissionAmount += $payableCommissionAmount;
           }

           if($o->product_payability === 'Non-Payable') {
               $nonPayableCommissionAmount = $ord->seller_total_commission_amount;
               $totalNonPayableCommissionAmount += $nonPayableCommissionAmount;
           }
       }
   ?>
   <tr>
       <td>{{ $order->code }} / Invoicer Shipping</td>
       <td>{{ $totalPayableCommissionAmount + $totalNonPayableCommissionAmount }}</td>
       <td>{{ $totalPayableCommissionAmount }}</td>
       <td>{{ $totalNonPayableCommissionAmount }}</td>
       <td>{{ $totalPayableCommissionAmount }}</td>
       <td>
           <?php
           $balance += $totalPayableCommissionAmount;
           $invoicerTotalPaymentBalance += $balance;
           ?>
           {{ $totalBalance = $invoicerTotalPaymentBalance }}
       </td>
       <td>
           {{ App\OrderCommission::where('invoicer_id', $member->id)->where('order_code', $order->code)->first()->created_at }}
       </td>
   </tr>
@endforeach


<?php
$moderatorTotalPayableCommissionAmount = $moderatorTotalNonPayableCommissionAmount = $moderatorPayableCommissionAmount = $moderaotrNonPayableCommissionAmount = 0;
 ?>
 @if($allOrders['moderatorOrders'] !== null && ! $allOrders['moderatorOrders']->isEmpty())
     @foreach($allOrders['moderatorOrders'] as $key => $order)
         <?php
         $tempOrderCommissions = App\OrderCommission::where('moderator_id', $member->id)->latest()->get();

         foreach($tempOrderCommissions as $ord) {
             $o = App\Order::find($ord->order_id);
             if($o->product_payability !== 'Non-Payable') {
                 $moderatorPayableCommissionAmount = $ord->moderator_total_commission_amount;
                 $moderatorTotalPayableCommissionAmount += $moderatorPayableCommissionAmount;
             }

             if($o->product_payability === 'Non-Payable') {
                 $moderaotrNonPayableCommissionAmount = $ord->moderator_total_commission_amount;
                 $moderatorTotalNonPayableCommissionAmount += $moderaotrNonPayableCommissionAmount;
             }
        }
        ?>
        <tr>
            <td>{{ $order->code }} / Moderator Commission</td>
            <td>{{ $moderatorTotalPayableCommissionAmount + $moderatorTotalNonPayableCommissionAmount }}</td>
            <td>{{ $moderatorTotalPayableCommissionAmount }}</td>
            <td>{{ $moderatorTotalNonPayableCommissionAmount }}</td>
            <td>{{ $moderatorTotalPayableCommissionAmount }}</td>
            <td>{{ $tempOrderCommissions->first()->created_at }}</td>
        </tr>
    @endforeach
@endif

Sorry for such a long question, but I had to give the detailed info in order to solve the issue..

Any help is highly appreciated.



via Chebli Mohamed

Laravel 5.1 redirect within a transaction block

I have a set of delete statements in my Laravel 5.1 application that I have put inside a transaction.

I had my code like the following and was trying to return to the same page. But I was getting a blank page. My routes.php is fine.

DB::transaction(function () use ($foo, $bar, $request)  
{   
    // Delete from table abc
    $deletedFoo = DB::delete('delete from abc where id = ' .  $foo);

    // Delete from table xyz
    $deletedBar = DB::delete('delete from xyz where id = ' .  $bar);

    // Shows blank page
    $request->session()->flash('changes_saved', 'Success! All your changes were saved.');
    return back();

});

However, if I put the return starement outside the DB::transaction block it works fine.

DB::transaction(function () use ($foo, $bar)    
{   
    // Delete from table abc
    $deletedFoo = DB::delete('delete from abc where id = ' .  $foo);

    // Delete from table xyz
    $deletedBar = DB::delete('delete from xyz where id = ' .  $bar);
});

// Goes back to the page with the message
$request->session()->flash('changes_saved', 'Success! All your changes were saved.');
return back();

I tried various things before I realized I need to put the redirect outside the transaction. But why? I am new to Laravel and bit confused here.



via Chebli Mohamed

Laravel php artisan Command returns null

When i run the php artisan on the console it will return null as the output. But its working in another bit bucket branch.

Working output

enter image description here

Error output

enter image description here

Any idea whats going on here? Thanks.



via Chebli Mohamed

How to use more then one table in laravel-5 model

I have an activity menu that have three sub-menu. These sub-menu are common to activity but have different table. So I want to use these three table under one model class, how can I do save operation individual to each other?

My code is as follows:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use DB;


class Activity extends Model {

    protected $table1 = 'task_management';
    protected $table2 = 'call_management';
    protected $table3 = 'event_management';
}



via Chebli Mohamed

jeudi 24 mars 2016

How to compare two strings in Jquery/Js [duplicate]

This question already has an answer here:

I have following Javascript

 <script>
        var socket = io.connect('http://localhost:8080');
        socket.on('callback', function (data) {
            var message = data.split("_"); 
            var myid = "<?php echo Auth::user()->empid; ?> ";
                myid = myid.toString();

                //alert($.type(myid)+'-'+$.type(message[0]));

            if(myid == message[0]){
              alert(message[0]);
            $( "#callback" ).append( "<p>"+message[1]+"</p>" );
          }
          });
    </script>

What I am trying to do is when the socket connects

I am sending message in following format

userid_textmessage

Example would be

MIT818_You have got a message from ram C

Now in the javascript I am trying to compare like this

var message = data.split("_"); 
var myid = "<?php echo Auth::user()->empid; ?>";

if(myid == message[0])
alert(something);

So now even though the myid and message[0] is same but my alert message is not throwing

Any Idea why ?

Thanks



via Chebli Mohamed

Why my routes are not ordered?

in my routes file I use a route group with segment like:

Route::group(['prefix' =>  request()->segment(1) ], function(){
  //routes
});

Normally, my routes are in the order they were written at, but when using the group with request()->segment(1) routes just get disarranged (not just inside the group itself, but all of them), I need to use segment so every customer will have their own slug as the first segment in the URL.

so how can I fix this issue?



via Chebli Mohamed

API-Oriented Laravel Admin-Backend CMS Builder

I am looking for a laravel project/package that helps me build the cms for my users quicker but still gives me the power of coding my app. The structure should remain as much laravel as possible so i can customise as much code as i like.

IN SHORT:I want a faster way to build an admin for my users full-stop, not a faster way to build the actual system. I don't know if it's viable, hopefully it is.



via Chebli Mohamed

Laravel service provider no ran

I have basically called: php artisan make:provider RiakServiceProvider but the new provider does not seem to be called. I have added a var_dump in both boot and register methods.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class RiakServiceProvider extends ServiceProvider
{
    public function boot() {
        var_dump('Should be call second');die;
    }

    public function register() {
        var_dump('Should be call first');die;
    }
}

But this does not seem to be called. Neither through the web server, neither in PHPUnit.?



via Chebli Mohamed

how to hide sections from pdf view laravel domPDF

I want to display only specific sections on my blade to pdf view . is it possible using DOMpdf ? pls advice

   public function pdf()
    {
         $pdf = PDF::loadView('home');
        return $pdf->stream();

    }



via Chebli Mohamed

Laravel 5.1 cached views path on remote server

I am using Laravel 5.1 and have uploaded the project to a server with only ftp access. The views folder has been cached to the local project's absolute path. /home/$USER/projectname/

I have changed the URL variable on config/app but I still get the View not found error. Please help



via Chebli Mohamed

Laravel single route point to different controller depending on slugs

I'm new to laravel and I have searched a lot for an answer to my problem but either it's not applicable or I'm not getting it.

I have a FileMaker solution for a client that handle customers and events. Each customer to my client have their own event websites that is managed via the solution. A cms simply. Each customer get a site with a url like clientsite.com/event.

Each page in the event has a page-type and I would like to address different controllers depending on the type.

In routes.php i have:

Route::group(['middleware' => ['sal', 'menu']], function () {

    Route::get('/{event}/{page}', function($event, $page) {
        // Query page for page-type and use controller depending on type
    });
});

There are many page types (standard text/image, specialized forms etc) and therefor I would like to address different controllers.

Event names are always unique but pages are not.



via Chebli Mohamed

Laravel - Always Returning Results From Database Model Even When Nonexistent

I am trying to determine the relationship between two databases to determine if a user has "liked" a post.

This entails the following vectors:

First the user loads up the collection of posts, or "wall"

This is that route:

Route::get('/wall',[
    'uses' => 'punscontroller@wall',
    'as'   => 'puns.wall'
]);

The relevant controller:

 public function wall()
           {
 if (Auth::check() && Auth::user()->AccountSetup != "FALSE")
{
$data = array();
$wall = Wall::orderBy('id', 'desc')->take(20)->get();
foreach ($wall as $snail){
    $type = $snail["post_type"];
    $id = json_decode($snail["assetID"])->id;
    if(count(Like::where('assetType', $type)->where('user_id', Auth::user()->id)->where('assetId', $id)) > 0){
        //you already liked this assetID
        //push into data
        $datatherobot = array(
    'wall'  => $snail,
    'liked?' => "y"
);
    }
    else{
    $datatherobot = array(
    'wall'  => $snail,
    'liked?' => "n"

);  
    }
array_push($data,$datatherobot);    
}
return view('wall')->with('data', $data);   ;
}
else{
echo "Insufficient Privileges! Please visit the homepage and login!";
}
       }

The view then looks something like this:

@foreach ($data as $snail)
<div class="wallfunctions">
          @if ($snail["liked?"] == "y") <i class="fa fa-thumbs-up liked" style="font-size: 100%;"></i> @else<i class="fa fa-thumbs-up" style=""></i>@endif<i class="fa fa-comments" style="color:black;padding:0 5%"></i>
          </div>
@endforeach

My problem is for each post on the wall, I am getting every single post liked when only the first post should be liked for the logged in user (I only liked one post on the wall, not all of them).

I don't understand why this is happening because if I follow my controller logic while looking at my datatables, I don't see how the count is always greater than 0 regardless of which wall post it is looking at.

Is there some mistake in my code?

Take a look at the two tables in question yourself and see that there should only be one liked post for the logged in user (user_id == 2).

Wall Data Table

Likes Data Table



via Chebli Mohamed

Can't find request model with sql

  1. this is my code , in create i want to insert into "invoicesout" not "invoice"
  2. the problem is when i execute the line is added in the table invoice
  3. i want to now where can i find the file who speak with mysql

  4. InvoiceOutController.php

                            public function create()
            {
                $invoiceSettings    = InvoiceSetting::find(1);
    
                $data = array(
                    'clients'       => Project::all(),
                    'products'      => Product::where('status', 1)->get(),
                    'currencies'    => Currency::all(),
                    'taxes'         => Tax::orderBy('value', 'asc')->get(),
                    'invoiceCode'   => isset($invoiceSettings->code)    
                     $invoiceSettings->code         : false,
                    'invoiceNumber' => isset($invoiceSettings->number)  ? 
                     $invoiceSettings->number + 1   : false
                );
                return View::make('user.invoiceout.create', $data);
            }
    
            public function store()
                {
                    if ( Auth::user()->role_id != 1 )
                    {
                        return Redirect::to('dashboard')->with('error', trans('translate.permissions_denied'));
                    }
    
                    $rules = array(
                        'client_id'     => 'required',
                        'number'        => 'required',
                        'start_date'    => 'required|date|date_format:"Y-m-d"',
                        'due_date'      => 'required|date|date_format:"Y-m-d"',
                        'currency_id'   => 'required'
                    );
    
                    $validator = Validator::make(Input::all(), $rules);
    
                    if ($validator->passes())
                    {
                        $invoiceSettings = InvoiceSetting::first();
    
                        if (isset($invoiceSettings->number))
                        {
                            $invoiceNumber              = $invoiceSettings->number + 1;
                            $invoiceSettings->number    = $invoiceNumber;
                            $invoiceSettings->save();
                        }
    
                        $store              = new Invoiceout;
                        $store->number      = isset($invoiceSettings->number) ? $invoiceNumber : Input::get('number');
                        $store->status_id   = 2;
                        $store->discount    = Input::get('invoiceDiscount') ? Input::get('invoiceDiscount') : 0;
                        $store->type        = Input::get('invoiceDiscountType') ? Input::get('invoiceDiscountType') : 0;
                        $store->amount      = $store->calculateInvoice(Input::get('qty'), Input::get('price'), Input::get('taxes'), Input::get('discount'), Input::get('discountType'), Input::get('invoiceDiscount'), Input::get('invoiceDiscountType'));
                        $store->fill(Input::all());
                        $store->save();
    
                        $products           = Input::get('products');
    
                        foreach ($products as $k => $v)
                        {
                            $product                    = new InvoiceProduct;
                            $product->invoice_id        = $store->id;
                            $product->product_id        = $v;
                            $product->quantity          = Input::get('qty')[$k];
                            $product->price             = Input::get('price')[$k];
                            $product->tax               = Input::get('taxes')[$k];
                            $product->discount          = Input::get('discount')[$k] ? Input::get('discount')[$k] : 0;
                            $product->discount_type     = Input::get('discountType')[$k] ? Input::get('discountType')[$k] : 0;
                            $product->discount_value    = $store->calculateProductPrice(1, Input::get('qty')[$k], Input::get('price')[$k], Input::get('taxes')[$k], Input::get('discount')[$k], Input::get('discountType')[$k]);
                            $product->amount            = $store->calculateProductPrice(2, Input::get('qty')[$k], Input::get('price')[$k], Input::get('taxes')[$k], Input::get('discount')[$k], Input::get('discountType')[$k]);
                            $product->save();
    
                            App::make('ProductController')->manageQuantity($v, Input::get('qty')[$k], Input::get('price')[$k]);
                        }
    
                        $invoiceout = new Invoiceout;
                        $invoiceout->invoiceStatus();
    
    
                    }
                    else
                    {
                        $invoiceSettings    = InvoiceSetting::find(1);
    
                        $data = array(
                            'clients'       => Project::all(),
                            'products'      => Product::where('status', 1)->get(),
                            'currencies'    => Currency::all(),
                            'taxes'         => Tax::all(),
                            'invoiceCode'   => isset($invoiceSettings->code)    ? $invoiceSettings->code        : false,
                            'invoiceNumber' => isset($invoiceSettings-
                             >number)   ? $invoiceSettings->number + 1  : false,
                            'errors'        => $validator->errors(),
                            'inputs'        => Input::all()
                        );
    
                        return View::make('user.invoiceout.create', $data);
                    }
    
                    return $this->loadDataTable();
                }
    
    


via Chebli Mohamed