lundi 29 février 2016

ReflectionException in Container.php line 741: Class 7 does not exist with Laravel5.1

I would like to provide the functionality to change his/her password on his/her own on my web application but I found the error addressed on the title so can anyone help me to solve this?

error:

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

    in Container.php line 741
    at ReflectionClass->__construct('7') in Container.php line 741
    at Container->build('7', array()) in Container.php line 631
    at Container->make('7', array()) in Application.php line 674
    at Application->make('7') in Pipeline.php line 123
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
    at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114
    at ControllerDispatcher->callWithinStack(object(PasswordController), object(Route), object(Request), 'prePassword') in ControllerDispatcher.php line 69
    at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\PasswordController', 'prePassword') in Route.php line 203
    at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
    at Route->run(object(Request)) in Router.php line 708
    at Router->Illuminate\Routing\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
    at Pipeline->then(object(Closure)) in Router.php line 710
    at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 675
    at Router->dispatchToRoute(object(Request)) in Router.php line 635
    at Router->dispatch(object(Request)) in Kernel.php line 236
    at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
    at VerifyCsrfToken->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
    at ShareErrorsFromSession->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
    at StartSession->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
    at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
    at EncryptCookies->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
    at CheckForMaintenanceMode->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
    at Pipeline->then(object(Closure)) in Kernel.php line 122
    at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
    at Kernel->handle(object(Request)) in index.php line 54

url:

http://ift.tt/1oLefsT

routing:

Route::post('auth/password', ['as' => 'auth.postPassword', 'uses' => 'PasswordController@postPassword']);
Route::get('auth/password', ['as' => 'auth.prePassword', 'uses' => 'PasswordController@prePassword']);

Controller:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Mail;
use App\Role;
use App\User;

use App\Http\Controllers\Controller;

class PasswordController extends Controller
{
  use ResourceController;

  public function __construct()
  {
    $this->middleware('role:' . Role::ADMIN + Role::OWNER + Role::MANAGER + Role::ACCOUNTANT);
  }

  protected function validator(array $data)
  {
    return Validator::make($data, [
        'password' => 'required|confirmed|min:8',
    ]);
  }

  private function updateData(Request $request)
  {
    $user = User::find($this::getMyId());
    $user->password = $request->input('password');
    $user->remember_token = str_random(60);
    $user->save();

    return $user;
  }

  public function prePassword()
  {
    return view('auth.change');
  }

  public function postPassword($request)
  {
    $validator = $this->validator($request->all());

    if ($validator->fails()) {
      \Session::flash('flash_error', $validator->messages());
      $this->throwValidationException(
        $request, $validator
      );
    }

    $this::updateData($request);
  }
}

view:

{{-- resources/views/auth/change.blade.php --}}

@extends('common.layout')

@section('header')   @parent @endsection

@section('navbar')   @include('common.navbar') @endsection

@section('sidebar')   @include('common.sidebar') @endsection

@section('content')
      <div class="panel panel-default">
        <div class="panel-heading">Login</div>
        <div class="panel-body">
          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input.<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif

          {!! Form::open(array('action' => ['PasswordController@postPassword'], 'class' => 'form-horizontal')) !!}
            <div class="form-group">
              <label class="col-md-4 control-label input-lg">Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control input-lg" name="password">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label input-lg">Confirm Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control input-lg" name="password_confirmation">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary btn-lg" style="margin-right: 15px;">
                  Reset Password
                </button>
              </div>
            </div>
          </form>
        </div><!-- .panel-body -->
      </div><!-- .panel --> @endsection

{{-- resources/views/auth/change.blade.php --}}

I really appreciate of any suggestions and advices in advance.



via Chebli Mohamed

Laravel Event not firing inside a listener

I have an event say EventA. with a handler HandlerA. Inside HandlerA, if a specific case is met, i'm trying to fire EventB. Unfortunately EventB is never getting fired.

I tried to fire EventB inside a controller and it worked just fine.

Is this a bug / is this supposed be like this / am i doing something wrong?

I'm using Laravel 5.1.

Thank you



via Chebli Mohamed

Laravel/MySQL - Error on foreign key contraint & belongsToMany with joins

Framework: Laravel 5.1.28.

MySQL: 5.6.16

When migrating the firemen table or the victims table I receive: General error: 1215 Cannot add foreign key constraint. Even just creating a table with the column name fireman_id produces the same table, even if it's not a foreign key.

users
    id (char36, uuid)
    first_name (varchar, 60)
    last_name (varchar, 60)

firemen
    fireman_id (char36, uuid) - primary foreign which references(id) on (users)

victims
    victim_id (char36, uuid) - primary foreign which references(id) on (users)

fireman_victim
    fireman_id (char36, uuid) - foreign which references(fireman_id) on (firemen)
    victim_id (char36, uuid) - foreign which references(victim_id) on (victims)

  1. The obvious, why is the error occuring?
  2. How can I join the users table to get the name data when doing the following?

This is my Model:

public function victims()
{
    return $this->belongsToMany('App\Victim', 'fireman_victim', 'fireman_id', 'victim_id');
}

In my Controller:

$fireman = Fireman::first();

$fireman->victims();

I can do this but is there a simpler way(Eager Loading? belongsToManyThrough)?

