samedi 31 décembre 2016

How to shorten a url in .htaccess file

I have a wordpress website with the integration of a laravel5.1 app. I use a couple views from the laravel app. How can I shorten the the following url

http://ift.tt/2hWLOWi

I would like to remove /larave-app/public/ from the url so that when they click on the link the url shows as

http://ift.tt/2hF6K83

I am not sure if I need to update the .htaccess file in the laravel-app/public folder or the .htaccess file in wordpress or in both files. Thanks



via Chebli Mohamed

vendredi 30 décembre 2016

Laravel 5.1 login register display custom error messages

I was start working with basic Auth in Laravel, described here: http://ift.tt/2hDeA2h

Everything works properly, when I enter right credentials I will authorised, and redirected, thats great but, when I enter bad credentials, nothing happens, just refresh the form...

I need to display custom error messages like "Bad credentials", "Please fill all inputs" for register ... "Email already registred" etc.

But I do not know, how can I do that.

Which method, or which file to edit to do that.

My login form looks simple from docs:

<form method="POST" action="login">
    {!! csrf_field() !!}

    <div>
        Email
        <input type="email" name="email" value="">
    </div>

    <div>
        Password
        <input type="password" name="password" id="password">
    </div>

    <div>
        <input type="checkbox" name="remember"> Remember Me
    </div>

    <div>
        <button type="submit">Login</button>
    </div>
</form>

Register form too:

<form method="POST" action="register">
    {!! csrf_field() !!}

    <div>
        Email
        <input type="email" name="email" value="">
    </div>

    <div>
        Password
        <input type="password" name="password">
    </div>

    <div>
        Confirm Password
        <input type="password" name="password_confirmation">
    </div>

    <div>
        <button type="submit">Register</button>
    </div>
</form>

And AuthController like this:

 use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    private $redirectTo = '/testing';
    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

Thank you very much, have a great time!



via Chebli Mohamed

Error in larabel 5.1. method save

Error while trying to save logs in larabel 5.1. The code and screenshot of the error shown below. I do not know how to solve them if I appeal to you, I look forward to your help. Thanks

 <?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Grupo;

use App\Http\Requests;

use App\Http\Controllers\Controller;


class ControllerGrupos extends Controller
{


    public function agregar_Grupo(Requests $request)
    {
        $nom = $request->get('name');

        $des   = $request->get('descrition');
        $grupo = new Grupo();


        $grupo->nombre      = $nom;
        $grupo->descripcion = $des;
        $grupo->save();

        return view('grupos.agregar_grupo');
    }

}

this error this error image



via Chebli Mohamed

Laravel 5.1 route not defined redirect

need to ask about error, when I tried to redirect my logout

This is UserController:

    public function logout()
{

    Auth::logout();
    return redirect()->route('auth/login');
}

This is my routes:

Route::get('/', function () {
    return view('welcome');
});
// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

// Registration routes...
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');

Route::get('testing', 'UserController@test');
Route::get('logout', 'UserController@logout');

I think, taht everything is ok on routes and I defined login properly (like a Laravel documentation)

but it still take this error:

InvalidArgumentException in UrlGenerator.php line 306:
Route [auth/login] not defined.

Can you please what is wrong? Did I make any mistake?

Thanks a lot, have a nice day!



via Chebli Mohamed

jeudi 29 décembre 2016

Send Validator Instance key along with keys given in rule method

Issue

Validator Instance is not sending the InvalidAttempts key along with other keys. Instead, it send when the validation is passed for all keys given in rule method.

My request class is like below

class RegisterRequest extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'Password'      => 'required',
            'EmailAddress'  => 'required',
            'UserName'      => 'required'

        ];
    }    
}

I am trying to add a key which will inform user that that are left with this many attempts and for that I am writing below code and my final request class becomes like below.

class RegisterRequest extends Request
{
    use ThrottlesLogins;

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'Password'     => 'required',
            'EmailAddress' => 'required',
            'UserName'     => 'required'            
        ];
    }

    protected function getValidatorInstance()
    {
        $instance = parent::getValidatorInstance();
        $instance->after(function ($validator) {
            $this->CheckTotalAttempts($validator);
        });
        return $instance;
    }

    public function CheckTotalAttempts($validator)
    {
        if ($this->hasTooManyRegisterAttempts($this)) {
            $validator->errors()->add('InvalidAttempts', $this->TotalAttemptsLeft($this) 
                                     . " attempts left.");
        }
    }
}



via Chebli Mohamed

Laravel/Composer: adding seeds programmatically

Currently I'm trying to develope a package update system with the following workflow. I'm creating a package (.zip) with the following files:

  • migrations (folder)
    • migrationClass
    • ..
  • seeds
    • seedfile
    • ..
  • package.xml
  • UpdateInstructionSeeder.php

As a administrator I can upload this package in my admin control panel to update my database.

backend workflow:

  1. get data from package.xml (get available seeds and migrations)
  2. check if a migration/seeding is needed
  3. migrate (works fine)
  4. seed (fails)

So, as you can see I have some trouble with my seeding.

At first I tried to move (with Storage::move()) my seeds from the package seed folder to the database/seed/ directory. I tried to seed it with Artisan::call('db:seed','--class']); but a Class MyClass does not exist error appeared. I guessed that there are some problems with my autoloader, so I've tried to dump it with system('composer dump-autoload', $test);. The output of $test was 1 but the autoload_classmap wasn't updated.

Now I've added a UpdateInstructionSeeder.php which is available in my framework by default to fix the autoloader problem. After uploading my package, I'm using now Storage::get() and Storage::put() to update this with my needed seeds.

Now I'm adding seeds with Artisan::call('make:seeder', ['name' => $className]); ($className is the name of my seeds from the package) and update them with Storage::get() and Storage::put(), too.

Now I'm calling my seeder with Artisan::call('db:seed','--class' => ']);. Result: Class MyClass does not exist

Content:

package UpdateInstructionSeeder

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class UpdateInstructionSeeder extends Seeder
{
   /**
    * Run the database seeds.
    *
    * @return void
    */
   public function run()
   {
       Model::unguard();

       $this->call(DemoTableSeeder::class);

       Model::reguard();
   }
}

package DemoTableSeeder

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DemoTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        DB::table('demos')->insert([
            [
                'demoInt' => 1,
                'demoString' => "a"
            ],
            [
                'demoInt' => 11,
                'demoString' => "aa"
            ],
        ]);

        Model::reguard();
    }
}

I wasted now a lot of hours and I have absolutely no idea to solve this problem programatically.



via Chebli Mohamed

Laravel5.1 can you passed an incremental variable in to a sub-view

I am trying to pass an incremental variable to a blade template subview to add a number to a class name.

@for($x=1; $x < 4; $x++)
            <div class="col-md-3">
                {!! Form::label('amenIcon'.$x,'Amenity Icon '.$x) !!}
                {!! Form::select('amenIcon'.$x,
                 [null =>'Choose Icon'] + $iconDirectory)
                    !!}
            </div>
                @include('portal._iconModals')
            @endfor

The sub-view portal._iconModals

div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Choose Icons</h4>
        </div>
        <div class="modal-body">
            <div class="row">
                <div class="col-md-12" id="bsnImage">
                    @foreach($brandSocialIcons as $bIcons)
                        <a href="javascript:void(0);" class="iconChoice"><img src="../../../../storage/icons/"></a>
                    @endforeach
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
</div>

I would like to increment the class name iconChoice because the I have 3 select fields with options that use the same subview but because of the class name when I choose one of the images with the class of iconChoice it chooses it for all 3 select list instead.

Here is the js code $( "#amenIcon1" ).click(function() {

     $('.iconChoice').click(function() {
         var $thumb = $(this);
         console.log($thumb);

         var icon1 = $thumb.find('img').attr('src');
         displayIcon1(icon1)
     });
     function displayIcon1(icon1) {
         $("#icon1Thumb").attr("src",icon1);
     }
 });

Might not be the best explanation but I will to elaborate more if need be. Thanks



via Chebli Mohamed

Check max attempts : Laravel 5

I have a controller action method like below. Control comes in Controller code only if validations passes in Request class below.

public function Register(RegisterRequest $request) {

}

and Request class is like this

class RegisterRequest extends Request
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'Password'      => 'required',
            'EmailAddress'  => 'required',
            'UserName'      => 'required',
        ];
    }
}

Now, I am trying to write below code in case the user exceeds defined max attempts.

if ($this->hasTooManyLoginAttempts($request)) {
    return  \Response::json([
        'Status'    =>  false,
        'Message'   =>  "Attempts locked",
        'Data'      =>  null,
    ], 403);
}

I think, I should write it in Request class? but if I do so, I will need to obtain the Request class instance for hasTooManyLoginAttempts method. So, not sure how should I proceed to implement this validation

Please suggest. Here the problem is that I am not able to obtain the request class object.



via Chebli Mohamed

how to display selected all values in drop down in laravel 5.1

Hi friend's help how to display selected all values for edit page in laravel this is my code

 <?php $explode_values =  explode(",",@$checkpointvalues[$checkpoint['id']]['description']); ?>

                                {!! Form::select($checkpoint['id'].'_c[]', isset($error_messages[$checkpoint['id']])?$error_messages[$checkpoint['id']] : array(), $explode_values, array('multiple'=>'true', 'class'=>'form-control js-example-tags select2','id'=>$checkpoint['id'].'_c')) !!}

all values stored to database but only display particular values only so help me



via Chebli Mohamed

mercredi 28 décembre 2016

select option in laravel not able to display values from database

Need your's help ,I have inserted value to database but when I edit the all values not display this is my code

 <?php $explode_values =  explode(",",@$checkpointvalues[$checkpoint['id']]['description']); ?>

                                {!! Form::select($checkpoint['id'].'_c[]', isset($error_messages[$checkpoint['id']])?$error_messages[$checkpoint['id']] : array(), $explode_values, array('multiple'=>'true', 'class'=>'form-control js-example-tags select2','id'=>$checkpoint['id'].'_c')) !!}



via Chebli Mohamed

Using RDP or RDC with godaddy windows hosting econmy?

I am wondering if anyone did access to windows hosting on godaddy econmy using rdc or rdp, I want to know to install laravel framework.



via Chebli Mohamed

mardi 27 décembre 2016

not able to get return array values

need your help. I am new in laravel framework, how to get the values from array values, this is my code.

 $output['device_type']=$arrout['equipment']['fabricat']['fabricat_name'].' '.$arrout['equipment']['model']['model'].''.$arrout['equipment']['type']['type'];

here equipment model and fabricat it is working fine. type only not working but

var_dump($arrout['equipment']['type']['type']);die;

return correct values : string 'Tilhengermontert' (length=16) please help me how can I solve



via Chebli Mohamed

Laravel 5.1 migration error auto increment primary

I was learning Laravel for a some time, I create some basic project for myself, but today I was try to migrate table with more integers. But it still take an error.

Every integer try to be auto_increment and primary, it can be a problem, but I do not know, how to resolve it.

        Schema::create ('users', function (Blueprint $table)
    {
        $table->increments ('id');
        $table->string ('email')->unique();
        $table->string ('pass',250);
        $table->integer ('tickets',4);
        $table->integer ('tokens',4);
        $table->integer ('in_raffle',4);
        $table->text ('profile',500);
        $table->string ('ip',20);
        $table->integer ('ban',1);
        $table->integer ('notice',1);
        $table->timestamp ('last_login');

    });

http://ift.tt/2htAxAs

Can somebody tell me, how can I resolve this problem? What to edit to work it properly?

Thanks a lot, have a nice day!



via Chebli Mohamed

paymenwall gateway integration with laravel 5.1

I tried to implement paymentwall gateway with laravel 5.1 using omnipay.But there is no exact documentation or sample codes available.Is there any implementation samples available for omnipay paymentwall integration with laravel.



via Chebli Mohamed

Why ThrottleLogin class increase attempts twice every time?

Problem

When i type wrong username and password, it show total attempts left. But due to some reasons, it increase 2 attempts every time. My code is below. Am I missing something?

Route

Route::post('/AuthenticateUser', 
    array(
        'uses'          =>  'API\Auth\apiLoginController@AuthenticateUser', 
        'as'            =>  'AuthenticateUser',
        'middleware'    =>  ['throttle: 6,1']
    )
);

Controller Action Method

class apiLoginController extends Controller
{
    use ThrottlesLogins;

    public function AuthenticateUser(LoginRequest $request) {        
        //If request fails then calling `$this->TotalAttemptsLeft($request)`
        'Message'   =>  "Invalid credentials" . $this->TotalAttemptsLeft($request) 
                                              . " attempts left.",
    }
}

Throttle Login Trait

trait ThrottlesLogins
{
    protected function TotalAttemptsLeft($request) {
        return $this->limiter()->retriesLeft($this->resolveRequestSignature($request), 6);
    }

    protected function resolveRequestSignature($request)
    {
        return $request->fingerprint();
    }

}



via Chebli Mohamed

lundi 26 décembre 2016

Cart update in laravel

have a form like this. This is an update form, i just need to update qty foreach product in cart. But i have tried to explode each results and not work... it return object2array conversion error... its the first time that i get this error How i can save this in DB?

<form action="update">
  @foreach($products as $product)
<input type="text" name="products[]">
<input type="text" name="qty[]">
@endforeach
<input type="submit" calss="btn btn-primary">

Thanks in advance.



via Chebli Mohamed

dimanche 25 décembre 2016

Override attempt auth method in laravel 5

I'm having a big problem with Auth:attempt method in laravel 5.2, and I wish I can override it.
I have the class users, by default, but doesn't containt the attribut 'email', this last one is containing in an other class user_contacts, with relation one to one with users.
Can I override this function? because by default, it takes 'email', which is not in users in my case I tried to make that in the model, but not working:

lass User extends Authenticatable

{

public function __construct(array $attr = array())
{
    parent::__construct($attr);

    $this->email = $this->user_contacts()->email;
}

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

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

public function user_contacts()
{
    return $this->hasOne('App\UserContact', 'user_id', 'id');
}

}

It just says that the email field is not defined.
Any suggestion plz?
Thanks alot.



via Chebli Mohamed

samedi 24 décembre 2016

Laravel 5.1 DB::table chunk for a Restful API and Angular.JS

Is there a way to chunk millions of records in a Restful API call?

I am using Angular.JS / Ionic for the client and have a restful API that works great with smaller number of records about 10,000. But my database has a couple of million records and if I make an api call to show all records it returns http Response Code 500. The reason I want to pull all the data is so that users can search the matching product using ng-model="query". On the client only 100 handpicked records will be displayed. I looked at the Laravel documentation and it suggests chunking the data. I tried the following code but I get the 500 http response code error. I am using mysql as the database. Eventually Iw ill be building a redis cache but to begin with I need to b able to fetch all the results.

$productlist = DB::table('productlist')->chunk(1000, $products) { foreach ($products as $product) {

    $productlist = array_merge($products, $product);
    }
    });     

 return $productlist;



via Chebli Mohamed

vendredi 23 décembre 2016

How to use $routeProvider with laravel

I'm trying to use routeProvider in my website which is built in laravel. I have a problem with routeProvider. In one of my page there are some options when user clicks it need to load a template. But when i click on the it is always going to .otherwise Here is my code

(function () {
var academics = angular.module('academics',['ngRoute'])

academics.controller("timeTableController",function($scope){
  $scope.test="Hello world";
})

academics.config(function ($routeProvider)
    {
        $routeProvider
            .when('/timetables',{
                template:"Hello world"
            })
            .when('/plates',{
              template:"Hello Planet"
        })
        .otherwise({
          template:"Good Bye"
        })

    })
})();

This is my blade template

@extends('layout.header')
@include('resources.highcharts')
@include('resources.angular')
@section('content')
<div ng-app="academics" class="col-lg-12">
    <div class="col-lg-4">
      <div class="col-lg-12 option-list">
          <ul class="nav">
            <li class="active"><a  href="#timetables">Exam Timetables</a></li>
          </ul>
      </div>
    </div>
    <div class="col-lg-8">
      <div class="ng-view">

      </div>
    </div>

</div>
@stop

Here when i click on timetables i should get Hello world in my ng-view but I'm not getting it. But the same code is working without laravel. Is there any wrong with my code.



via Chebli Mohamed

Using getAuthPassword() with another Model instead of User Model?

I am facing issue, I want to use different field name for password. let us say in users table, when I use this code with User model it works perfectly

/**
 * Override required, otherwise existing Authentication system will not match credentials
 * @return mixed
 */
public function getAuthPassword()
{
    return $this->userPassword;
}

but when I use it with another Model let us say Customer model with same table structure , it doesnt work??!!! does anyone have idea about this issue

Thanks in advance.



via Chebli Mohamed

jeudi 22 décembre 2016

laravel routing issue with domain

I am using laravel version 5.1. I have been using domain routing functionality and have had success with the following code as described in the docs. But the problem is that, When the user visits user.mysite.com, it is taking too much time to load routes. Below is my route:

Route::group(['domain' => 'user.mysite.com'], function ()
{Route::resource('users', 'UserController', ['except' => ['edit', 'create', 'destroy']]);});

As, shown below in the image you can see the time difference it is taking to load routes after loading autoload file.

image for time difference with domain routes

When i do the same thing with prefix instead of domain routes it loads easily without taking time.

Route::group(['prefix' => 'user')], function () 
{Route::resource('users', 'UserController', ['except' => ['edit', 'create', 'destroy']]);});

});

image for time difference with prefix routes

Laravel version is 5.1, Using Apache 2.4.23, and PHP version 5.6.25.

I want to know, Why it is taking this much time, and what is the solution for this.



via Chebli Mohamed

How to store values

I construct one, different values for each id ,this is my code

$errorMessage = array();
        $result = CheckpointErrormsg::where('checklist_template_id', $checklist_template_id)->orderby('error_message', 'asc')->select('checkpoint_id', 'error_message')->get()->toArray();
        foreach ($result as $row) {
            $errorMessage[$row['checkpoint_id']][] = $row['error_message'];
        }
        return $errorMessage;

} This is my blade view page:

 {!! Form::select($checkpoint['id'].'_c[]', isset($error_messages[$checkpoint['id']])?$error_messages[$checkpoint['id']] : array(), $explode_values, array('multiple'=>'true', 'class'=>'form-control js-example-tags select2','id'=>$checkpoint['id'].'_c')) !!}