$fireman->victims()->join('users', 'users.id', '=', 'victims.victim_id')->select('first_name', 'last_name);



via Chebli Mohamed

Passing variable to view by with not working in laravel 5.1

I am new in laravel , I want to pass my variable to view by with this is my controller for example :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

class PricesController extends Controller
{

        function getIndex()
        {
            $prices =   Prices::orderBy( 'id' , 'desc' )-> paginate(2) ;

            return view('home')->nest('content' , 'price', compact('prices')  )   ->with( [ 'title' => 'prices page' , 'message' => 'my message text ' ]) ;

        }
}

and this is my master.blade.php :

<!doctype html>
<html lang="fa">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>    {{ $title  }}</title>

    <link rel="stylesheet" href="{{ url()  }}/css/bootstrap.css">
    <link rel="stylesheet" href="{{ url()  }}/css/style.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="http://ift.tt/1fK4qT1"></script>
    <script src="http://ift.tt/1knl5gY"></script>

    <![endif]-->
</head>
<body>

<div class="container">
    @yield("main")
</div><!-- container -->



<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->

<script src="{{ url()  }}/js/bootstrap.min.js"></script>
<script src="{{ url()  }}/js/dropdown.js"></script>
<script src="{{ url()  }}/js/collapse.js"></script>
<script src="{{ url()  }}/js/transition.js"></script>
<script src="{{ url()  }}/js/tab.js"></script>
</body>
</html>

and this is home.blade.php :

@extends('master')

@section('main')
    @include('top_menu')

    <div class="row">
        <section class="col-sm-12 col-md-12   content">

            <div class="row">
                <section class="col-md-12">
                    <div class="in">
                        {!! $content !!}
                    </div>
                </section>
            </div>

        </section>
    </div>


@stop

and this is my price.blade.php :

@if(   empty($prices)     )
    <div class="alert alert-warning">
        No result
    </div>
@else


    @if( !   isset(  $message)     )
            No message
    @else
        {{ $message  }}

        @endif

    <table class="table table-striped">
        <tr>
            <th>name</th>
            <th>yeat</th>
            <th>qnty </th>
        </tr>

    @foreach( $prices as $price )
        <tr>
            <td>  {{$price->product}} </td>
            <td>  {{$price->yaer}} </td>
            <td>  {{$price->quantity}} </td>
        </tr>
    @endforeach
    </table>

    <center>    {!! $prices->render() !!} </center>


@endif

in Output title in <title> {{ $title }}</title> in master.balde.php is passed good and it will show : prices page in page title , But in this part in price.blade.php :

@if( !   isset(  $message)     )
        No message
@else
    {{ $message  }}

    @endif

the output is :

No maessage

how can I fix it ?



via Chebli Mohamed

Send emoji in php or php5

I want send emoji like as iphone or android phone in php. If any buddy have any ideas. How can send emoji in php? I have already sent column in mysql "utf8mb4_unicode_ci". In php web browser Some emoji not showing in color

enter image description here

I want click on a button then show all emoji and select then send. How can show all emoji

enter image description here

please help me.



via Chebli Mohamed

Laravel 5 - passinf data to view when they are null

I have a Model called Data. My Data Model has a show page. On this show page I have tabs where data related to this Model can be inputted. So the show view for Data looks something like this.

<div id="cInfo" class="tab-pane in active fade">
    @if (count($dType) == 0)
        @include('forms.dTypes.dtypes')
    @else
        @include('forms.dTypes.dtypesEdit')
    @endif
</div>
<div id="cAndC" class="tab-pane fade">
    @if (count($dCreative) == 0)
        @include('forms.dCreatives.dcreatives')
    @else
        @include('forms.dCreatives.dcreativesEdit')
    @endif
</div>

dType and dCreative are Models that belong to Data. Relationships have been set up appropiately. Now I am having an issue in my DataController, specifically the show function. At the moment I have something like so

public function show(Data $data)
{
    $dataManager = User::select('userName')->where('id', $data->userId)->first();
    $clientName = Client::select('clientName')->where('id', $data->clientId)->first();

    $dType = DataType::where('dataId', '=', $data->id)->get();

    $dCreative = CampaignCreatives::where('dataId', '=', $data->id)->first();

    return View::make('campaigns.show', compact('data', 'dataManager', 'clientName', 'dType', 'dCreative'));
}

My first problem is with dType and dCreative. So when a Data Model is first added, dType and dCreative have not yet been created.
Therefore, when I get to the show page for Data, I get the error Trying to get property of non-object. These two Collections should only be passed to the view if they have been created.

What would be the best way to achieve this?

Thanks



via Chebli Mohamed

Get the value of dynamically generated radio button n function laravel 5.1

Could someone help resolve how I can get the value of dynamically generated radio button because it is impossible to get the value by the name value.

This is the blade view:

@foreach($myBuyers as $myQuotedProducts)
                            @foreach($product as $products)
                                @if($products->id === $myQuotedProducts->product_id)
                                    @if($myQuotedProducts->user_id === Auth::user()->id)
                                    <TABLE>
                                        {!! $products->productname !!} | {!! count($myQuotedProducts->product_id) !!} 
                                            <TH>SELECT</TH><TH>COMMENTS</TH><TH>PRICE</TH><TH>ACTION</TH>
                                            @foreach($myBuyersCount as $countingBuyers)
                                                @if($countingBuyers->product_id === $myQuotedProducts->product_id)

                                                    <TR><TD>{!! Form::radio('selected'.$myQuotedProducts->product_id, $myQuotedProducts->id) !!}</TD><TD>{!! $countingBuyers->comments !!} </TD><TD>{!! $countingBuyers->price !!} </TD><TD>{!! Form::label('SUBMIT') !!} | {!! Form::label('DECLINE') !!} | {!! Form::label('ONHOLD') !!}</TD></TR>
                                                @endif
                                            @endforeach

                                    </TABLE>
                                    @endif
                                @endif
                            @endforeach
                        @endforeach

Unlike in the normal way of using the name had it been the name is not dynamic, it would have been easy to call the name thus: $biddingComments_id = $request->selectedCounting;but the dynamic part makes it cumbersome getting the name. All i want is to get the value passed to the radio button.

This is the controller I have written for it but I'm very sure it wouldn't work because of the dynamic missing part. Kindly help out.

public function create(Request $request, $id)
    {
        $biddingComments_id = $request->selected;

    }



via Chebli Mohamed

How to move local server to live server in laravel

I want to upload my local project into live server. i aslo changeall the .env related changes. but still it will not working. So,what kind of changes need for live.



via Chebli Mohamed

php - Laravel 5.2 Auth not Working

I want to make a authentication user login and register in laravel. But when I submit to save the register info..It's showing

Object not found!

The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error. If you think this is a server error, please contact the webmaster.

Here is my authController:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */


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

    /**
     * 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, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }


    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

    protected function getLogin() {
        return View('auth.login');
    }

    protected function postLogin(LoginRequest $request) {
        if ($this->auth->attempt($request->only('email', 'password'))) {
                return redirect()->route('/');
          //  return view('course.index');
        }

        return redirect('auth/login')->withErrors([
            'email' => 'The email or the password is invalid. Please try again.',
        ]);
    }

    /* Register get post methods */
    protected function getRegister() {
        return View('auth.register');
    }

    protected function postRegister(RegisterRequest $request) {
        $this->user->name = $request->name;
        $this->user->email = $request->email;
        $this->user->password = bcrypt($request->password);
        $this->user->save();
        return redirect('auth.login');
    }


  protected function getLogout()
    {
        $this->auth->logout();
        return redirect('auth.login'); 
    } 
    protected $redirectTo = '/course';
    protected $loginPath = '/auth/login';

}

Here is my login.blade.php file:

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

        <div>
            Email
            <input type="email" name="email" value="{{ old('email') }}">
        </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>

Here is my register.blade.php file

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

    <div>
        Name
        <input type="text" name="name" value="{{ old('name') }}">
    </div>

    <div>
        Email
        <input type="email" name="email" value="{{ old('email') }}">
    </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 Here is the routes.php

<?php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

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

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

Route::get('all_user/{id}/{name}',function($id,$name){      // Here we pass the peremeter in url all_user
    return 'User '.$id." ".$name;                         // with the parameter id and name
});

Route::get('home','basicController@index'); // Here Home is the URL and it 
                                            //execute the basiccontroller index page
Route::get('about','basicController@about');

Route::resource('course','courseController');

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/


Route::group(['middleware' => ['web']], function () {
   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');
});



via Chebli Mohamed

dimanche 28 février 2016

When Refectring the current statmement

When I try to refecter commented into the static method, its return null. Other wise its ok. why ?

    public static  function Table($input) {
      $name = 'gazett_'.$input['ExamYear'].'_'.$input['gender'].'_'.$input['Examtype'];
      //        $obj = new static;
      //        $obj->setTable($name);
      //        return $obj; if i return insetance its ok, but in given below its return null why ?

      return (new static)->setTable($name);
    }

Here how return current instance from static method ?



via Chebli Mohamed

Laravel 5.1 Eloquent collection not returning correct results

I have an eloquent collection {{ $questions }}, when i output it inside a blade template i get the following results:

[{"question_num":0,"survey_id":2,"question_text":"test","expected_answer":1},
  {"question_num":1,"survey_id":2,"question_text":"test","expected_answer":1}] 

As you can see there are exactly two objects. Now when I apply this filter {{ $questions->where('question_num','=', 0) }}, I get the following results which is correct:

[{"question_num":0,"survey_id":2,"question_text":"test","expected_answer":1}] 

But when I apply the following filter {{ $questions->where('question_num','=', 1) }}, I get an empty result, why is that, when clearly the collection has a question_num with value of 1?

[]

I've been scratching my head all day with this!



via Chebli Mohamed

how to use Redis Server Detection in laravel?

1-Xampp

2-laravel 5.1

3-run localhost:8000

class in function

$redis = LRedis::connection();
$redis->publish('message', "fgfgff");