in my database inserted this formate :values 0,1,2 but I need red,blue,green please help me



via Chebli Mohamed

Custom fonts not working in Generated PDF using WKHTMLTOPDF Library

I am using Laravel 5.1 SnappyPDF wrapper, which is using WKHTMLTOPDF library. I am trying to include some custom google fonts for my PDF file, but those fonts are not working in generated PDF file.

I tried, converting fonts into Base64 and also tried to include fonts by absolute URL and relative URL, also tried many answers available at stack overflow but none of them worked for me. How to fix this issue.

//Calling fonts
@font-face {
    font-family: Roboto Condensed;
    src: url("/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.ttf");
}
@font-face {
    font-family: 'Open Sans';src: url("/fonts/OpenSans/OpenSans-Regular.ttf");
}

@font-face {
    font-family: 'Open Sans Semi Bold Italic';
    src: url("/fonts/OpenSans/OpenSans-SemiboldItalic.ttf");
}

 //implenting fonts
.report-page2-col-wrapper .col-heading{
    font-family:"Open Sans Semi Bold Italic";
    font-size:12pt;
    line-height:17pt;
}

see difference in screen shots

1) This is web browser HTML version, looks find and fonts implementing properly


enter image description here

2) This is Generated PDF version, fonts not applying properly


enter image description here



via Chebli Mohamed

mercredi 21 décembre 2016

how to get single id from array

need help , I am new in laravel framework,here how we can passed the checkpoint id this is my code.

 $data['checkpoints'] = CheckpointTemplate::where('checklist_template_id', $data['checklist']->checklist_template_id)->where('is_flexible',0)->orderby('sort_order', 'asc')->orderby('sort_order', 'asc')->get()->toArray();

this working fine, but here how to passed $data['checkpoint_error_msgs'] = CheckpointErrormsg::where('checkpoint_id',**$data['checkpoints']->id**)-> orderby('error_message', 'asc')->lists('error_message', 'error_message');



via Chebli Mohamed

Unable to pass multiple values in not like clause Laravel

I am working on a Laravel project and want to post multiple values in a not like clause.
I have tried the following way with no success.

    $exclude_emails=['%odz%', '%test.com%'];

    $vendors=\DB::table("vendor_infos")
              ->where("vendor_infos.email", 'not like', '%'.$exclude_emails.'%' )
              ->orderByRaw("RAND()")->take(8)->get(['vendor_infos.*']);

I have also tried to pass it as string, but still no success,

Please let me know where i am wrong.

Thanks.



via Chebli Mohamed

Lumen: PHPUnit give failure but testing passed in Gitlab CI Runner

This is my first time to use testing in my project. I use Gitlab CI and gitlab runner to perform test. But something weird happened, when phpunit executed the output is failure, but the test result in gitlab is passed. Gitlab should be show failed result.

I use Lumen 5.1. And Gitlab Runner using docker.

This is my .gitlab-ci.yml file

image: dragoncapital/comic:1.0.0

stages:
 - test

cache:
 paths:
  - vendor/

before_script:
 - bash .gitlab-ci.sh > /dev/null

test:7.0:
 script:
  - phpunit

This is my .gitlab-sh.sh file

#!/bin/bash

# We need to install dependencies only for Docker
[[ ! -e /.dockerenv ]] && exit 0

set -xe

composer install
cp .env.testing .env

The log and result:

Fail test, passed status

As you can see the phpunit test fail, but the status in gitlab CI is passed.



via Chebli Mohamed

How can I register a new language key at run time with Laravel?

I wrote a script with Laravel 5.3 that checks if a lang key exists in a giving language at run time. If the key does not exists, it will add it to the file.

However, if the first time around the key does not exists and I add it, then I do another check "during the same request" to see if the key exists, it will say it does not exist. So the loaded languages will not be aware that I added new keys to the file since Laravel loaded the keys in memory and I am only writing to the file on the hard-disk.

when I evaluate the Illuminate\Translation\Translator class I see that the load method checks if a groups is load it does not load it again.

Here is the Laravel Code

/**
 * Load the specified language group.
 *
 * @param  string  $namespace
 * @param  string  $group
 * @param  string  $locale
 * @return void
 */
public function load($namespace, $group, $locale)
{
    if ($this->isLoaded($namespace, $group, $locale)) {
        return;
    }

    // The loader is responsible for returning the array of language lines for the
    // given namespace, group, and locale. We'll set the lines in this array of
    // lines that have already been loaded so that we can easily access them.
    $lines = $this->loader->load($locale, $group, $namespace);

    $this->loaded[$namespace][$group][$locale] = $lines;
}

Is there a way to force Laravel to read the language each time I request? Or, is there a way to add a key to the currently-in-memory keys? How can I tell laravel that I added new keys?



via Chebli Mohamed

Could I use ThrottleRequests class in my controller to get remaining attempts?

Route

Route::post('/AuthenticateUser', 
    array(
        'uses'          =>  'API\Auth\apiLoginController@AuthenticateUser', 
        'as'            =>  'AuthenticateUser',
        'middleware'    =>  ['throttle: 6,1']
    )
);

Controller Action Method

class apiLoginController extends Controller
{
    use ThrottlesLogins;

    public function AuthenticateUser(LoginRequest $request) {        
        //If request fails then calling `$this->TotalAttemptsLeft($request)`
        'Message'   =>  "Invalid credentials" . $this->TotalAttemptsLeft($request) 
                                              . " attempts left.",
    }
}

Details about the issue

ThrottlesLogins class present here :

vendor\laravel\framework\src\Illuminate\Foundation\Auth\ThrottlesLogins.php

has a function called throttleKey which uses username and IP address for the key whereas ThrottleRequests class which is present here:

\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php

uses $request->fingerprint(); function to get key

What's the problem?

In the controller action method above: I am unable to get total attempts left using method TotalAttemptsLeft in ThrottlesLogins class.

Question?

Is there any way if I could use ThrottleRequests class in my controller to get remaining attempts? or please suggest any appropriate way



via Chebli Mohamed

How do I override package language files in Laravel 5.1

According to Laravel Docs: http://ift.tt/2hdzzbr

for example, if you need to override the English language lines in messages.php for a package named skyrim/hearthfire, you would place a language file at: resources/lang/vendor/hearthfire/en/messages.php.

I currently have the package activewebsite/enterprise-entity package that I am including in my project. It contains a language file:

vendor/activewebsite/enterprise-entity/src/resources/lang/en/phone.php

This file contains translations for types of phone numbers:

'phone_1' => 'Home',
'phone_2' => 'Work',
'phone_3' => 'Mobile',
'phone_4' => 'Office',
'phone_5' => 'Fax',
'phone_6' => 'Fax 2',
'phone_7' => 'Home 2',
'phone_8' => 'Direct',

Following the example above, I attempted to override this file by creating the following directory:

resources/lang/vendor/enterprise-entity/en/phone.php 

containing an additional phone number specific to this project:

    'phone_9' => 'Rapid Rewards Text Alert Number',

But the the translation does not come through to the front-end. The only way I've been able to get the translation to appear is to edit the language file within the enterprise-entity package.

I found this thread: http://ift.tt/2hs8kX2 Where another user seems to be having a similar issue, but it is suggested that they use the directory structure:

/lang/{locale}/{vendor}/{plugin}/lang.php

so I attempted

/lang/en/activewebsite/enterprise-entity/phone.php

with no luck.

Can anyone tell me what I may be getting wrong here? I've attempted running a php artisan optimize after each change to see if that could clear things up, but no luck.

Thanks!



via Chebli Mohamed

mardi 20 décembre 2016

Closing database connection In Laravel 5.1

Is that possible to close the database connection after running each database query in Laravel 5.1. I have already built an application by using the Laravel 5.1 and PostgreSQL, and in my server there are limited number of connections has been provided to connect with the database, that's why sometimes I am getting the error "To Many Connections". So please tell me how I can resolve this problem.

I am not sure if Laravel automatically closes the db connection after each db request.

Thanks in advance...



via Chebli Mohamed

Address in mailbox given [] does on Laravel

in there i have been create function for send an email, here my code like this :

$row=DB::table('orders')
->join("cms_members","cms_members.id","=","orders.id_cms_members")
->select("orders.*","cms_members.email as email","cms_members.name as name","cms_members.phone as phone")
->where('orders.id',$id_order)
->first();
$datas = array(
                    'name' => 'test',   
                    'detail'=> 'test',
                    'sender' => 'adamprojo@gmail.com'
                );
$customPaper = array(0,0,800,800);
$pdf = PDF::loadView('testing', $data)->setPaper($customPaper);
Mail::send('emails.temp', $datas, function($message) use($pdf)
{
$message->from("no-reply@crocodic.net","Invoice HOP Daily rent Orders");
$message->to($row->email)->subject('Invoice');
$message->attachData($pdf->output(), "invoice.pdf");
});

here my problem when ever i want to send an email i get response

Address in mailbox given does not comply with RFC 2822, 3.6.2.

but if i try to print the email its give me the email address. what should i do ?

have someone give me solution for my problem so its can work like what i want ?



via Chebli Mohamed

Laravel + PostgreSQL Ltree

How to write the migration file to add the field type 'ltree' (PostgreSQL)