error ConnectionException in AbstractConnection.php line 155: No connection could be made because the target machine actively refused it. [tcp://127.0.0.1:6379]



via Chebli Mohamed

Laravel 5.1 Creating and Updating Dynamically Created Form Field Array

I have a survey which can have many questions - a belongs to many relationship. The fields for the questions are dynamically created as follows. The question_num is the array index value.

How can you create and update the questions table in this scenario. I tried the following but it doesnt work?

foreach ($request->input('questions') as $key => $val) {
   $survey->questions()->updateOrCreate(['survey_id' => $request->input('survey_id'), 'question_num' => $key], $request->input('questions'));
}

Form:

{{ Form::hidden('survey_id', '1') }}

{{ Form::text('questions[0][question_text]', null, array('class'=>'form-control')) }}
{{ Form::text('questions[0][question_answer]', null, array('class'=>'form-control')) }}


{{ Form::text('questions[1][question_text]', null, array('class'=>'form-control')) }}
{{ Form::text('questions[1][question_answer]', null, array('class'=>'form-control')) }}

Questions table

CREATE TABLE `questions` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`survey_id` INT(10) UNSIGNED NOT NULL,
`question_num` INT(10) UNSIGNED NOT NULL,
`question_text` VARCHAR(150) NOT NULL COLLATE 'utf8_unicode_ci',
`question_answer` TINYINT(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `question_num_survey_id_unique` (`question_num`, `survey_id`),
INDEX `survey_id_foreign` (`survey_id`)
CONSTRAINT `survey_id_foreign` FOREIGN KEY (`survey_id`) REFERENCES `surveys` (`id`)
)



via Chebli Mohamed

samedi 27 février 2016

Why are Laravel eloquent model attributes based on default definitions empty after save?

With a very simple model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{

}

And it's schema for completeness:

<?php

use App\Models\Lease;
use App\Models\Choice;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTableExamples extends Migration {

    public function up()
    {
        Schema::create('example', function(Blueprint $table)
        {
            $table->increments('id');
            $table->enum('status', [1, 2, 3])->default(1);
            $table->text('abc')->nullable();
            $table->text('foo')->nullable();
        });
    }

    public function down()
    {
        Schema::dropIfExists('example');
    }
}

Why does the following save statement, result in empty attributes for the fields that are defined with defaults?

$example1 = new App\Models\Example();
$example1->foo = "BAR";
$example1->save();

var_dump($example1->attributes);

This outputs the following, note that the output has skipped the status field. Also note that field abc is missing.

array (size=4)
    'foo' => string 'BAR' (length=3)
    'id' => int 19

If I reload the model, with $example1->fresh(), I get the expected output:

array (size=4)
    'foo' => string 'BAR' (length=3)
    'abc' => null,
    'status' => int 1,
    'id' => int 19

Is there a way to avoid the fresh method? Under the hood, fresh is another trip to the db.



via Chebli Mohamed

Laravel 5.1 using collection methods inside blade

In my blade template I have the following $questionList collection

Collection {#322 
  #items: array:2 [
    0 => Question {#321 
      ....
      #attributes: array:7 [
        "job_id" => 3
        "question_id" => 0
        "question_text" => "test"
        "expected_answer" => 1
        "created_at" => "0000-00-00 00:00:00"
        "updated_at" => "0000-00-00 00:00:00"
      ]
    }
    1 => Question {#318 ▶}
  ]
}

In the template I have a for loop. How can I check if my collection has an item with a question_id equal to the index of the for loop and if it does how do I display the question_text for that question_id. I've tried chaining the following collection methods but they don't work?

@for ($i = 0; $i < 5; $i++)

    {!! Form::text("question_list[{$i}][question_text]", $questionList->where('question_id', $i)->get('question_text', null), ['class' => '']) !!}

@endfor



via Chebli Mohamed

Laravel 5.1 form model binding a one to many relationship

Is is possible to form model bind a one to many relationship when using arrays? In the example below I have one to many relation between the jobs and questions table. A job can have many or no questions associated with it. In my blade template I want to know if its possible to bind this relations ship as I've been able to do so with the job industries relationship using a simple method on the job class getIndustryListAttribute(). I tried using the getQuestionListAttribute() method but it doesn't work?

Tables

 jobs
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`job_title` VARCHAR(100) NOT NULL,

questions
`job_id` INT(10) UNSIGNED NOT NULL,
`question_id` INT(10) UNSIGNED NOT NULL,
`question_text` VARCHAR(150) NOT NULL,
`expected_answer` TINYINT(1) NOT NULL,
    PRIMARY KEY (`job_id`, `question_id`),

Class

   class Job extends Model {

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

        public function industries()
        {
          return $this->belongsToMany('App\Industry', 'job_industry');
        }

        public function getIndustryListAttribute()
        {
          return $this->industries->lists('id')->all();
        }

        public function getQuestionListAttribute()
        {
          return $this->questions->lists('question_text', 'question_id')->all();
        }

   }

   class Question extends Model {

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

Form

   @for ($i = 0; $i < 5; $i++)
       <div class="form-group >
          {!! Form::label("question_list.{$i}.question_text", 'Question', ['class' => '']) !!}
          {!! Form::text("question_list[{$i}][question_text]", null, ['maxlength' => '150', 'class' => 'form-control']) !!}
       </div>
       <div class="form-group">
          {!! Form::label("question_list.{$i}.expected_answer", 'Expected answer', ['class' => '']) !!}
          {!! Form::select("question_list[{$i}][expected_answer]", ['' => 'Please Select', 'true' => 'Yes', 'false' => 'No'], null, ['class' => 'form-control']) !!}
      </div>
    @endfor

     <div class="form-group">
         {!! Form::label('industry_list', 'Industry', ['class' => '']) !!}
         {!! Form::select('industry_list[]', $industries, null, ['id' => 'industry_list', 'class' => 'form-control', 'multiple']) !!}
     </div>

Note: the question_id is simply the array index value.



via Chebli Mohamed

Grouping related models using Laravel 5.1 blade and HTML

Could a someone help me out of this, I am finding it hard grouping related models together using html table. The system I'm trying to come up with is a bidding system. Multiple users can bid on a product, and as well, multiple products. When the owner views his products, they should be grouped based on the product name. Let say a user posts 2 products, and 4 other users have bid on these products, the users' bid should be grouped under the product name, but I'm what I'm getting is that it groups each under different tables. This is my blade view:

<DIV style="color:#0000FF">
                    @foreach($myBuyers as $myQuotedProducts)
                            @foreach($product as $products)
                                @if($products->id === $myQuotedProducts->product_id)
                                    @if(count($products->productname) > 1)
                                <div style="color:#0000FF">
                                    <p>{!! $products->productname !!}</p>
                                    <TABLE>
                                    <TH>SELECT</TH><TH>PRODUCT</TH><TH>COMMENT</TH><TH>PRICE</TH>
                                        <TR><TD>{!! Form::radio('selectedButton' .$myQuotedProducts->product_id, $myQuotedProducts->product_id) !!}</TD><TD>{!! $products->productname !!}</TD><TD>{!! $myQuotedProducts->comments !!}</TD><TD>{!! $myQuotedProducts->price !!}</TD></TR>
                                    </TABLE>
                                </div>
                                @else
                                    <div style="color:#0000FF">
                                    <p>{!! $products->productname !!}</p>
                                    <TABLE>
                                    <TH>SELECT</TH><TH>PRODUCT</TH><TH>COMMENT</TH><TH>PRICE</TH>
                                        <TR><TD>{!! Form::radio('selectedButton' .$myQuotedProducts->product_id, $myQuotedProducts->product_id) !!}</TD><TD>{!! $products->productname !!}</TD><TD>{!! $myQuotedProducts->comments !!}</TD><TD>{!! $myQuotedProducts->price !!}</TD></TR>
                                    </TABLE>
                                </div>
                                @endif
                                @endif
                            @endforeach
                        @endforeach

                </DIV>

This is my controller:

public function index()
    {
        $product = Product::all();
        $myBuyers = BiddingComments::where('user_id', '=', Auth::user()->id)->orderBy('price', 'DESC')->get();

        return view('buyers.index')
        ->with('product', $product)
        ->with('myBuyers', $myBuyers);
    }

Please kindly see the attached screenshots to be well acquainted on what I want to achieve and what I'm getting.

This is what I want to achieve: This is what I want to achieve

This is what I'm getting now which is wrong enter image description here



via Chebli Mohamed

error with migrate refresh

I am getting this error when trying to run: php artisan migrate:refresh:

Rolled back: 2016_02_16_114444_create_posts_table
Rolled back: 2016_01_20_234538_expectations
Rolled back: 2016_01_20_200616_expectation_profile
Rolled back: 2015_12_22_111958_create_profiles_table
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table


  [Illuminate\Database\QueryException]                                          
  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'follower  
  _id' (SQL: alter table `follower_followee` add `follower_id` int unsigned no  
  t null, add `followee_id` int unsigned not null)                              

  [PDOException]                                                                
  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'follower  
  _id'

This is the migration the error refers to:

<?php

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

class FollowerFollowee extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('follower_followee', function (Blueprint $table) 
        {
            $table->integer('follower_id')->unsigned(); // follower id number,must be positive.
            $table->integer('followee_id')->unsigned(); // followee id number,must be positive.
            $table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
            //The 'follower_id' column references to the 'id' column in a 'users' table.
            //When a user is deleted in the parent column ('follower_id'), then also the user in 'id' ('users') is deleted. 
            $table->foreign('followee_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()

{
    Schema::dropIfExists('follower_followee');
    }
}

when trying to run : composer dump-autoload - it returns only this:

Generating autoload files

I honestly can't identify where's that duplication appears. Any help would be lovely.

Thank you.



via Chebli Mohamed

Laravel Push Notifications doesn't work on server, receiving null response

I am using Laravel 5.1 with davibennun/laravel-push-notification library in order to send push notifications.

With this library I am doing the following:

 // Makes a DeviceCollection with my fetched devices
 // $androidTokens is an array of Device objects with my tokens
 $deviceCollection = $this->pushNotificationManager
          ->DeviceCollection($androidTokens);

 // Sends the push notification message
 $collection = $this->pushNotificationManager->app('appNameAndroid')
        ->to($deviceCollection)
        ->send($message);

 // Logs the response status
 foreach ($collection->pushManager as $push) {
        $response = $push->getAdapter()->getResponse();
        Log::info('Push notification response:', [
            'response' => $response,
        ]);
    }

I already configured my push notifications credentials on the generated push-notifications.php file with the following:

 'appNameAndroid' => array(
    'environment' => env('GCM_ENVIRONMENT'),
    'apiKey'      => env('GOOGLE_API_SERVER_KEY'),
    'service'     =>'gcm'
)

And configured everything on my google developer console to enable Google Cloud Messaging with specified keys.

I already tried on my local Homestead machine with my credentials, and it is able to send the push notification successfully. However, when i tried the same in my production server, push notification is not sent and my application logs the following:

 production.INFO: Push notification response: {"response":null}

I don't really have a clue as to why it is not working, as on my local machine push sends successfully and logs the following response:

 local.INFO: Push notification response: {"response":"[object] (ZendService\\Google\\Gcm\\Response: {})"}

Note: they have the exact same configuration (server key, GCM environment) and I am copying my device tokens from my production server to my local homestead machine to test notifications.

So it seems there's some problem communicating with google services from the server.

I have already checked for many issues like:

  • Checking if my api key configuration on the google console is blocking my production's server ip address (already removed ip filtering and it doesn't work)
  • Checking if my generated server key is invalid, which i used the method described here: http://ift.tt/1T0ULL8 under Checking the validity of an API key which i got the expected success response.

I have looked for hours to a solution to this error, but i couldn't find anything related on the subject so i already ran out of ideas.

Just in case it helps, i'm using homestead version 0.4.0 on a VirtualBox provider, and my production server is hosted on Digital Ocean and it's being managed by Laravel Forge (dunno if it's some sort of port configuration issue or if there is some extra process involved with this technologies).

Any ideas as to why this is not working would be really appreciated.



via Chebli Mohamed

larave 5.1 routes groups takes only the first controller?

Route::group(['prefix' => 'api'], function () {

    Route::controller(null, 'BoxController');
    Route::controller(null, 'CostController');

});

This is a routed group in Laravel 5.1 the urls for the first controller is working but not for the second one 'CostController'.

If I switch the lines the first one works only. I want both controllers url to be prefixed with ...api/box/ and ...api/cost/

Examples on the internet has only one controller in the group, maybe there is another syntax?



via Chebli Mohamed

Laravel string Localization in config files

I'm having problem using trans() function in config file, I feel it not supposed to be used that way. However I've no clue on what would be the most efficient way to translate string text in config files (files in /config folder).

Original code

<?php

return [
    'daily' => 'Daily'
];

When I try to implement trans() application crashes and laravel return white page without any error messages

<?php

return [
    'daily' => trans('app.daily_text')
];



via Chebli Mohamed

CORS issue when registering

angular.module('wwwApp')
    .controller('RegisterCtrl', function ($scope,$auth) {
        $scope.loginForm={};
        $scope.loginForm.email='';
        $scope.loginForm.password='';

        $scope.register1=function()  {
            console.log('hi');
            $auth.signup($scope.loginForm).then(function (response) {
                console.log('hi');
                console.log(response);
                //$state.go('dashboard');
            }).catch(function (response) {
                console.log(response);
                window.alert('Error: Register failed');
            });
        };

    });

Code of auth controller

public function register(Request $request)
    {
        $newUser = $request->create([
      'name' => $request->get('name'),
      'email' => $request->get('email'),
      'password' => bcrypt($request->get('password'))
    ]);

this is the controller code for registering the user, but it displaying No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 500.



via Chebli Mohamed

Session::setId not work in Laravel

I have code for testing :

public function setUp()
{
    parent::setUp();
    Session::setId('test');
}

public function testInitialize()
{
    echo Session::getId() . "\n";
}

and output in testInitialize function is:

bf7535b20443fd1302e2aa27a917a885b522e320

I assume that once laravel sets the session id it can't be set up again, but does somebody have snippet how to destroy session and set up again so the output in testInitialize() will be :

test



via Chebli Mohamed

vendredi 26 février 2016

Unique Value from multidimensional array

I'm fetching data from database in multidimensional array like this

$par = [];
$var = DB::table('welcome_call_done')->where('state','LIKE', '%'. $states .'%')->where('city','LIKE', '%'. $citys .'%')->get();
foreach($var as $val)
{
    $prod = DB::table('welcome_call_product')->where(['assoc_id' => $val->assoc_id])->get();
    array_push($par, $prod);                           
}
$unique = array_map("unserialize", array_unique(array_map("serialize", $par)));

I want to display singles values but after execution is display multiple data. Please tell some solution to sort this problem.



via Chebli Mohamed

Need advice on laravel modeling (pivot of pivot)

I have a company auditing system, which is a bit difficult to explain but i will try to keep it simple. Here are the main parts

1) Comapny

2) Audits (certifications)

3) Clauses (These are questions specific to a certification and they all need to be answered in order for the audit to complete. The user can then add comments, status, mark it as complete etc )

There are lots of audits that a company can be tested for. So a company can have multiple audits. Each audit have some clauses, that needs to be executed in order to complete the audit. A user can also add some data to these clauses, for eg progress of the clause, status, comments etc.

Right now i have these database tables

1) Companies

2) Audits

3) Clauses

4) Companies - Audits (Pivot table)

5) Clauses - Audit (Pivot table)

6) Companies - Audits - Clauses (pivot of pivot table)

Now the first 5 are preety standard, but i am not sure how to impliment the last one. Right now in companies-audits pivot table i have an auto increment field called companies_audits_id, And i then use this id inside Companies_Audits_Clauses table. In Companies_Audits_Clauses table i also have the fields like status, progress, comments etc.

I am not sure if this is a good idea. So i need your thoughts on it. Every help is appreciated.



via Chebli Mohamed

a middleware to be run during every HTTP request to application except one in laravel 5.1

I am new in laravel , I want to create my app ( I dont want to use laravel default login system)

I want to use a middleware to be run during every HTTP request in my application except one

in laravel 5.1 documention syas I can use Global Middleware but I want to not use middleware for just login page. what should I do ? this is my middleware :

<?php

namespace App\Http\Middleware;

use Closure;

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

        if( !  session()->has('Login' )  )
        {
            return redirect('login');
        }

        return $next($request);
    }
}



via Chebli Mohamed

Why composer "psr-4" loading not woking in outer folder

I have this in composer:

"MyCompany\\": ["app/MyCompany/", "app/LaravelPackage/src/MyCompany/"]

and everything works fine. This also works fine:

"MyCompany\\": ["app/MyCompany/", "app/Console/../LaravelPackage/src/MyCompany/"]