Schema::create('table', function (Blueprint $table) {
     ....
$table->ltree('path');
}

Does not work.

Thanks!



via Chebli Mohamed

How can i create controller in laravel

Hi I want to create controller but i tired because of command show could not open input file php:artisian what's the problem's can you help me.



via Chebli Mohamed

lundi 19 décembre 2016

Sending multi-dimensional array with files using cURL

Is there a proper way to POST a multi-dimensional array with files using cURL? I am in control of the receiving back-end, which is built using Laravel. But I'm trying find a way to send the data endpoint using cURL, because it's how a client connects to our API and I'm trying to assist them with that.

If I use a Chrome add-on called Postman, I'm able to use the endpoint as intended. But is there a way to make it work using cURL?

I've tried something like:

    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://ift.tt/2gVqdMJ',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data,
    ]);

    $files = array(
        ['file_data' => new \CURLFile('logo.jpg'), 'file_type' => 1],
        ['file_data' => new \CURLFile('logo2.jpg'), 'file_type' => 2],
    );

    $data = ['files' => $files];

    $response = curl_exec($ch);

    curl_close($ch);

But then I get an Array to string conversion error.

The endpoint expects a parameter called files to be an array, which contains an array of files and their type.

Thanks in advance.



via Chebli Mohamed

dimanche 18 décembre 2016

Extending views in laravel package

I am trying hard to extend the views in laravel package . I have try many methods . But nothing is working. I have researched on Google also but no result . Please help me . It is very easy in laravel but not in laravel package



via Chebli Mohamed

User is not allowed to see the application : when user test login facebook

User is not allowed to see the application.: The user is not allowed to see this application per the developer set configuration. enter image description here



via Chebli Mohamed

samedi 17 décembre 2016

How to get data from variable in ln laravel 5.2

My database table has name,phone,email etc fields.Now I store particular field data in different variable and pass them.here is my code. I tried it from controller function. what should I do?

$var=DB::select("SELECT * FROM reg where email = '$c_email' and Password = '$c_pass' and type = '$c_type'");
   $var2=$var->name;
   $var3=$var->phone;
return redirect('farmer')->with('key', $var2)->with('key2', $var3);



via Chebli Mohamed

How to pass session value in laravel 5.2

I want to pass $var variable with session to a page . And want to receive this data.

public function check(Request $request)
{
    $c_email = $request->email;
    $c_pass=$request->pass;
    $c_type=$request->select;
    //dd($Idpass);
   $var=DB::select("SELECT * FROM reg where email = '$c_email' and Password = '$c_pass' and type = '$c_type'");
   if ($var) {
       session_start();
       $request->session()->put('key', '$var');
     return redirect('farmer');
   }
   else {
    $msg="Invalid login";
    return view('index')->with('show',$msg);
   }
}



via Chebli Mohamed

jeudi 15 décembre 2016

Is it possible to create a model from mysql database table in laravel

I know that in Laravel we can create a model and migrate them into database.

model ----> migrate ----> table to SQL server.

But my question is there any way to inverse this operation.

i.e

SQL server ---> table_name ----> class table_name extends Model { // }



via Chebli Mohamed

form update with file upload laravel

I'm having a bit of an issue when it comes to updating a form and and having an file input. Here is what I am working with.

I have a form in laraval 5.1 which has a post method and a hidden 'Patch' method. This works as is should updating the fields that are in the form. However, when it introduce:

<input type="file" id="profile_picture" name="image_url" />

into the form, i get a:

MethodNotAllowedHttpException in RouteCollection.php line 218:

laravel error. I have tried changing the

 <input type='hidden' name='_method' value='PATCH'>

to PUT and it still doesnt like it.

My form looks like this:

<form action='' method="post" class="form-horizontal" enctype="multipart/form-data">

route resource looks like this:

Route::resource('profiles', 'ProfilesController');

I can't figure out what I am missing here...Any help is much appreciated.



via Chebli Mohamed

Laravel Middleware - ReflectionException in Container.php

I'm looking for help because I'm having this error message when I try to load an Middleware.

ReflectionException in Container.php line 741:
Class roles does not exist

I've checked the Kernel, namespaces,etc. and it seems to be ok. I'll post it anyway because maybe I'm missing something.

Kernel.php

<?php

namespace Imuva\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {

    use \Arcanedev\Localization\Traits\LocalizationKernelTrait;

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Imuva\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Imuva\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Imuva\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \Imuva\Http\Middleware\RedirectIfAuthenticated::class,
        'roles' => \Imuva\Http\Middleware\RolesMiddleware::class,
    ];

}

Stock RolesMiddleware (placed in /app/Http/Middleware)

<?php
namespace Imuva\Http\Middleware;

use Closure;

class RolesMiddleware
{
    public function __construct() {

    } 
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

Using it

<?php

namespace Imuva\Http\Controllers;

use Illuminate\Http\Request;
use Imuva\Http\Requests;
use Imuva\Http\Middleware; // This is just testing
use Imuva\Http\Controllers\Controller;
use Session;
use Redirect;
use Illuminate\Routing\Route;
use Barryvdh\DomPDF\Facade as PDF2;
use Barryvdh\Snappy\Facades\SnappyPdf as PDF;
use Imuva\GoogleCalendar;


class ActividadesController extends Controller {

    public function __construct() {
        $this->middleware('roles');
        $this->beforeFilter('@find', ['only' => ['edit', 'update', 'destroy', 'show', 'cartelH', 'cartelV']]);
    }

I've run the commands "composer dump autoload" , "php artisan clear-compiled" and "php artisan optimize" but the error still appears when I try to access to any function included on this Controller.

Someone can help me? Thanks so much.



via Chebli Mohamed

mercredi 14 décembre 2016

Laravel Cashier creates customer but not subscription

I'm using Laravel 5.2 and after deploying my app the stripe checkout doesnt work. In localhost mode it works and creates a customer with subscription but in production it throws an "InvalidRequest" error and only creates a customer in Stripe but without the subscription.

The apikeys are set in services, stripe and .env and it gets the stripeToken.

                try {
                  // Use Stripe's library to make requests...

                    $user = new User;

                    $user->name = $request->input('name');
                    $user->email = $request->input('email');
                    $user->password = Hash::make($request->input('password'));
                    $user->created_at = Carbon::now();
                    $user->save();

                    $creditCardToken = $request->input('stripeToken');

                    $user->newSubscription('Silver', 'Silver')->create($creditCardToken);


                } catch(\Stripe\Error\Card $e) {
                  // Since it's a decline, \Stripe\Error\Card will be caught

                    $error = 'Det verkade vara något fel med ditt kreditkort. Vänligen testa igen.';
                    return redirect()->back()->with('error', $error);  

                } catch (\Stripe\Error\RateLimit $e) {
                  // Too many requests made to the API too quickly

                    $error = 'Vi upplever för tillfälligt ett högt tryck. Vänligen försök igen om en liten stund.';
                    return redirect()->back()->with('error', $error);  

                } catch (\Stripe\Error\InvalidRequest $e) {
                  // Invalid parameters were supplied to Stripe's API

                    $error = 'Ops! Något gick fel. Vänligen testa igen';
                    return redirect()->back()->with('error', $error);  

                } catch (\Stripe\Error\Authentication $e) {
                  // Authentication with Stripe's API failed
                  // (maybe you changed API keys recently)

                    $error = 'Ops! Något gick fel. Vänligen konktakta kundtjänst så vi kan fixa problemet. Tack!';
                    return redirect()->back()->with('error', $error);  

                } catch (\Stripe\Error\ApiConnection $e) {
                  // Network communication with Stripe failed
                    $error = 'Ops! Servern är för tillfälligt nere. Vänligen testa inom kort igen.';
                    //return redirect()->back()->with('error', $error);  

                } catch (\Stripe\Error\Base $e) {
                  // Display a very generic error to the user, and maybe send
                  // yourself an email
                    $error = 'Ops! Något gick fel.';
                    //return redirect()->back()->with('error', $error);  
                } catch (Exception $e) {
                  // Something else happened, completely unrelated to Stripe
                    $error = 'Ops! Något gick fel. Vänligen kontakta kundtjänst.';
                    //return redirect()->back()->with('error', $error);  
                }

                    $name = $request->input('name');

                    return view('checkout.confirmation', compact('plan', 'name'));



via Chebli Mohamed

Laravel set view from helper

I have a simple helper (/app/Helpers/Helper.php). Is is possible to set a view from helper's function? How can i do that?

Notice: this function called in controller's __construct

public function __construct()
{
   set_view();
}

Thank you!



via Chebli Mohamed

Laravel - Validator double - ERR_TOO_MANY_REDIRECTS

Hi have more than 1 forms for a payment procedure

Here my payment steps

Step 1 - Form input datas;
Step 2 - Valide data of Step 1;
Step 3 - Form input other datas;
Step 4 - Valide data of Step 2;

In the second validation, if validator fail I return...

return redirect()->back()->withErrors($validator)->withInput();

The problem is that, if the second validation fail, it give me this error int he browser

ERR_TOO_MANY_REDIRECTS


I think is due because it redirect()->back() to previous Step 1 and so to the previous validator... and going in to loop.

Now I'have solved returning a View

return View('staff.cedola', $data)->withErrors($validator);

Is this the right way?



via Chebli Mohamed

Insert on duplicate key update with laravel 5.1 eloquent (only one query)

I wan to perform insert on duplicate key update with eloquent model without making two queries ,the problem is when i use updateOrCreate() it does two queries