Even with non existing folder and path back, works:

THIS IS PROBABY BUG. TRY IF YOU DON'T BELIEVE.

"MyCompany\\": ["app/MyCompany/", "app/Console-babababa/../LaravelPackage/src/MyCompany/"]

But if I move package out of root folder where I run composer install it not works:

"MyCompany\\": ["app/MyCompany/", "../app/LaravelPackage/src/MyCompany/"]

This should work or ?



via Chebli Mohamed

Where to look in laravel documentation api for all available functions for each facade?

I know how facades work and I can find full facede list in Laravel: http://ift.tt/20ZoUfM

But how I can see all available functions for each facade ?

If I use facase Session I can: 1.Find methods in laravel documentation: http://ift.tt/1S5PR10

2.Or search methods in each class in "Illuminate/Session" namespace http://ift.tt/20ZoVQO

But I think it should be more elegant to find ?



via Chebli Mohamed

Laravel 5.1 ajax is removing a session value

I have an ajax call, that sometimes work and sometimes doesn't, completly random as it seems cause this ajax is called in more than one place in the same view, woks for some, fail for others and sometimes works for all.

function callAjax(id_projeto){
    $.ajax({
          url: "{{ URL::to('/thatPlaceOverThere') }}",
          type: "post",
          data: {'_token'   : '{{ csrf_token() }}',
                 'id_projeto': id_projeto
                 },
          error: function(erro){
              // Error Suff //
          },
          success: function(data){
              // Ok Suff //
          }// success
    });
}

The part of works sometimes is question 1. Why would that happen in localhost?

Now, the second and more puzzling. This ajax call is removing my session values. The _token and flash are there, but I guess that laravel is just puttin it back, any value that I putted is gone.

If the ajax call is removed the session values remain there as it should.

The session values are set in a middleware like this

$request->session()->put('id_usuario', $id_usuario); 

My session file:

return [

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "array"
|
*/

'driver' => env('SESSION_DRIVER', 'file'),

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => 12000,

'expire_on_close' => false,

/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/

'encrypt' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/

'files' => storage_path('framework/sessions'),

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

'connection' => null,

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => [2, 100],

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/

'cookie' => 'laravel_session1',

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/

'domain' => null,

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => false,

];

This happens with laravel 5.1, php 7.0.3.



via Chebli Mohamed

How to write tests for Custom Laravel packages which use migrations files?

I created custom Laravel package that have own migrations. There is no documentation how to test custom packages in laravel documentation.

Do you have any suggestion how to do this, or do you have some package example which have implemented tests good ?

I need to create tables from migration file and fill database after that ...



via Chebli Mohamed

Find matching keywords from comma separated

I am trying to find keywords from comma separating string with FIND_IN_SET and here is mysql query in Laravel framwork.

$Keyword = $_POST['keyword'];
$Result = DB::table('faqtopic')
    ->whereRaw('FIND_IN_SET(?,Keywords)', 'LIKE', ''[$Keyword])
    ->get();

faqtopic table:

╔════╦══════════════╗
║ id ║   keywords   ║
╠════╬══════════════╣
║  1 ║ php, android ║
║  2 ║ microsoft,net║
║  3 ║ android, ios ║
╚════╩══════════════╝

I am getting two results, If I pass android keyword but not getting any result I pass only andro. I want to get android result If user pass andro keyword for search query.

Any Idea how to get this results.

Thanks.



via Chebli Mohamed

HTML parsing with relevant value in PHP

I have used Laravel 5.1 for my current project. In this project, I have a text area input field where user can insert HTML with predefined placeholder. Please take a look:

<div id="recommend">
  <div class="title"><p>Title</p></div>
    #{item}
  <div class="layout">
    <div class="item">
      <a href="#{url}" class="rcm11"><img border="0" alt="#{name}" src="#{image}"></a>
    </div>
    <div class="price">#{comma(price_tax)}</div>
  </div>
  #{/item}
</div>

I saved it to my database. when a user request a HTML, I have given this html by replacing placeholder with proper value. On the above HTML #{item}, #{url} etc. are place holders. I need to parse this place holders and replace with proper value. In Laravel or PHP, how can I do it? If anyone have a answer please let me know.



via Chebli Mohamed

How to search by columns union in datatable?

i need to search by user firstname and lastname where are merge to one. Im working with laravel 5.1 and http://ift.tt/1QjEdLi.

Here is me code of backend query:

                $orders = Order::select([
                                    'orders.created_at',
                                    'users.firstname AS user_firstname',
                                    'users.lastname AS user_lastname'
                            ])
                            ->join('users', 'users.id', '=', 'orders.user_id')
                            ->where('orders.client_id', \Auth::user()->client_id)
                            ->where('orders.status', 'finished');

And return:

        return Datatables::of($orders)
                    ->addColumn('user', function ($user) {
                        return $user->user_firstname.' '.$user->auser_lastname;
                    })
                    ->addColumn('action', function ($order) {
                        return '<div class="btn-group" style="min-width: 76px;">
                                    <a href="'.url('history/order/edit/'.$order->id).'" class="btn btn-default"><i class="fa fa-edit"></i></a>
                                    <a href="'.url('history/order/delete/'.$order->id).'" class="btn btn-default" onClick="return confirm(\'Are you sure?\');"><i class="fa fa-times"></i></a>
                                </div>';
                    })
                    ->removeColumn('user_firstname')
                    ->removeColumn('user_lastname')
                    ->make(true);

I merge user column to one with user_firstname and user_lastname.

When im searchng in datatable i need to search by this column - USER. Query to to be like this:

SELECT
    `orders`.`created_at`,
    `users`.`firstname` AS `agent_firstname`,
    `users`.`lastname` AS `agent_lastname`,
FROM
    `orders`
INNER JOIN `users` ON `users`.`id` = `orders`.`user_id`
WHERE
    `orders`.`client_id` = '3'
AND `orders`.`status` = 'finished'
AND (
    LOWER(`orders`.`created_at`) LIKE '%search_word%'
    OR LOWER(`users`.`firstname`) LIKE '%search_word%'
    OR LOWER(`users`.`lastname`) LIKE '%search_word%'
)
ORDER BY
    `orders`.`created_at` DESC
LIMIT 10 OFFSET 0

Here is my datatable JS:

// Data tables
var oTable = $('#orders-data').dataTable({
    "processing": true,
    "serverSide": true,
    "ajax": '/history/orders',
    "columns": [
        { data: 'created_at', name: 'orders.created_at' },
        { data: 'user', name: 'user' },
        { data: 'action', name: 'action', orderable: false, searchable: false }
    ],
});

If I change line { data: 'user', name: 'user' } in JS to { data: 'user', name: 'users.firstaname' } than searching only in users.firstname column, But i need search in users.lastname too.

How to do that?



via Chebli Mohamed

How to handle MethodNotAllowedHttpException

I'm looking to handle a MethodNotAllowedException. I've viewed other answers available on here that to create what i think should handle this in the exceptions/handler.php class. This is what i came up with.

  public function render($request, Exception $e)
  {

    if ($e instanceof MethodNotAllowedHttpException) {

        \Auth::logout();
        \Session::flush();
        return redirect()->('/')->withErrors(['error' => 'Something went wrong']);
    }
    return parent::render($request, $e);
  }

However where i used to get an error before, all i recieve now is a blank page on the page where i usually recieve an error and a user is not logged out nor are they redirected. Am i placing this handler in the right place and if so, is the function shown below correct?

Thanks



via Chebli Mohamed

Remove public from URL Laravel 5.1

I'm using Laravel 5.1 and would remove public from my URL. Any ideas how this is done without renaming files?



via Chebli Mohamed

jeudi 25 février 2016

Laravel - controller calling another controller - good practice?

I was able to implement a PaypalController, with a reusable postPayment() method, which accepts items and their prices, and creates a Paypal payment, and redirects to a Paypal payment page.

class PaypalController extends Controller {

    private static $_api_context;

    private static function initialize() {
        //initialize api context
    }

    public static function postPayment($items, $currency, $description) {
        self::initialize();

        //create item list, transaction, payment objects, etc

        $payment->create(PaypalController::$_api_context);
        ...
        return redirect()->away($redirect_url); // redirect to paypal
    }
}

PaypalController is called statically by other controllers. For example, the AuthController might call it to request payment from the user right after the user registers to my site:

class AuthController extends Controller {
    public function postRegister(Request $request) {
        return PaypalController::postPayment($items, 'JPY', 'description');
    }
}

Basically, PaypalController returns a Redirect to AuthController, which also returns it, to perform the redirect to the Paypal payment page.

I was wondering if this is a good design - a controller calling a different controller, is it?

If not, what would be a better way to do this? Maybe move my code from PaypalController into custom Service Provider, or custom Helper, or something else? I am very new to Laravel, and I would appreciate some guidance.



via Chebli Mohamed

Laravel 5.1 PhpUnit action more than once does not work

Here is my Code.

   <?php

   use Illuminate\Foundation\Testing\WithoutMiddleware;
   use Illuminate\Foundation\Testing\DatabaseMigrations;
   use Illuminate\Foundation\Testing\DatabaseTransactions;

   use App\Models\master\Company;
   use App\User;

   class JobReferenceControllerTest extends TestCase
   {


    public function setUp(){
      parent::setUp();
      // $this->mock = \Mockery::mock('Moloquent','App\Models\master\Company');
      $company                =     new Company;
      $company->cmp_name          =  'TestCompany123';
      $company->cmp_website          =  'www.testcompany.com';
      $company->cmp_desc          = 'This is Description';
      $company->cmp_employe          =  '0-100';
      $company->save();
    }

    public function testAddJobWithoutTitleFunctionality(){
        $company    =     Company::where('cmp_name','=','TestCompany123')->orderBy('created_at','desc')->first();
        $status   =   true;
        if($company == null){
          $status  =   false;
        }

        $this->assertEquals($status,true);

        $parameters   =   [
            'job_description' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
            'job_type' => 'WALKIN',
            'job_valid_to' => '2016-07-07',
            'for_company_id' => $company->_id
        ];
        $cookies  =   [];
        $files  =   [];

        $user = User::where('email','=','lokesh@skoolkhojo.com')->first();
        if($user != null){
          $this->be($user);
        }

        $response = $this->action('POST', '\App\Http\Controllers\Api\Features\JobReferenceController@store', $parameters);


        // var_dump($response->getContent());
        $this->assertEquals(400, $response->getStatusCode());

    }

    public function testAddJobFunctionality(){
         $this->withoutMiddleware();

        $company    =     Company::where('cmp_name','=','TestCompany123')->orderBy('created_at','desc')->first();
        $status   =   true;
        if($company == null){
          $status  =   false;
        }

        $this->assertEquals($status,true);
        $parameters   =   [
            'job_title' => 'Dummy Job',
            'job_description' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
            'job_type' => 'WALKIN',
            'job_valid_to' => '2016-07-07',
            'for_company_id' => $company->_id
        ];


        $user = User::where('email','=','lokesh@skoolkhojo.com')->first();
        if($user != null){
          $this->be($user);
        }

        $action   =   '\App\Http\Controllers\Api\Features\JobReferenceController@store';
        $response = $this->action('POST',$action, $parameters);
        $this->assertEquals(200, $response->getStatusCode());

    }


    public function tearDown(){
      $company    =     Company::where('cmp_name','=','TestCompany123')->orderBy('created_at','desc')->first();
      if($company != null){
        $company->delete();
      }
      parent::tearDown();
    }

}

It execute the statement for first time 
$response = $this->action('POST',$action, $parameters);

Latter says 

1) JobReferenceControllerTest::testAddJobFunctionality InvalidArgumentException: Action App\Http\Controllers\Api\Features\JobReferenceController@store not defined.

/Users/lokesh/Documents/projects/skoolkhojo_v2/skoolkhojo_services/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:590 /Users/lokesh/Documents/projects/skoolkhojo_v2/skoolkhojo_services/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:435 /Users/lokesh/Documents/projects/skoolkhojo_v2/skoolkhojo_services/tests/Http/Controllers/Api/Features/JobReferenceControllerTest.php:81

Could anyone please help me out to figure out why action method is executes perfectly for once than say action not found.

Please help me out.

Thanks in Advance.



via Chebli Mohamed

Fresh install Laravel 5.1 and get server 500

i install Laravel 5.1 via composer set premissions for /storage and /bootstrap/cache and create vhost in sites-enable/project.conf:

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    ServerName www.sklad.dev

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/sklad/public

    <Directory /var/www/html/sklad/public>
        AllowOverride All
        Order allow,deny
        Allow from all
        # New directive needed in Apache 2.4.3: 
        Require all granted
    </Directory>


    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>


# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

in /public/.htaccess i have :

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

i enabled revrite mod on apache2 and restart apache.But i still have Server not found 500. Do you have some ides what can be wrong?Thanks



via Chebli Mohamed

Customized Error Message : Laravel 5.2.15

I have the following code written in Request class under Rules method.

public function rules()
{
    return [
        'Currency' => 'required|max:5|min:2|composite_unique:tblcurrency,CurrencyCode',
        'CurrencyCode' => 'required|max:5|min:1',
    ];
}

This works fine. Only issue is, when the validation fails, I get the following message..

validation.composite_unique

What i tried so far?

After writing the below code, still I am getting the same error string.

public function messages () {
    return [
        'validation.composite_unique'  => 'Duplicate Country and code combination found.',
    ];
}

Question: Can we customize the error message to make it look more user friendly?



via Chebli Mohamed

Importing already installed laravel project on to godaddy server

I am trying to import the existing laravel project folder through Installatron on godaddy server and iam getting the following error it says Error

Unable to detect the source installed application's database information.

enter image description here



via Chebli Mohamed

404 Error Handling in Laravel 5.2.15

I am asking this question because I did not get reply after adding my comment in this question

laravel routing and 404 error

In the above answer, we can see below code to be used in filters.php

App::missing(function($exception)
{
    return Response::view('errors.missing', array(), 404);
});

But, I think we don't have filters.php in latest version. Can somebody suggest better way to handle 404 error?



via Chebli Mohamed

Laravel Show not authorised if user opens admin route

Here are two routes

Route::group(['prefix' => 'admin', 'middleware' => ['role:superAdmin']], function() {
Route::get('/dashboard', 'Admin\AdminController@getDashboard');
});

Route::group(['prefix' => 'user', 'middleware' => ['role:user']], function() {
Route::get('/profile', 'User\UserController@getProfile');
});

If user try to access /admin/dashboard Not authorized view should be show.



via Chebli Mohamed

PHP, CURL ,curl_exec

I'm trying to set an API for online payment process.According to their documentation i should have like this in url http://localhost:8000/shopping/success/45?oid=XYZ-1234&amt=330&refId=0006QHT

i mean, oid="something"&amt="something"&refId="something"

i got like this in browser. But i got message like this on doing die()at end of code :

Failed to connect to dev.esewa.com.np port 80: Connection refused

I want to know what the message suggesting me .is there anything wrong,How can i solve this error

here is my code

       $site_url = 'http://ift.tt/1p8tdty';
        $esewa_url = 'http://ift.tt/21tWn4g';
        $esewa_verfication_url = 'http://ift.tt/1p8tg8M';
        $merchant_id = "xxxxxx";

        //create array of data to be posted
       // dd($_REQUEST['oid']);
        $post_data['amt'] = $_REQUEST['amt'];
        $post_data['scd'] = $merchant_id;
        $post_data['pid'] = $_REQUEST['oid'];
        $post_data['rid'] = $_REQUEST['refId'];

        //traverse array and prepare data for posting (key1=value1)
        foreach ($post_data as $key => $value) {
        $post_items[] = $key . '=' . $value;
        }

        //create the final string to be posted using implode()
        $post_string = implode('&', $post_items);

       // dd($post_string);

        //create cURL connection
        $curl_connection =
            curl_init($esewa_verfication_url);

       //dd($curl_connection);
        //set options
        curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
        curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

        //set data to be posted
        curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

        //perform our request
        $result = curl_exec($curl_connection);


        if($result === FALSE) {
          die(curl_error($curl_connection));
//here i go message like this:Failed to connect to dev.esewa.com.np port 80: Connection refused
        }

        //close the connection
        curl_close($curl_connection);


        $verification_response  = strtoupper( trim( strip_tags( $result ) ) ) ;

        if('SUCCESS' == $verification_response){
        echo '<h2><strong>SUCCESS:</strong> Transaction is successful !!!</h2>';

        return Redirect::to('/');
        }
        else{
        echo '<h2><strong>ERROR:</strong> Transaction could not be verified</h2>';

                return Redirect::to('/');


        }