 /**
 * Create or update a record matching the attributes, and fill it with     values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return static
 */
public static function updateOrCreate(array $attributes, array $values = [])
{
    $instance = static::firstOrNew($attributes);
    //seconde querie
    $instance->fill($values)->save();

    return $instance;
}
public static function firstOrNew(array $attributes)
{
    //first query
    if (! is_null($instance = (new static)->newQueryWithoutScopes()->where($attributes)->first())) {
        return $instance;
    }

    return new static($attributes);
}

thanks :)



via Chebli Mohamed

lundi 12 décembre 2016

product.ERROR: exception 'Aws\Sqs\Exception\SqsException'

In Laravel 5.1 I'm receiving the following error:

product.ERROR: exception 'Aws\Sqs\Exception\SqsException' with message 
'Error executing "ReceiveMessage" on "http://ift.tt/1CL6jLd"; AWS HTTP error: Client error: `POST http://ift.tt/1CL6jLd` resulted in a `403 Forbidden` response:
<?xml version="1.0"?><ErrorResponse xmlns="http://ift.tt/1rrYF3s"><Error><Type>Sender</Type><Code>I (truncated...)
 InvalidClientTokenId (client): The security token included in the request is invalid. - <?xml version="1.0"?><ErrorResponse xmlns="http://ift.tt/1rrYF3s"><Error><Type>Sender</Type><Code>InvalidClientTokenId</Code><Message>The security token included in the request is invalid.</Message><Detail/></Error><RequestId>f2ee54a4-bc0f-56cf-959f-046ce8302605</RequestId></ErrorResponse>'

But i didn't use Sqs. My config: QUEUE_DRIVER=async

What happend? Thanks.

GuzzleHttp\Exception\ClientException: Client error: `POST http://ift.tt/1CL6jLd` resulted in a `403 Forbidden` response:
<?xml version="1.0"?><ErrorResponse xmlns="http://ift.tt/1rrYF3s"><Error><Type>Sender</Type><Code>I (truncated...)
 in /iwzdata/www/taotaoe/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:111
Stack trace:
#0 /iwzdata/www/taotaoe/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /iwzdata/www/taotaoe/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /iwzdata/www/taotaoe/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
#3 /iwzdata/www/taotaoe/vendor/guzzlehttp/promises/src/TaskQueue.php(47): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise\{closure}()



via Chebli Mohamed

laravel- how can i get a user with all roles and all permissions with per role in orm in 5.1 with zizaco?

I create all model and relations . one user have many Roles and one Role have many Permissions. i want a elequent that give a user with all roles and all permission for per role.



via Chebli Mohamed

dimanche 11 décembre 2016

In Laravel email sending issue.?

I am trying to send email using laravel framework,but I can't.Actually when I put my code and trying to run on wamp server. I got this error.

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

My Route code:

Route::get('sendemail','admin\LoginController@sendemail');

MY Controller code:

namespace App\Http\Controllers\admin;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Mail;
use App\Mail\Reminder;

 public function sendemail(Request $request)
{
     $postsite1234 = $request->all();

     $email = $postsite1234['email'];   

    $to_email = 'bdt.svk@gmail.com';



        Mail::send('emailconfirm',['name' => 'yuven'], function ($message){
         $message->to($to_email,'vijay')
                 ->subject('code');
         $message->from('vijay@app.com', 'vijay');


    });


}

Can I send email using wamp server in localhost.? Is that work? please help If you can.



via Chebli Mohamed

Show Welcome Message in Angularjs

My Laravel Code is here

<a class="navbar-brand" href="">
    @if (Auth::guest())
        
    @else
        Welcome {!! \Auth::user()->UserName !!}
    @endif
</a>

I am trying to convert this into Angular Js

Here is my code in Html.

<a class="navbar-brand">
    
</a>

and code in Controller

myApp.controller("NavController", ["$scope", "UserModel", function($scope, UserModel) {

    $scope.WelcomeMessage = function() {
        debugger;
        if(UserModel.GetUserObject() !== null) {
            return "Welcome " + UserModel.GetUserObject().UserName;
        }
        else {
            return "Welcome ";
        }
    };
}]);

Controller reference is present in layout file but due to some reasons Controller is not even hitting debugger.

Am I missing something?



via Chebli Mohamed

samedi 10 décembre 2016

Partial is showing 404 in AngularJs


Directory Structure is here. I can't show it because of insufficient reputation score.

Base Controller

myApp.controller("BaseController", ["$scope", function($scope) {
    $scope.Navigation = [];
    $scope.NavigationUrl = "Templates/Partials/Include/Navigation.html";
}]);

Login Page Html

<div ng-include="NavigationUrl"></div>
then the html for login Page

Master blade

<!DOCTYPE html>
<html ng-app="myApp">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div class="container" ng-controller="BaseController">
            <div ng-view></div>
        </div>
        <script type='text/javascript' src='{!! asset("bower_components/angular/angular.min.js") !!}'></script>
        <script type='text/javascript' src='{!! asset("bower_components/angular-route/angular-route.min.js") !!}'></script>
        <script type='text/javascript' src='{!! asset("bower_components/angular-cookies/angular-cookies.min.js") !!}'></script>