via Chebli Mohamed

What is the best practice to fix bad data in one of the table in the database?

Problem

I have a bad data in one of my table in my database, and it requires me to truncate a table. I can do it with no problem, but what about my team, QAs, and other developers - that already have the code, and bad data. Do they need to truncate their table manually too ? How do people usually deal with something like this ?


Solution

If I truncate that table via migration script, is it a good idea ? Is there anything bad about it ? Then, my whole team will just need to run : php artisan migrate.


I'm open to any suggestions on this.



via Chebli Mohamed

Allow a user to bid on a product only once using laravel 5.1

Simple logic required to get this finished, I pray the help of an expert. I'm presently trying a way out to implement a restriction on a bidding website I'm developing, the simplicity is this: a user cannot bid on a product more than once. If the user clicks on the product again, he should be prompted with a response page noting the user of having previously bid on the product,

This is the blade form:

  <p><h3>{!! ucfirst($product->productname) !!}</h3></p>

            @if(Auth::user()->id === $product->user_id)
                <p>Sorry, you posted this product, you cannot quote on it.</p>

            @else
            <p>{!! Form::label('Higest Price') !!}</p>
            <p>{!! Form::number('price', Input::old('price')) !!}</p>
            <p>{!! Form::textarea('comments', Input::old('comments')) !!}</p>
            <p>{!! Form::hidden('product_id', $product->id) !!}</p>
            <p>{!! Form::hidden('company_id', $product->company_id) !!}</p>
            <p>{!! Form::hidden('user_id', $product->user_id) !!}</p>

            <p>{!! Form::submit('ADD QUOTE') !!}</p>
        @endif
        {!! Form::close() !!}

This is the controller:

public function store(BiddingCommentRequest $biddingCommentRequest)
    {
        $biddingComments = new BiddingComments;
        $product_id = $biddingCommentRequest->product_id;
        $AuthUserBidder = Auth::user()->id;
        $bidderCommented = BiddingComments::all();

        if($biddingCommentRequest->isMethod('post')){
            foreach ($bidderCommented as $key => $commentedBidder) {
               if(!count($commentedBidder->id) > 0)
               {
                    $biddingComments->bidder_id  = $AuthUserBidder;
                    $biddingComments->product_id = $product_id;
                    $biddingComments->company_id = $biddingCommentRequest->company_id;
                    $biddingComments->user_id    = $biddingCommentRequest->user_id;
                    $biddingComments->comments   = $biddingCommentRequest->comments;
                    $biddingComments->price      = $biddingCommentRequest->price;
                    $biddingComments->save();
                     return redirect()->route('biddingCommentView', $product_id)->with('message', 'Your question has been posted.');
               }elseif(($AuthUserBidder == $commentedBidder->bidder_id) && ($product_id == $commentedBidder->product_id))
               {
                    return redirect()->route('productindex')->with('message', 'Your question has been posted.');
               }else
               {
                    $biddingComments->bidder_id  = $AuthUserBidder;
                    $biddingComments->product_id = $product_id;
                    $biddingComments->company_id = $biddingCommentRequest->company_id;
                    $biddingComments->user_id    = $biddingCommentRequest->user_id;
                    $biddingComments->comments   = $biddingCommentRequest->comments;
                    $biddingComments->price      = $biddingCommentRequest->price;
                    $biddingComments->save();
                     return redirect()->route('biddingCommentView', $product_id)->with('message', 'Your question has been posted.');
                }
            }
        }
    }

It's not adding the restriction. It allows user to keep quoting on a product over and over again. Kindly help, please.



via Chebli Mohamed

Laravel 5: The difference between Auth::guard($this->getGuard())->login($user); and auth()->login($user);

What is the difference between:

Auth::guard($this->getGuard())->login($user);

and

auth()->login($user);

? For example, in PasswordController.php we can have:

protected function resetPassword($user, $password)
{
    $user->password = $password;

    $user->save();

    Auth::guard($this->getGuard())->login($user);
}

or

protected function resetPassword($user, $password)
{
    $user->password = $password;

    $user->save();

    auth()->login($user);
}

(in this case, we create a mutator in Users.php to bcrypt password AND NOT in resetPassword($user, $password) as it is by default)



via Chebli Mohamed

LARAVEL how to change $fillable in Model from trait?

I have in model:

use seoTrait;

protected $fillable = [
    'name', 'title', 'description'
];

I created trait "seoTrait" which need "seoMeta" in $fillable.

Now I add :

protected $fillable = [
    'name', 'title', 'description', 'seoMeta'
];

But is it possible in trait "seoTrait" add something to $fillable ?



via Chebli Mohamed

mercredi 24 février 2016

Use Laravel-filemanager without editor

I am planning to use the Laravel-filemanager (http://ift.tt/1oChYJa) in my project. In the documentation it is described to integrate with the CKEditor. But I want to use this file manager separately for a input field.



via Chebli Mohamed

interective video conferencing for E-classes

We are developing an education portal(laravel 5.1), for E-classes, is there any tool by which we can start interactive video conferencing on our website?like _so_



via Chebli Mohamed

Convert 3 variables to a date in php/laravel 5.1

Im trying to convert 3 variables $day $month $year. Into a date here is my code

$user->age = 23;


$day   = array_rand($days);
$month = array_rand($months);
$year  = date('Y', strtotime('-'.$user->age.' years'));
$date_combine = $day.$month.$year;
$convert = strtotime($date_combine);
$dob = date('d/M/Y', $convert);
dd($dob);

when I output the $dob I just get "01/Jan/1970" when I should be getting "01/Jan/1993". Not sure why this I happening or what Im missing.

Note: Im using laravel 5.1.



via Chebli Mohamed

How to change font-family of recaptcha v2?

I am use laravel 5.2. How do I change the font-family in other languages?



via Chebli Mohamed

laravel Server error 500 in cpanel hosting

im hosting laravel 5.1 in my cpanel but it always accured error.I tried every method (htaccess, chmod 644 and storage give o r+W) but it doesnt work in my cpanel but when i removed following line from index.php of public folder it give acces to inde file:

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

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

$response->send();

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

so it give access to mine folder . Can anybody help me? can it cause due to php version of cpanel?



via Chebli Mohamed

Laravel 5.1 - Retrieving single Models using string instead of the name of the model

Sorry for title. I don't know what to write. This is my problem: If i write this is all ok:

  $obj_license = License::where('licenses.company_id',$company->id)->first();

But this throw an error:

 $license='License';
 $obj_license = $license::where('licenses.company_id',$company->id)->first();

ERROR: Class 'Butchery_license' not found

This is just an example. I really need to have the second way working. There is a solution?



via Chebli Mohamed

Route NotFoundException error using AJAX GET

I'm trying to make an Ajax call to retrieve some data, so in the JavaScript I have:

var url = 'http://ift.tt/1LcWywM' $.ajax({ cache: false, url: url, method: 'GET' }).done(function(response) { var data = jQuery.parseJSON(response); console.log(data); });

Then in my route I have:

Route::get('my/uri/{ID1}/{ID2}', 'MyController@getSomeData'); If I type the url in my browser the route works as expected and returns the data, but when called via the Ajax function I get

``` NotFoundHttpException in RouteCollection.php line 161:

in RouteCollection.php line 161
at RouteCollection->match(object (Request)) in Router.php line 750
at Router->findRoute(object(Request)) in Router.php line 659
at Router->dispatchToRoute(object (Request)) in Router.php line 635
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http \{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure }(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object (Request), object(Closure ))) in Pipeline .php line 124
at Pipeline->Illuminate\Pipeline\{closure }(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession ->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure }(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure }(object(Request)) in AddQueuedCookiesToResponse .php line 37
at AddQueuedCookiesToResponse ->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array (object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure }(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle (object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure }(object(Request)) in CheckForMaintenanceMode .php line 44
at CheckForMaintenanceMode ->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure }(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter (object(Request)) in Kernel.php line 87
at Kernel->handle(object( Request)) in index.php line 54

```

Any ideas why this is happening?



via Chebli Mohamed

Calling function to save and redirect route: Laravel 5.2

I have following functions in Controller.

public function UpdateCountry(\App\Http\Requests\CountryRequest $request) {
    $this->SaveChanges($request);
}

private function SaveChanges($request) {
    if($request['CountryID'] == 0) {
        $Country = new \App\Models\CountryModel();
    }
    else {
        $Country = \App\Models\CountryModel
                  ::where('CountryID', $request['CountryID'])->first();
    }

    $Country->Country = $request['Country'];
    $Country->CountryCode = $request['CountryCode'];
    $Country->save();
    return redirect()->route('AllCountries');
}

public function AllCountries() {
    $Countries = \App\Models\CountryModel::all();
    return view('Country.List', array('Countries' => $Countries));
}

Issue is in below line: When I call function SaveChanges, I am not able to see List of countries page and when I write the code directly in UpdateCountry function, it redirect route successfully.

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

Anybody faced this issue before ?



via Chebli Mohamed

Laravel 5.1 and Socialite Questions

This isn't a post about a problem I'm having right now. I'm planning on using the Laravel Socialite plugin in my App, I already have a fully working login/register system using Laravel's built in Auth system but I'm wondering if there is a good way to allow users that already have their accounts in my app to link their social profiles to the already existing account?

The plan would be that they can login with their username and password or any of their social profiles. All the research I've done so far explains how to set up Socialite and utilise that data for registering/logging in new users, however I can't find anything to marry the two together.

I'm not looking for anyone to write this for me so please don't get confused by this post.

Thanks for any info, Andy



via Chebli Mohamed

email sends whole html page(instead of email body) in laravel 5.1

i'm making contact form. if someone fills in form, these data(text,subject) should be sent to my mail. everything's work, but when I fill in form and send mail, it sends whole html page (not text from form). here's how it looks like

printscreen

here's my controller where i send mail

 public function sendEmail(Request $request)
{

    $data["username"] = $request->username;
    $data["email"] = $request->email;
    $data["subject"] = $request->subject;
    $data["mail_text"] = $request->mail_text;

    Mail::send('contact', ["data" => $data], function ($mail) use ($data){

        $mail->to("leribobo@gmail.com")->from($data["email"])->subject($data["subject"]);

    });

    return redirect()->back();
}

as i guess it sends 'contact' page, which is first parameter in method

 Mail::send('contact' .... 



via Chebli Mohamed

Start new project with an exsiting laravel project

I have a local laravel 5.1 project A, I want to use it as a startup of a new project B. So, how can I use project A to start project B in the same localhost ? I did copy of A and rename its folder to B, create its new DB but it doesn't work :/ Please any idea ?



via Chebli Mohamed

Laravel 5.1 AuthController contains 5 abstract methods and must therefore be declared abstract or implement the remaining methods

I have deleted the vendor folder and recreated it using composer install yesterday and it was working fine (probably cached). Today I'm facing this error.

FatalErrorException in AuthController.php line 84: Class enterglobe\Http\Controllers\Auth\AuthController contains 5 abstract methods and must therefore be declared abstract or implement the remaining methods (enterglobe\Http\Controllers\Auth\AuthController::toArray, enterglobe\Http\Controllers\Auth\AuthController::getKey, enterglobe\Http\Controllers\Auth\AuthController::getTable, ...)

I tried deleting it and installing, also composer dump-autoload also cleared composer cached files to install another version of laravel but with no success.

The error disappears if i just implement the methods on this class for example

public function toArray(){}
public function getKey() 
etc...

Error goes away from AuthController but then it appears in other controllers.

Anyone faced this before.



via Chebli Mohamed

Multiple property Full-Text Search with MongoDB in Laravel

I am using MongoDb with laravel.

Below is my users collection sample json data

{
    "_id" : "52dfcd17daf02a2e6cb396c7",
    "email" : "nikhil@gmail.com",
    "name" : "Nikhil"
}
{
    "_id" : "52e0f9a2daf02ac908064f68",
    "email" : Michael@gmail.com,
    "name" : "Michael"
}

I have created index for 2 columns in collection, which is name & email.

db.users.ensureIndex({'email':'text', 'name': 'text'})

When i search for name I get the data but when i search exactly for an email id it gives unexpected results which should have been the emailId record.

Here is my code

$users = Users::whereRaw(['$text' => ['$search' => 'example@gmail.com']])->paginate(20);

return response()->view('users.view',
[
      'users' => $users,
      'title' => 'Search results for your query: ' . $query
]);



via Chebli Mohamed

Laravel 5.2: While moving to production, class "Collective\Html\HtmlServiceProvider" not found in vendor folder

I have been trying to move my laravel app to production. I following below steps

1. git clone
2. composer install
3. set env variables
4. (artisan key:generate)
5. artisan migrate --seed

But when i ran composer install, am getting the following error

Class 'Collective\Html\HtmlServiceProvider' not found in vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php on line 146

I know this error means, laravelcollective not added in composer.json and need to following steps as mentioned here.

But i already have done the same thing in dev mode and now the composer.json has require "laravelcollective" and aliases in config/app.php.

My question is, do i need to the same thing what i have done in dev (resolving laravelcollective issue) for every new production instance that i am gonna set it up ?



via Chebli Mohamed

mardi 23 février 2016

find in set in laravel ? example

I am new in laravel. My query is i need to find out value from comma separated field.

Here is my table.

Table name :- tags_value

| id  | tags         
| --- | ------------ 

| 1   | css,html,php 

| 2   | php,java,css      

| 3   | java,c++,ios 

My sql query :-

 $query = DB::table('tags_value')
          ->whereRaw(FIND_IN_SET('css',Tags))
          ->get();

but its not working.

Please help me for solve this problem.

Thanks in advance



via Chebli Mohamed

Curl request to twitter API using laravel 5.1

just start using curl don't know much about it i am trying to send a request to twitter API using laravel 5.1 through Curl that's my Controller code

public function getTwitterLogin($auth=NULL){
    if($auth == 'auth')
    {
        Hybrid_Endpoint::process();
        return;
    }
    try{
        $oauth=new Hybrid_Auth(app_path(). '/config/twitterAuth.php');
        $provider=$oauth->authenticate('Twitter');
        $client->getHttpClient()->setDefaultOption('verify', 'D:\General software');
       //curl_init();
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'https://api.twitter.com/1.1/users/search.json');
        $result = curl_exec($curl);
          var_dump($result);

i downloaded a curl folder from curl website and place the curl.exe file in D:\General software and changed the environment variable path also but now its replying that Undefined variable: client



via Chebli Mohamed

Sending info from database to SideNavigation blade through BaseController is good?

I have Layout Page that has following blade references.

<!DOCTYPE html>
<html lang="en">
<head>
    @include('Includes.head')                    //reference - 1
</head>
<body class="nav-md">
    <div class="container body">
        <div class="main_container">
            @include('Includes.topheader')       //reference - 2
            @include('Includes.sideNavigations') //reference - 3
            @yield('content')
            @include('Includes.footer')          //reference - 4
        </div>
    </div>
    @include('Includes.footerscripts')           //reference - 5
</body>
</html>

I want to send list of record to Side navigation. Can somebody suggest if I should use Base Controller



via Chebli Mohamed