        <script type='text/javascript' src='{!! asset("App/Controller/BaseController/BaseController.js") !!}'></script>
    </body>
</html>

When I see login page, I got 404 error for navigation.html.

Am I missing something?



via Chebli Mohamed

Laravel - Load common header and footer to view

I am new to laravel and I am trying to load header, footer and the view file from controller in a common template and display the data from controller in the view file. But I am get error View ['admin.dashboard'] not found.

The dashboard file is present in admin folder inside views

controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class common extends Controller
{

   public function login()
   {
        $data['title'] = 'Dashboard';
        $data['template'] = 'admin/dashboard';
        return view('common_template', compact('data'));

   }
}

common_template.blade View

<?php echo View::make('includes/header'); ?>

<?php echo $template = "'".$data['template']."'"; 
echo View::make($template); ?> 
<?php echo View::make('includes/footer'); ?>

When I add 'admin/dashboard' instead of $data['template'] directly in $template it loads the dashboard file whereas it doesnt load when i pass it as string from controller.

dashboard.blade view

<p><?php echo $data['title']; ?></p> //printing the data from the controller

Kindly help me get through this. Thanks



via Chebli Mohamed

vendredi 9 décembre 2016

Laravel 5.1 Mail::raw works but Mail::send doesn't

I am using Laravel 5.1 email with Amazon SES.

If I use:

Mail::send('mymail', function ($m) use ($user) or Mail::send('mymail', $data, function ($m) use ($user) It doesn't work. I get a 500 error.

However if I use:

Mail::raw('Hello this is a test message', function ($m) use ($user) it works fine.

Any thoughts what could be causing this?



via Chebli Mohamed

Laravel Homestead vagrant up times out

I'm following the official guide for running Laravel 5.1 on Homestead.

But when I try vagrant up it hangs up at homestead-7: SSH auth method: private key and eventually times out with the message:

Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.

If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.

If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.

My SSH keys where generated using this command:

ssh-keygen -t rsa -C "you@homestead"

I'm using Ubuntu 16.04 64-bit, Vagrant 1.8.4 and VirtualBox 5.0.18. Virtualization is enabled in my computer, other boxes boot up without problems.

Tried vagrant destroy and deleting the ~/.homestead folder to start again from scratch, but same results.

Here is my ~/.homestead/Homestead.yaml file.

I'm not uploading the vagrant log file because it's too large for PasteBin but I can upload it compressed if needed.



via Chebli Mohamed

how can i detect language in laravel 5.1 api for validation error?

I have a api in laravel and I want return validation errors in user's language. how can I specify language in laravel api? for example response this :

 if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->getMessageBag()->getMessages(),
            ], 400);
        }

return best for each language. fa and en.



via Chebli Mohamed

jeudi 8 décembre 2016

Laravel 5.1 + google drive API 3.0 download from google drive

I try download file from google drive using google drive API 3.0, but i don't understand how actually save file.

I do this: $content = $service->files->export($fileId, 'application/pdf', array( 'alt' => 'media' ))

And get:

GuzzleHttp\Psr7\Response Object
(
    [reasonPhrase:GuzzleHttp\Psr7\Response:private] => OK
    [statusCode:GuzzleHttp\Psr7\Response:private] => 200
    [headers:GuzzleHttp\Psr7\Response:private] => Array
        (
            [Expires] => Array
                (
                    [0] => Mon, 05 Dec 2016 19:39:38 GMT
                )

            [Date] => Array
                (
                    [0] => Mon, 05 Dec 2016 19:39:38 GMT
                )

            [Cache-Control] => Array
                (
                    [0] => private, max-age=0, must-revalidate, no-transform
                )

            [Content-Disposition] => Array
                (
                    [0] => attachment
                )

            [Vary] => Array
                (
                    [0] => Origin
                    [1] => X-Origin
                )

            [Content-Type] => Array
                (
                    [0] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
                )

            [X-Content-Type-Options] => Array
                (
                    [0] => nosniff
                )

            [X-Frame-Options] => Array
                (
                    [0] => SAMEORIGIN
                )

            [X-XSS-Protection] => Array
                (
                    [0] => 1; mode=block
                )

            [Content-Length] => Array
                (
                    [0] => 4312
                )

            [Server] => Array
                (
                    [0] => GSE
                )

            [Alt-Svc] => Array
                (
                    [0] => quic=":443"; ma=2592000; v="36,35,34"
                )

        )

    [headerNames:GuzzleHttp\Psr7\Response:private] => Array
        (
            [expires] => Expires
            [date] => Date
            [cache-control] => Cache-Control
            [content-disposition] => Content-Disposition
            [vary] => Vary
            [content-type] => Content-Type
            [x-content-type-options] => X-Content-Type-Options
            [x-frame-options] => X-Frame-Options
            [x-xss-protection] => X-XSS-Protection
            [content-length] => Content-Length
            [server] => Server
            [alt-svc] => Alt-Svc
        )

    [protocol:GuzzleHttp\Psr7\Response:private] => 1.1
    [stream:GuzzleHttp\Psr7\Response:private] => GuzzleHttp\Psr7\Stream Object
        (
            [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #334
            [size:GuzzleHttp\Psr7\Stream:private] => 
            [seekable:GuzzleHttp\Psr7\Stream:private] => 1
            [readable:GuzzleHttp\Psr7\Stream:private] => 1
            [writable:GuzzleHttp\Psr7\Stream:private] => 1
            [uri:GuzzleHttp\Psr7\Stream:private] => php://temp
            [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array
                (
                )
        )
)

I tried many things from documentation by GuzzleHttp, but they didn't work...

Please help me to know what I must to do to download file.



via Chebli Mohamed

How to integrate ccavenue payment gateway in laravel frame work?

I have Larvel 5.1 and composer version 1.2.0 and it setup on ubuntu 14,04 . I struck in step 4(Publish the config & Middleware by running in your terminal) and displays error message like "FatalErrorException in ProviderRepository.php line 146: Class 'Softon\Indipay\IndipayServiceProvider' not found". Please help to solve this.



via Chebli Mohamed

mercredi 7 décembre 2016

Laravel make like post

Is it possible make posts like without Login? And how can I do it. I've got it the when laravel cookies set i need pass it to all of my views! is it true? how can in pass cookies to all of my views now :|



via Chebli Mohamed

lundi 5 décembre 2016

Artisan::call('db:seed') not work in production

My app is Laravel 5.1 and artisan call method work fine in local. But not work in production.

Artisan::call('db:seed', [
      '--class'   => 'ResetSeeder',
      '--force'   => true
]);

This is my code in controller. when i var_dump this code in local and production; return zero (0). But local is execute and production not_execute.

My database settings is perfect. All system methods work fine. Only Artisan::call() is not working.

NOTE: when i call "php artisan db:seed --class=ResetSeeder --force" command on console. This command work fine in console too.

Thank you so much for help me and sorry my English.



via Chebli Mohamed

Cron job is running two different commands : Laravel 5

My command on godaddy server for Cron job is below.

/usr/local/bin/php -q public_html/Publisher/artisan schedule:run > /dev/null 2>&1

My app\Console\Kernel.php is here

class Kernel extends ConsoleKernel
{
    protected $commands = [
        'App\Console\Commands\ytzAPI',
        'App\Console\Commands\Invoice',
    ];

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('api:ytz')->everyMinute();
        $schedule->command('api:invoice')->daily();
    }

    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

My Question

I want to run one command after every minute and another command on daily basis.

$schedule->command('api:ytz')->everyMinute();
$schedule->command('api:invoice')->daily();

Cron job is running after each minute and is running $schedule->command('api:invoice')->daily(); also. How could I differentiate everyMinute command from daily



via Chebli Mohamed

Error trying to send Email using Mailgun in Laravel 5.1

I have a problem when I try to send emails with Mailgun, I already configured my project according the documentation in the page on Mailgun and some tutorials, but the error still there, I hope someone help's me!!

Here is the error:

Mailgun on Laravel 5.1 error

Here is the code:

Env configuration

MAIL_DRIVER= mailgun
MAILGUN_DOMAIN= sandbox***************.mailgun.org
MAILGUN_PASS= key-********************************

Services configuration

'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_PASS'),
]

Controller

$data = [];
    \Mail::send('emails.plantilla', $data, function($message){
        $message->from('some@gmail.com')
                ->to('aguilas@hotmail.com')
                ->subject('Probando mailgun en laravel 5.1');
    });



via Chebli Mohamed

How to change database name before authentication in laravel 5.1

I have multiple database. I want to change db name based on the url dynamically. How can I set particular db before authentication.

I want to change database from authentication to through out the application. For ex. If url is like http://ift.tt/2gsUWkY then it will select database company1

If url is like http://ift.tt/2gYbt3y then it will select database company2

Based on the selected database authentication will be done and selected database will be used for that user.



via Chebli Mohamed

dimanche 4 décembre 2016

How to make reverse relationship for multiple Role in Laravel

i`m using Entrust and has 3 types of users (Admin,Moderator, Player); I have 2 tables: Users and Hall (Game place); All this users (Admin, Moderator, Player) are stored in the Users table; so Admin and Moderator can make Hall; Users connected with hall_id;

I did relationship in Hall with Users for Owner_Id (who created Hall); and i want do same back for Players;

Users: when i did something in migration like $table->foreign('hall_id')->references('id')->on('hall') => i have error; Of course I do not forget to register unsigned() and hall_id is integer;

[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (bingo.#sql-396_1dc, CONSTR AINT users_hall_id_foreign FOREIGN KEY (hall_id) REFERENCES hall (id )) (SQL: alter table users add constraint users_hall_id_foreign foreig n key (hall_id) references hall (id))


I want get about hall information of Players



via Chebli Mohamed

Laravel mail queue wrong mailgun domain

I m using Laravel 5.1 and for sending emails I use:

Mail::queue(XYZ, compact(ABC), function($message) use ($mailTo)
                {
                    $message->from(XXX, XXX);
                    $message->to(XXX)->subject(XXX);
                });

In the services.php I have:

'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
],

and everything works as expected.

However I had to change my Mailgun domain from sandboxXXXXXXXXXXXXX.mailgun.org to my.domain.com

and email are not delivered using the new domain unless I use Mail::send instead of Mail::queue. I also ran php artisan queue:restart, php artisan cache:clear and finally I restarted the supervisor on my server but it didn't work. In my log file I can see that using Mail::queue, Guzzle is still using the old domain while contacting Mailgun even if there is not any trace of the old domain in the code anymore.

Any suggestion?!

How can I fix this issue and be able to queue my emails using the new domain?

Thanks for your help!



via Chebli Mohamed

laravel - auth in laravel API

I have a question about token expire in laravel 5.1 . when a user login to app in mobile, app send a token with expire time to mob. mob use this for 1 hour. now after 1 hour how app get new token? we have to send user to login page and user have to login per 1 hour? I can't know how can i refresh token before expire that.



via Chebli Mohamed

samedi 3 décembre 2016

on the fly change database in laravel 5

Scenario is - User will register on a site. After registration it will create new database and tables for that user. Now when the new user will try to login, he should be able to connect with newly created database.

If 10 user register then it will create 10 database. Each user has own database.

Now how can I set database for user on the fly.



via Chebli Mohamed

Is there any way to extend blog pluging to import xml file

Just been looking at October cms and I would like to extend the import funtion to include xml files is this posible in Ocotber I have looked on the october forum but unable to find any info on this, I like the way the blog section imports csv file and would like to do something similar but with xml. I noted that the ImportExportController uses League\Csv\Reader namespace is there something similar for XML



via Chebli Mohamed

Validation Issue in Select : Laravel 5.3

My Form is like below

<form method="POST" action="http://localhost:1234/Update" accept-charset="UTF-8">
    <input name="_token" type="hidden" value="bVyYZGPprZKHab8sQXairqhtwszTeQ36LRhp9u2k">
    <input type="hidden" name="_token" value="bVyYZGPprZKHab8sQXairqhtwszTeQ36LRhp9u2k">

    <select class="form-control" name="TypeID">
        <option value="-1">Please select Payment Type</option>
            <option value="2">Bitcoin</option>
            <option value="1">Paypal</option>
            <option value="3">Pioneer</option>
    </select>
    <button type="submit">Update</button>
</form>

Controller Action Method is like below

public function UpdatePaymentDetails(PaymentDetailsRequest $request) {
}

Request Class is below

class PaymentDetailsRequest extends Request {

    public function authorize()
    {
        return true;
    }

    public function rules() {
        return [
            'TypeID' => 'required|min:1',
        ];            
    }
}

What's the problem?

It is not validating when I don't selected TypeID, Am I missing something?



via Chebli Mohamed

ClientException in Middleware.php line 68: Client error: 404

I'm new to socialite integration in laravel..

Thus finally I did social login for google & also facebook..

But, in LinkedIn it through me an error (exception) like this

ClientException in Middleware.php line 68: Client error: 404

@Route

Route::get('auth/linkedin', 'Auth\AuthController@redirectToLinkedin');
Route::get('auth/linkedin/callback', 'Auth\AuthController@handleLinkedinCallback');

@AuthController

public function redirectToLinkedin()
{
    return Socialite::with('linkedin')->redirect();
}

public function handleLinkedinCallback()
{
    //get the driver and set desired fields
        // $driver = Socialite::driver('linkedin')->fields(['first_name','last_name','email-address']);
    // retrieve the user
        // $user = $driver->user();

    $user       = Socialite::driver('linkedin')->user();
    echo "<pre>";print_r($user);exit();
}

Here, I just try to print all those values retrieved from LinkedIn

But,It always through me the exception as Client error: 404

@Services.php

'linkedin' => [
    'client_id' => 'MYClientID',
    'client_secret' => 'MYSecretKey',
    'redirect' => 'Mycallback URL',
],

How should I solve this issue..Could someone help me..

Thank you in advance



via Chebli Mohamed

vendredi 2 décembre 2016

Laravel 5.1 SES Integration

I'm trying to set up AWS SES integration with my Laravel 5.1 app. I have been research different ways to use the SES integration include SQS. But reading the laravel documentation - it says enter the values for

'key' => 'your-ses-key',
'secret' => 'your-ses-secret'

However, I haven't been able to find a place in the SES console to generate either. Any suggestions?



via Chebli Mohamed

Laravel Broadcast Pusher Event Firing Multiple Times

I have this Laravel 5.1 Event that I fire when a chat is stored. But it is creating multiple broadcasts to Pusher

<?php namespace App\Events;

use App\Events\Event;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class ChatSent extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $channel;
    public $chat;

    public function __construct($channel,$chat)
    {
        $this->channel = $channel;
        $this->chat = $chat;
    }

    public function broadcastOn()
    {
        return ['private-'.$this->channel];
    }
}

I am using Supervisor (supervisord) with multiple workers... not sure if that makes a difference... here's the laravel.conf:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/app/artisan queue:work database --sleep=3 --tries=3 --daemon
autostart=true
autorestart=true
user=ubuntu
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/app/worker.log

Any idea why this may be happening?



via Chebli Mohamed

With query Issue in Eloquent

I have following query which works fine and gives result for StatusType

AddOnModel::with('StatusType')->get();

But when I write below, it does not bind StatusType Records

AddOnModel
::select(\DB::Raw('A.AddOnID, A.AddOn, Count(R.AddOnID) as Total'))
->from( 'tblAddOn as A' )
->with('StatusType')
->leftjoin( 'tblrevenue as R', \DB::raw( 'R.AddOnID' ), '=', \DB::raw( 'A.AddOnID' ) )
->groupBy("A.AddOnID", "A.AddOn")->get();

The part which does not work is this one: ->with('StatusType')

Am I doing something incorrectly?



via Chebli Mohamed

jeudi 1 décembre 2016

laravel 5.1 access-control-origin for restFull api

Guys I'm developing restFull api using laravel 5.1.My endpoints are working correctly on postman. But when I integrate it with front-end it is getting following error.

XMLHttpRequest cannot load http://ift.tt/2gFV6Wq. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ideahubfront.dev' is therefore not allowed access. The response had HTTP status code 500.

I've tried following methods.

(1) created core middle-ware.

 <?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');
    }
}

added it to kernal.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'web' => \App\Http\Middleware\VerifyCsrfToken::class,
        'cors' => \App\Http\Middleware\Cors::class,
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    ];
}

and to routes.php

Route::group(['middleware' => ['web', 'core'], 'prefix' => 'api/v1'], function(){

    // get single user by user id
    Route::get('getuserbyid/{user_id}', 'UserController@getSingleUserById');

    Route::post('users/register', 'UserController@register');

});

After that options requests worked. But post request still same.

(2) Added headers to controller return manually. Like this.

return response()->json([$user, $merchant], 200)
                ->header('Access-Control-Allow-Origin', '*')
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers', 'Cache-Control, Connection, Date, Server, Content-Type, User-Agent,  Accept, Referer, Authorization,Origin,  Accept-Encoding, Content-Length, Host, Connection,  X-Requested-With');

No luck. Guys please help me. I'm dying for this. My clients wants to see the registration. I'm stuck on this.



via Chebli Mohamed

Task Scheduling : Laravel 5.3

I am following this tutorial to schedule a function every minute. Below is my code.

class Kernel extends ConsoleKernel
{
    protected $commands = [
        'App\Console\Commands\Inspire',
    ];

    protected function schedule(Schedule $schedule)
    {
        $schedule->call($this->WriteFile())->everyMinute();
    }

    protected function commands()
    {
        require base_path('routes/console.php');
    }

    private function WriteFile() {
        $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
        $txt = "John Doe\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    }
}

I saw that the txt file is not showing the contents. i placed the txt file in public folder. Am I missing something?



via Chebli Mohamed

PayPal Express Checkout on behalf of a client php

I've received permissions for Express Checkout from my client using the Permissions Service, getting token and token-secret and I can generate the X-PAYPAL-AUTHORIZATION header [contains AccessToken, OAuthSignature, CurrentOAuthTimestamp] as described 'http://ift.tt/1payxXm'

I don't understand how can I call the SetExpressCheckout API on behalf of my client. I don't see the X-PAYPAL-AUTHORIZATION header mentioned in the Express Checkout docs. http://ift.tt/2gM3yUo



via Chebli Mohamed

Controller class not found laravel 5.1

I am new to laravel and I tried to post the values from view to controller. But I am not able to get through as i get error saying FatalErrorException in routes.php line 26: Class 'registration' not found while submitting the form

Routes.php

Route::get('/', function () {
    return view('welcome');
});

Route::get('/register', function(){
return view('register');
});

Route::post('/register_action', function()
{
     $values = registration::store();
});

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\model\registration as register_model

class registration extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        echo 'hello';
        register_model::saveFormData();
    }
}

View

<html>
<head>
    <meta charset="UTF-8">
    <title>Registration</title>
</head>
<body>
    {!! Form::open(array('url' => 'register_action')) !!}
        <p>Name : {!! Form::text('name') !!}</p>
        <p>Email : {!! Form::text('email') !!}</p>
        <p>Password : {!! Form::password('password') !!}</p>
        <p>Confirm Password : {!! Form::password('cpassword') !!}</p>
        <p>{!! Form::submit('Submit') !!}</p>
    {!! Form::close() !!}
</body>
</html>

Please help me to solve the issue and to get the post values in controller. Thanks



via Chebli Mohamed

Update user profile in Laravel 5.1

I am trying to update some user profile data as follows:

To update profile in routes.php

Route::get('/profile/update/{id}', [
        'as' => 'user.edit',
        'uses' => 'UserController@edit'
    ]);

In my UserController.php

public function edit($id)
{
      $user = User::findOrFail($id);

      return view('user/edit', compact('user'));
}

My action in edit.blade.php

{!! Form::model($user, ['action' => ['UserController@update', 'id' => $user->id], 'method' => 'PUT']) !!}
                    <div class="form-group">
                        {!! Form::label('name', 'Name') !!}
                        {!! Form::text('name', $user->name, [
                            'class' => 'form-control'
                        ]) !!}
                    </div>

                    <div class="form-group">
                        {!! Form::label('email', 'E-mail') !!}
                        {!! Form::text('email', $user->email, [
                            'class' => 'form-control'
                        ]) !!}
                    </div>

                    <div class="form-group">
                        {!! Form::label('phone', 'Phone') !!}
                        {!! Form::text('phone', $user->phone, [
                            'class' => 'form-control'
                        ]) !!}
                    </div>

                    <p><button type="submit" class="btn btn-primary">Update Profile</button></p>
                {!! Form::close() !!}

The route for update:

Route::put('/profile/update/{id}', [
        'as' => 'user.update',
        'uses' => 'UserController@update'
    ]);

And the function in the UserController.php

public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);
        $user->update([
            $request->input('name'),
            $request->input('email'),
            $request->input('phone')
        ]);

        return Redirect::route('user.profile');
    }

After updating the field I want (for example the phone), it simply returns to the profile screen, but does not update it in the database. What am I doing wrong? Thank you very much for your help.



via Chebli Mohamed

mardi 29 novembre 2016

Upload file in S3 using Laravel 5.3

Installation Process

I followed this tutorial to install aws Package in Laravel 5.3

My Code is below

$s3 = \App::make('aws')->createClient('s3');

$s3->putObject(array(
    'Bucket'     => 'Bucket_Name',
    'Key'        => 'AWS_ACCESS_KEY_ID',
    'SourceFile' => 'http://domainname/sample.txt',
));

I am trying a txt file with around 50 bytes contents and got below error.

A sha256 checksum could not be calculated for the provided upload body, because it was not seekable. To prevent this error you can either 1) include the ContentMD5 or ContentSHA256 parameters with your request, 2) use a seekable stream for the body, or 3) wrap the non-seekable stream in a GuzzleHttp\Psr7\CachingStream object. You should be careful though and remember that the CachingStream utilizes PHP temp streams. This means that the stream will be temporarily stored on the local disk.

Am I missing something?



via Chebli Mohamed

lundi 28 novembre 2016

Phpunit overriding variable in .env

In my .env file of a laravel 5.1 project i have set the APP_ENV to local, But when i run the test from the terminal the with

vendor/bin/phpunit

the debug and die on

dd(env(APP_ENV));

gives me "testing".

I Have dont a good research on this, tried using the following ways -

  • trying to set the APP_ENV=local pipelining vendor/bin/phpunit form the cli.
  • Trying to add env variable in the phpunit.xml file<env name="APP_ENV" value="local" override="true"> (dosent seem to override though)
  • adding a .env.testing file and setting the APP_ENV=local
  • in the testCase.php file where the application autoloads $app->loadEnvironmentFrom('.env.testing');

none of the above methods give me the expected result rather everytime i run the test give APP_ENV as "testing".

Not able to trace where is phpunit setting this variable from. Pls help out!



via Chebli Mohamed

how can i retrieve username from another collection by using join in laravel

//viewing tickets generated by them $user= Auth::user()->_id; $tickets = ticket::where(function ($query) use ($user) { $query->where('user', '=', $user); })->get();

  //  created ticket by which user
    $atickets = ticket::where(function ($query) use ($user) {
        $query->where('user_assigned', '=', $user);
    })->get();


    return view('ticketviews', compact('tickets','atickets'));

$atickets returns record details such as user_id and ticket details, now i need to display the username for that particular record stored in another collection mongodb. Can anyone suggest me the code to do that.



via Chebli Mohamed

dimanche 27 novembre 2016

Failing to install Laravel/Homestead with VirtualBox via Vagrant

I'm trying to install Laravel / Homestead with VirtualBox via Vagrant. I followed step by step the installation guide but I keep getting this error:

The box 'laravel/homestead' could not be found or
could not be accessed in the remote catalog. If this is a private
box on HashiCorp's Atlas, please verify you're logged in via
`vagrant login`. Also, please double-check the name. The expanded
URL and error message are shown below:

URL: ["http://ift.tt/1KBs0RO"]

I checked that I use latest version of Vagrant(1.8.7).



via Chebli Mohamed

samedi 26 novembre 2016

Passing data from view to controller in Laravel 5.1

i want to pass arguments from a blade view to a function in the controller

index.blade.php

<a href="" class="like">
    Like
</a>

<a href="" class="like">
    Dislike
</a>

PostController.php

  public function getLikePost($post_id, $like_value)
    {
       $post = Post::find($post_id);
       ...
    }

routes.php

Route::get('like', [
        'uses' => 'PostController@getLikePost',
        'as'   => 'like'
      ]);

but i get an error message

ErrorException in PostController.php line 149:
Missing argument 2 for App\Http\Controllers\PostController::getLikePost()

could anyone help me with this issue?



via Chebli Mohamed

Laravel, Image get from storage display correctly but console return status code 404

I'm having this problem where by image get from storage shows in page correctly but console shows status code 404 as shown in the image belowenter image description here



via Chebli Mohamed

Nearby stores in Laravel

i'm try to get neraby store in Laravel 5.1 I have geocoding parser that caluclate coorinate. But i have problem with haversine formulas. Basically i need that from table Aziende (Stores) given a lat, long e category passed trough url, fetch the nearby stores.

I try with this code:

$dove = Input::get('dove');
    $categoria_id = Input::get('id_categoria');
    // 4: check if any matches found in the database table 
    if (!empty($dove)) {
        $response = \GoogleMaps::load('geocoding')->setParamByKey ('address', $dove)->get();
        $response = json_decode($response, true);
        $latitude = $response['results'][0]['geometry']['location']['lat'];
        $longitude = $response['results'][0]['geometry']['location']['lng'];
        $radius = '5';
        $aziende  = DB::table('aziende')
            ->select(
                 ( 'lat * acos( cos( radians(50) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )
                       + sin( radians(37) ) * sin( radians( lat ) ) ) as distance') )->get();




    } else {
    $aziende = DB::table("aziende")->where('categoria', $categoria_id)->get();
 }
 ?>



via Chebli Mohamed

Laravel - group data by created_at field and apply pagination

I need to get previous 10 days activity of a user. In my case i am just getting 10 activity records instead of previous 10 days activity.

*My Code:

$activity   = $this->where('user_id', '=', $userId)->paginate(10);

$activities = collect($activity->items())->groupBy(function($item) {
    return \Carbon\Carbon::parse($item->created_at)->format('d-M-Y');
});

$activity->setCollection($activities);

dd($activity->toArray());

Output:

enter image description here



via Chebli Mohamed

vendredi 25 novembre 2016

Laravel CkEDITOR AND TINYMCE content not post in form issue

I have Laravel 5.1 website developed my domain is http://example.ca I have issue with form submit. I have ck editor integrated in my form if i remove ck editor then form can be submit on correct page if i keep ck editor then form is redirecting on index page. I am sure that issue is because of .ca in domain because in other domains(.com,.in etc...) form works perfect.

I have tried many option but not success i appreciate your help. Thank you



via Chebli Mohamed

How to send Emails in Laravel without using 3rd party tools

I want to send email in laravel without using the 3rd party tool like sendgrid,gmail etc.

I have gone through the various links in forum and google but nothing is upto the mark.

http://ift.tt/2d3DtgC

Can anyone help me out or providing steps to resolve the issue.

Thanks



via Chebli Mohamed

jeudi 24 novembre 2016

Apache 500 error with code 732

I've developed my website and RESTful APIs. Few weeks ago everything was working fine then I found a strange error on my VPS. See the screenshot below:

500 Internal Server Error with code# 732

I'm using:

  • CentOS 6.5
  • Apache 2.2.x
  • PHP 5.6.x with FastCGI
  • Laravel 5.1

The error shows up eventually (not every time), I checked all server logs including Apache access_log.log, error_log.log and domlogs. There was no information about the error.

I also tried to find the issue with top c command and all server resources were free at the time of error. The server was at idle state.

Any help would be great.

Thanks



via Chebli Mohamed

mercredi 23 novembre 2016

Cant mock Cache::rememberForever

using the following code

Cache::shouldReceive('rememberForever')

Gives

Mockery_1_Illuminate_Cache_CacheManager::rememberForever() does not exist on this mock object

The call works (something is cached) but just cant test it.

The others seem ok Cache::get for example

How should this be mocked ?



via Chebli Mohamed

mardi 22 novembre 2016

Laravel 5.1 Logger Timezone

Is there a way I can change the timezone for the Laravel 5.1 logger? I've seen previous discussions where they extended the Monolog class and updated the Service Provider, but that was for an older version of Laravel and it doesn't look like the LogServiceProvider is used anymore.

I see there's a timezone key in the app.php file, but I don't want the whole system to change. I just want to update the timezone for the logs, and keep the rest of the system in UTC.



via Chebli Mohamed

laravel print results to html

i make this style: http://ift.tt/2f3Z8uM

now i need to insert to this html:

   <div class="trading-info">
  <div class="row" data-sameparent="1">
    <div class="col-4">
      <a href="#" class="info-box large" data-samecol="1">
        <div class="holder">
          <h2>Forex trading</h2>
          <h3>LESSON 1</h3>
          <span class="icon-play block"><img src="images/icon7.png" alt="play"></span>
        </div>
      </a>
    </div>
    <div class="col-8">
      <div class="row" data-sameparent="true" data-samecol="1">
        <div class="col-6">
          <a href="#" class="info-box small" data-samecol="true">
            <div class="holder">
              <h2>Stocks trading</h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-6">
          <a href="#" class="info-box small" data-samecol="true">
            <div class="holder">
              <h2>CFD’S trading</h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-6 locked">
          <a href="#" class="info-box small lightbox-open" data-samecol="true">
            <div class="holder">
              <h2>Forex trading strategies</h2>
              <h3>LESSON 1</h3>
              <span class="icon-lock small"><img src="images/icon8.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-6 locked">
          <a href="#" class="info-box small lightbox-open" data-samecol="true">
            <div class="holder">
              <h2>Airsoft trading platform</h2>
              <h3>LESSON 1</h3>
              <span class="icon-lock small"><img src="images/icon8.png" alt="play"></span>
            </div>
          </a>
        </div>
      </div>
    </div>
  </div>
  <div class="row" data-sameparent="true">
    <div class="col-4">
      <a href="#" class="info-box" data-samecol="true">
        <div class="holder">
          <h2>Social trading </h2>
          <h3>LESSON 1</h3>
          <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
        </div>
      </a>
    </div>
    <div class="col-8">
      <a href="#" class="info-box alt" data-samecol="true">
        <div class="holder">
          <h2>Psychology of trading </h2>
          <h3>LESSON 1</h3>
          <span class="icon-play block"><img src="images/icon7.png" alt="play"></span>
        </div>
      </a>
    </div>
  </div>
  <div class="row" data-sameparent="1">
    <div class="col-4">
      <a href="#" class="info-box" data-samecol="1">
        <div class="holder">
          <h2>Sirix &amp; BX8 trading platforms </h2>
          <h3>LESSON 1</h3>
          <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
        </div>
      </a>
    </div>
    <div class="col-8">
      <div class="row" data-sameparent="true" data-samecol="1">
        <div class="col-4 no-padding">
          <a href="#" class="info-box" data-samecol="true">
            <div class="holder">
              <h2>Techfinancials trading platform</h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-4 no-padding">
          <a href="#" class="info-box" data-samecol="true">
            <div class="holder">
              <h2>Market <br> analysis </h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-4 no-padding">
          <a href="#" class="info-box" data-samecol="true">
            <div class="holder">
              <h2>Binary Options Trading </h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

the result from the SQL i have there: title, number lessons.

how i can do it? i have different codes in every row and col tags.

im use laravel framework version 5.1



via Chebli Mohamed