jeudi 31 mars 2016

Validate whether multiple fields are unique simultaneously in laravel 5

This my request class rules.

        'eventDate' => 'required|date|after:yesterday',
        'venue' => 'required',
        'time' => 'required',

I want to validate a rule like below.

        'eventDate' && 'venue' && 'time' => 'unique'

There I need to check if there any row without same eventDate, venue and time altogether. Anyone knows how to declare such a rule?



via Chebli Mohamed

get first and last value of a groupby object in laravel 5 and mysql

I have a table called income.

+----+-------------+---------------------+--------+--------+--------+-----------+---------------------+---------------------+
| id | employee_id | date                | gross  | income | credit | comission | created_at          | updated_at          |
+----+-------------+---------------------+--------+--------+--------+-----------+---------------------+---------------------+
|  1 |           1 | 2016-03-30 19:21:09 | 100.00 |  29.00 |  11.00 |     60.00 | 2016-03-31 19:21:46 | 2016-03-31 19:21:46 |
|  2 |           1 | 2016-03-31 19:24:44 | 110.00 |  43.00 |   1.00 |     60.00 | 2016-03-31 19:24:56 | 2016-03-31 19:24:56 |
|  3 |           2 | 2016-03-31 21:44:09 |  77.00 |  30.80 |   0.00 |     60.00 | 2016-03-31 21:44:19 | 2016-03-31 21:44:19 |
+----+-------------+---------------------+--------+--------+--------+-----------+---------------------+---------------------+

what i want to do is query these and group it by employee_id and i want the date it started and date it end. What i got is

$records = Income::whereBetween('date', [$start, $end])
                ->groupBy('employee_id')
                ->selectRaw('store_incomes.* , sum(gross) as total_gross , sum(income) as total_income, sum(credit) as total_credit')
                ->get();

This always return the first date for that employee. For example, employee_id 1 always return the date of 2016-03-30 19:21:09. What i want is to get the first and last date for each employee_id, so employee id 1 would have start date of 2016-30-30 and end date of 2016-03-31. Is there a way to do this without messy manual code?



via Chebli Mohamed

How to use one to many relation in Laravel?

I'm beginning to use Laravel Model relationship. But now I don't know how to used that relationship as below function

 public function getNotification() {

        return self::select('*')->join('users','users.id','=','Notification.n_user_id')->get();
    }



via Chebli Mohamed

When using auth middleware, its redirecting me to home page

I am new in laravel app development. When I am using auth middleware, then it works fine for unregistered user(redirecting to login page). But when logged user going to visit that page, then its redirecting to home page (root directory).

below the route from routes.php code is

Route::group(['middleware' => 'auth'], function () {
    Route::resource('/edit', 'userController@edit');
});

Below my userController.php code is

<?php
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use App\Http\Requests;
 use App\allUsers;
 class userController extends Controller
 {
     public function index(){
     }

     public function show($id){
     }

     public function edit(){
         return view('auth.user_edit');
     }
  }

Anyone help me please.



via Chebli Mohamed

How addSelect() Builder method works in Laravel

Say I have these models:

User Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'User';

    protected $fillable =
    [
       'username', 'favoriteColor'
    ];          

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

Flight Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'Flight';

    protected $fillable =
    [
       'flightName', 
    ];              
}   

I'm trying to do something with eager loading, whenever I do this:

$usersWithFlights = User::with(['flights'])->get();

I get data like this: (Which if fine, is what I expect)

{
    "userID": 1,
    "favoriteColor": green
    "flights": 
    [
       {
           "flightID": 2240,
           "flightName" : "To Beijing fellas"
       },
       {
           "flightID": 4432,
           "flightName" : "To Russia fellas"
       },       
    ]
}

But then I want to add a column using a select raw like this: (Don't think about how silly the 1 as number is, it's just for the sake of the example.

$usersWithFlights = User::with(['flights'])->addSelect(DB::raw('1 as number'))->get();

I get the data like this:

[
    {
        "userID": 1,
        "favoriteColor": green
        "flights": []
    }
]

QUESTION

Was the addSelect() method made for this kind of behaviour? If not are other work arounds in order to achieve this?

NOTE

I know I could add in the select method something like Flights.*, Users.* but I want to know if the addSelect method works that way



via Chebli Mohamed

Query in controller but take variable from Blade for loop value Laravel

Problem is I don't want to query inside blade cause it's a bad idea, I have 2 tables:

"kriterias" table (id_kriteria, kriteria_name)
"evaluasis" table (id_food, id_kriteria, grade)

and have model for it:

Kriteria Model
    public function evaluasi()
    {
        return $this->hasMany(Evaluasi::class, id_kriteria, id_kriteria);
    }

Evaluasi Model
    public function kriteria()
    {
        return $this->belongsTo(Kriteria::class, id_kriteria, id_kriteria);
    }  

Controller part (don't wory about "nis" value, cause I get it from request it's integer) :

$jlhkriteria = Kriteria::count();
return view('rank', compact('nis', 'jlhkriteria));  

This is where my problems begin, I want this code to be applied in my blade view:

@for ($i=1;$i<=$jlhkriteria;$i++)
                    <?php $evaluasi = mysqli_query($mysqli, "SELECT k.kriteria_name,e.id_kriteria,e.grade FROM evaluasis e, kriterias k WHERE
                e.id_food='$nis' AND e.id_kriteria='$i' AND e.id_kriteria=k.id_kriteria");
                    $hasil = mysqli_fetch_array($evaluasi, MYSQLI_ASSOC); ?>

<?php echo $hasil['kriteria_name']; ?>
<?php echo $hasil['grade']; ?>

@endfor

As far as I know to join select query above using eloquent I use this :

$evaluasi = Kriteria::with(array('evaluasi' => function($query) use ($nis) { 
        $query  ->where('id_food', $nis)
            ->where('id_kriteria',$i)//this $i value are get from for loop in blade
            ->select('id_kriteria', 'grade'); 
    }))->get();  

I always have problem when query something inside for loop in blade. How to query it in controller while taking $i value in blade and echo "kriteria_name" and "grade"?



via Chebli Mohamed

Storing @include() in a variable?

Is it possible to store the output of @include('view.name') into a variable?

Something like this:

$var = @include('view.name')
{{$var}}

The reason I want to do that I want to pass @include('view.name') into Blade::directive()

For example:

@blocksection([
        'Title',
        '<p>Descrption</p>,
         @include('view.name'),
])
// HTML 
@endblocksection



via Chebli Mohamed

Laravel Scheduler not running daily

I have laravel scheduler set up to run daily and do a db backup. This will not work, but it will if I change to everyMinute(). Why cannot it not run daily, but works fine every minute?

Here is my cron:

* * * * * php /var/www/artisan schedule:run 1>> /dev/null 2>&1

And my command:

$schedule->command(
        "db:backup --database=mysql --destination=ftp --destinationPath=`date +\\%Y/\\%m/%m-%d-%Y` --compression=gzip"
    )->daily();



via Chebli Mohamed

Laravel 5.1 - Save in one timezone, display in another

I'm using Laravel 5.1 and I need everything in my database to be in UTC format. But when displaying the data it has to be in timezone 'Europe/Ljubljana' (also display needs to change depending on DST).

The app is already quite large so I want to change it on as few places as possible. What would be the best way for doing this?

What I thought of so far was either extending the model class and setting accessors/mutators (I have to change it in all x Models then) for created_at/updated_at or simply creating a trait for those accessors/mutators and putting it in all models.

But the problem with this is that some models have more than just created_at/updated_at and I need to add those mutators/accessors manually then for each model.

Is there any better way? And if not, does it make sense to make a trait or is it better to create some type of master model and extend it everywhere?



via Chebli Mohamed

Laravel 5 Multiple public folder asset function

I need some help.

I want to create a multisite from only one Laravel 5.1 installation. I read multiple .env based on subdomain.

But I want to every site has its own public folder.

So for example with this folders:

-> public
-> custom_publics
   -> user1
   -> user2
   -> etc

I can set public_path() but when I try to get it with asset() function doesn’t work.

For example: I have a image.png on http://ift.tt/1ZNpqyz. I change public_path() to custom_publics/user2. But when call asset(image.png)gives me http://ift.tt/1UEW32n and not exists.

There is some way to point to http://ift.tt/1UEW32n but really goes to http://ift.tt/1ZNpqyz ?

Or, how can I set asset() function path?

Any one has tried? Any help?

Regards, Eric.



via Chebli Mohamed

Fetch last N records Using Jenssegers laravel-mongodb

I want to fetch last 2 inserted chats of users according to the created_at time from the database in the sequence they were inserted using Jenssegers and Mongodb. I have tried some queries but not able to get the desired result.

These queries gives the first two chats in the sequence they were inserted:

$prev_chats = ChatMessages::where('chat_id','=', $chat_id)->take(2)->get();

$prev_chats = ChatMessages::orderBy('created_at','asc')->where('chat_id','=', $chat_id)->take(2)->get();

$prev_chats = ChatMessages::orderBy('created_at','asc')->where('chat_id','=', $chat_id)->paginate(2);

When I try to reverse the order then it fetch the last 2 but the serial in which they were inserted changes(Means Last becomes First).

$prev_chats = ChatMessages::orderBy('created_at','desc')->where('chat_id','=', $chat_id)->paginate(2);

$prev_chats = ChatMessages::orderBy('created_at','desc')->where('chat_id','=', $chat_id)->take(2)->get();

Is there a way to get the last 2 records in the sequence they were inserted.



via Chebli Mohamed

Laravel 5 re-usable project

After some fiddling building a package for a project we've realised there's some issues with doing what we need to achieve as per Laravel 5 package development clarity

Maybe I should rather explain my goal and someone can suggest a direction to head in.

We've built a Laravel 5 application that now needs to be "re-used".

We had to modify Laravel and implement an Eloquent type base model as our data-source is actually C# Web Services. At the point the call would be made to a database we intercept this and make an "API" call to SOAP.

The major difference will be CSS, maybe some JS & content but all the routes/controllers/models will remain the same across all projects. Most configuration comes from endpoints.

Initially we considered creating multiple asset repositories for each site's styling and have a base repo which is the core Laravel project that gets included. This seemed to get quite complex as we couldn't simply just have a repo in a repo due to branching and multiple directory issues.

We then started experimenting with the idea of building the "core" as a Laravel package but we seem to constantly hit walls. The latest problem being including models in the package. For the models to be called we are using the root projects config/composer to access these models instead of just the service provider. It feels like the package is becoming to tightly coupled to the project config.

Are there any better ways of going about what we are trying to achieve?



via Chebli Mohamed

Password creation link which was sent to the mail could not redirect the proper page in laravel

I can mail password creation link to the email address. But when I click that link it doesn't open my "Password Creation Page", instead it goes to my home page.

My route is:

Route::get('auth/set/password/{token}', 'Auth\PasswordController@getSetPassword')

any my PasswordController page is:

public function getSetPassword($token)
{
   return view('auth.create_password');
}

and the link in my mail is:

Click the given below link to generate your password:
http://krankontroll:8000/auth/set/password/IhQTMgArKUNYPf18WoloHzhWIjlewt

When I click this link it redirects to,

http://krankontroll:8000/home 

What mistake I made here? Can anyone help me with this????



via Chebli Mohamed

Laravel Model with Two Primary Keys update

I'm trying to update Model which has two primary keys.

Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Inventory extends Model
{
    /**
     * The table associated with the model.
     */
    protected $table = 'inventories';

    /**
     * Indicates model primary keys.
     */
    protected $primaryKey = ['user_id', 'stock_id'];
...

Migration

Schema::create('inventories', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->integer('stock_id')->unsigned();
    $table->bigInteger('quantity');

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

    $table->foreign('user_id')->references('id')->on('users')
        ->onUpdate('restrict')
        ->onDelete('cascade');
    $table->foreign('stock_id')->references('id')->on('stocks')
        ->onUpdate('restrict')
        ->onDelete('cascade');
});

This is code which should update Inventory model, but it doesn't.

$inventory = Inventory::where('user_id', $user->id)->where('stock_id', $order->stock->id)->first();
$inventory->quantity += $order->quantity;
$inventory->save();

I get this error:

Illegal offset type

I also tried to use updateOrCreate() method. It doesn't work (I get same error).

Can anyone tell how Model with two primary key should be updated?



via Chebli Mohamed

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

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

Any Idea what is wrong in my code.

Here is my HTML:

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

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

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

PasswordController.php

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

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

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

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

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



via Chebli Mohamed

How to execute MYSQL query in laravel?

I have one MYSQL query with me I want to execute this query in laravel.

    select d1.update_id from ( select update_id, count(update_id)
 as ct from updates_tags where tag_id in 
(67,33,86,55) group by update_id) as d1 where d1.ct=4

Please guide me how do i Do it easily.

I have one reference with me.... It is not working

$update = DB::table('tags')
->select('t_id', 'u_id', DB::raw('count(*) as total'))
->whereIn('t_id',$tags)
->where('total','=',count($tags))
->groupBy('u_id')
->lists('u_id');



via Chebli Mohamed

Laravel 5 isDirty() always returns false

I want to check if the model has been changed with isDirty method, but always returns false.

This is my code :

 if (!is_null($partnersData)) {
        foreach ($partnersData as $partnerData) {
            $partner = Partner::find($partnerData['partner_id']);
            $partner->update($partnerData);

            if($partner->isDirty()){
                dd('true');
            }
        }
    }



via Chebli Mohamed

Laravel 5 eloquent order by subtraction

How to perform this query using Eloquent

select * from `reviews` order by `up_vote` - `down_vote` desc

I am trying to do something like this:

$top_reviews = $reviews()->orderBy('up_vote - down_vote','DESC')->get();

But I am getting Unknown column 'up_vote - down_vote'. Is it possible to do this without using DB ?



via Chebli Mohamed

getting err_too_many_redirects in laravel when I use Request for validation for validating unique

it is my error page

I have used customize Request page for geting value from post request.

in that request I am validation

namespace App\Http\Requests;

use App\Http\Requests\Request;

class TaxclassRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            "tax_class"=>'unique:taxes,tax_class'
        ];
    }
}

and my controller is


    function insert(TaxclassRequest $request)
    {



                $n=$request->input('number');           //total number of variable that has been created dyanamic
                $tax_class=$request->input("tax_class"); // tax_class
.
.
.
other code

I am getting error ERR_TOO_MANY_REDIRECTS



via Chebli Mohamed

Hidden input field value should be changed according to the drop box selection

This my script code. There's something wrong with it.

$(function() {
    $('#type').on('change', function() {
        if ($('#type').val('Workshop'))
            $('#color').val($('Orange').val());
        else if ($('#type').val('Social'))
            $('#color').val($('Green').val());
        else if ($('#type').val('Other'))
            $('#color').val($('Red').val());

    });
});



via Chebli Mohamed

Laravel run composer / git commands within controller

is it possible to run composer or git commands from within a controller in Laravel? Something like that:

class TestController extends Controller
{
    //
    public function shell(Request $request){
        if($request->isMethod('post')){


            $data['output'] = shell_exec('composer update');
            // or some git commands
            return view('tests.shell', $data);
        } else {
            return view('tests.shell');
        }
    }
}

If I do it the way shown above, I get no message. I think, the problem is, that these commands have to be run in the projects root directory and not in an subfolder.

And is there a php function to run a complete shell script and not only single commands?

Thanks!



via Chebli Mohamed

How should I call a function from model in laravel?

I'm build an application with Laravel which is new for me and I want to create any method in model and i will call that method from those model in some Controller but I don't know it is good or follow Laravel structure or not because Codeigniter let developer do that thing.

How can I use this structure with Eloquent instead of using raw sql query? because I got no data if I used $data = self::select("*")->get(); to query data.

This is my Model

    <?php
/**
 * Created by PhpStorm.
 * User: SOPHEAK Heng
 * Date: 16/03/31
 * Time: 10:29 AM
 * Notification Module
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Notification extends Model {

    protected $table = 'notification';
    public $timestamps = false;

    public function __construct(array $attributes)
    {
        parent::__construct($attributes);
    }
     public static function queryData() {

    $data = self::all();
    return $data;
    }
}

Here is Controller:

<?php
/**
 * Created by PhpStorm.
 * User: SOPHEAK Heng
 * Date: 5/25/2015
 * Time: 5:40 PM
 */

namespace App\Http\Controllers;
use App\Models\Notification;

class MyController extends Controller
{ 

    public function __construct()
    { 
        $t = $this->sendDataToView();
        var_dump($t);
    }
    public function sendDataToView() {

        $test = new Notification();
        return $test->queryData();
    }

}

Here is my result when I have try to used Eloquent It seem known that tables but can't see any data at there enter image description here



via Chebli Mohamed

mercredi 30 mars 2016

Execute a function inside script tag

This my script.

<script>
    $(document).ready(function(){
        $('#type').on('change',function(){
            $('#color').val($(this).val());
        });
    });
</script>

How should I execute this code? Where should I call? That is in the view blade.php file. Form is also there. Do I need to call that on submit button? The above code is to change a hidden input value according to selected drop box value



via Chebli Mohamed

using github laravel 5.2 projects

when am trying to download larvael 5.x projects from github and trying to use it

i got these two errors :

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

Fatal error: require(): Failed opening required 'C:\wamp\www\laravelshop\bootstrap/../vendor/autoload.php' (include_path='.;C:\php\pear') in C:\wamp\www\laravelshop\bootstrap\autoload.php on line 17

is there anything i need to modify first after downloading any project , before using it ?



via Chebli Mohamed

NotFoundHttpException in Handler.php line 102: No query results for model [App\....]

I tried to edit/update my data in database. But always get this error.

NotFoundHttpException in Handler.php line 102: No query results for model [App\Produk]

Here's the function in controller:

public function update($id, Request $request)
{
    $data = Produk::findOrFail($id);
    $data->update($request->all());
    return redirect('pages.admin.lihat');
}

And here's my edit.blade.php form:

    {!! Form::model($data,['method'=>'PATCH','url' => 'admin/update']) !!}

<div class="contact-form">
<div class="form-group">
    {!! Form::label('Nama Produk') !!}
    {!! Form::text('nama', null, 
        array('required', 
              'class'=>'form-control', 
              'placeholder'=>'Nama Produk')) !!}
</div>

<div class="form-group">
    {!! Form::label('Jumlah Produk') !!}
    {!! Form::number('jumlah', null, 
        array('required', 
              'class'=>'form-control', 
              'placeholder'=>'Jumlah Produk')) !!}
</div>

<div class="form-group">
    {!! Form::label('Harga') !!}
    {!! Form::text('harga', null, 
        array('required', 
              'class'=>'form-control', 
              'placeholder'=>'Harga')) !!}
</div>

<div class="form-group">
    {!! Form::label('Gambar') !!}
    {!! Form::text('images', null, 
        array('required', 
              'class'=>'form-control', 
              'placeholder'=>'Gambar')) !!}
</div>

<div class="form-group">
    {!! Form::submit('Edit', 
      array('class'=>'btn btn-primary')) !!}
</div>

</div>
{!! Form::close() !!}

I use this in my routes (the first one is for the store function so nothing to do with this update):

Route::post('admin/success','ProdukController@simpan');

Route::resource('admin','ProdukController');



via Chebli Mohamed

Can i add sub route in Route::get?

I need control sub route by User Config

  • i can't get request/route parameters on Route::group
  • middleware run after Route::group
  • Can't Include file sub route in Route::get

How do you do.

Example.

Route.php

Route::group(['prefix' => '/{user}'], function () { 

    Route::group(['prefix' => '/map'], function () { require app_path('map.route.php'); });
    Route::group(['prefix' => '/contact'], function () { require app_path('contact.route.php'); });

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

      $user = \App\User::find($user);
       if( $user -> first_page )
       {
        require app_path($user -> first_page.'.route.php');
       }

    });

});

Thank you very much.



via Chebli Mohamed

Laravel 5 validation issue with reset password form

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

Any Idea what is wrong in my code.

Here is my HTML:

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

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

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

PasswordController.php

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

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

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

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

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



via Chebli Mohamed

doesnot show any validation error messages in laravel5

I have used this function in controller to store the records of the users with validations. The data is not stored if the validation is not met but it doesnot show any validation error message.

public function store()
  {

        $input = Input::all();
        $validation = Validator::make($input, User::$rules);

        if ($validation->passes())
        {
            User::create($input);

            return Redirect::route('users.index');
        }

        return Redirect::route('users.create')
            ->withInput()
            ->withErrors($validation)
            ->with('message', 'There were validation errors.');
  }

I have the model:

<?php
namespace App;

class User extends BaseModel{

    protected $fillable = [
        'name', 'email', 'password', 'phone'
    ];


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

  public static $rules = array(
    'name' => 'required|min:5',
    'email' => 'required|email');
}



via Chebli Mohamed

Laravel - Pass AJAX data to function

I am working on a very simple Laravel application that basically presents a graph based on an id. I believe I have set up the correct route using:

app\Http\routes.php

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for 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('getProcessorData', array('uses' => 'HonoursController@getProcessorData'));
#Route::get('getProcessorData/{id}', 'HonoursController@getProcessorData');
Route::get('getBandwidthData', array('uses' => 'HonoursController@getBandwidthData'));
Route::get('getMemoryData', array('uses' => 'HonoursController@getMemoryData'));

Route::resource('honours','HonoursController');

From there I went on to set up the correct function in the controller:

app\Http\Controllers\HonoursController.php

...
    public function getProcessorData()
    {
      $id = Input::get('host_id');
      return Response::json(HostProcessor::get_processor_formatted($id));
    }
...

Since this called a function from the HostProcessor model, I created this function below:

app\HostProcessor.php

...
    public static function get_processor_formatted($id)
    {
        $processor = self::findorfail($id);

        $json = array();
        $json['cols'] = array(
          array('label' => 'Time', 'type' => 'string'),
          array('label' => 'Kernel Space Usage', 'type' => 'number'),
          array('label' => 'User Space Usage', 'type' => 'number'),
          array('label' => 'IO Space Usage', 'type' => 'number')
        );

        foreach($processor as $p){
          $json['rows'][] = array('c' => array(
            array('v' => date("M-j H:i",strtotime($p->system_time))),
            array('v' => $p->kernel_space_time),
            array('v' => $p->user_space_time),
            array('v' => $p->io_space_time)
          ));
        }

        return $json;
    }
...

Finally I set up my AJAX function such as below:

resources/views/honours/partials/master.blade.php

...
     <script type="text/javascript">
        // Load the Visualization API and the piechart package.
        google.charts.load('current', {'packages':['corechart']});

        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
           var processor_usage = $.ajax({
              url:'getProcessorData',
              dataType:'json',
              async: false
           }).responseText;

           var p_options = {
              title: 'Processor Usage',
              width: 800,
              height: 400,
              hAxis: {
                 title: 'Time',
                 gridlines: {
                    count: 5 
                 }
              } 
          };
...

Now the issue I am having here is when I try and pass a value to the HostProcessor function it fails. I have tried passing an id value using the data attribute of AJAX. By doing this I had to update my route to Route::get('getProcessorData?{id}', array('uses' => 'HonoursController@getProcessorData')); but this still failed with a 404 error. I also tried just getting the value of host_id value using $id = Input::get('host_id'); and passing those to the HostProcessor function but that still failed with a 404 error. Any ideas why?



via Chebli Mohamed

Laravel Cashier Stripe API method calls is an optional per-request apiKey

I hope some one can help me, Im using Laravel 5.2 and Cashier 6, and Im getting this error

Api in RequestOptions.php line 77: The second argument to Stripe API method calls is an optional per-request apiKey, which must be a string, or per-request options, which must be an array. (HINT: you can set a global apiKey by "Stripe::setApiKey()")

but all the API of stripe are ok, thanks



via Chebli Mohamed

Using Laravel 5.2's Authenticated() Method

I am using Laravel 5.2's default authentication and having some trouble with the behavior of the framework's authenticated() method. The method is useful for running code after successful authentication occurs but before loading any subsequent pages. A successful authentication will trigger the authenticated() method in AuthController, which I have defined as follows:

protected function authenticated() {
        session(['loggedIn' => 'show']);
        return redirect('/home');
}

As we see, it can be useful for setting session variables that are required when the homepage first loads up (but that should not be reset each time the homepage is reloaded).

In my case, I use loggedIn to display a certain welcome div only once per session after the user logs in or registers. I include the following PHP on the homepage for that:

function displayWelcome() {
    if (session('loggedIn') == 'show') {
        echo '<div class="container" name="loggedIn" id="loggedIn">';
        session(['loggedIn' => 'hide']);
    } else {
        echo '<div class="container" name="loggedIn" id="loggedIn" hidden>';
    }
}

Presently, this code works fine when existing users log in.

It does not, however, fully work for user registrations. It does successfully redirect to the homepage, but the welcome div never shows up at all. Oddly enough, when I echo session('loggedIn') before calling the displayWelcome() function, it outputs "hide" after registration (and correctly displays "show" after login). I fail to see how it is acquiring the value "hide" and why it is not correctly opening the div.

Any hints?



via Chebli Mohamed

Access denied for user 'homestead'@'localhost' (using password: YES) on Laravel 5.2.27

I have been creating a Laravel 5.2 application and everything was working perfectly until this morning. Now, when I try to login to the laravel app like I did yesterday at localhost:8888/login, I get this: PDOException in Connector.php line 55: SQLSTATE[28000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

There was an OSX 10.10.5 security update 2016-002 that was installed and required a restart. I think this is the only thing that changed between it working and not working. It's apparently too soon to see the details of that update on the apple site.

My .env file looks like this:

APP_ENV=local
APP_DEBUG=true
APP_KEY=0ag8zA7SD5JRSmQTmVOpteTx82lIZF3n
APP_URL=http://localhost:8888

DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_lic
DB_USERNAME=root
DB_PASSWORD=root

I searched the web and StackOverflow for answers and have tried the following:

  • php artisan config:clear to clear the config
  • Restarted the server by ^C in the terminal window where the server was started and then started it again with php -S localhost:8888 -t public
  • Restarted the MySQL server using the OSX System Preferences panel like usual.
  • Checked the connection using php artisan tinker and entering DB::connection()->getDatabaseName() which resulted in "laravel_lic"
  • Checked the Config database username with Config::get('database.connections.mysql.username') in tinker which resulted in "root"
  • ran php artisan migrate:reset which successfully rolled back all the migrations, then ran php artisan migrate which successfully migrated the tables and verified using the database panel in PHPStorm as I have been doing since I started the project.
  • Did a text search in the entire project for the word 'homestead' and the only results were in the git ignore file.
  • I ran composer update which updated some Symfony stuff.

I'm NOT using homestead.

I also did NOT do anything related to the unix_socket. I hadn't heard of it until searching for answers to this question and don't see any settings for it so I doubt there could be an issue there.

I have been trying things for the last few hours, many more than once (such as restarting the server) so I'm doubtful the order of doing things could be a cause.

Is anyone else having this issue? Are there any other things I should try to get it working again?



via Chebli Mohamed

Letter "a" at the beginning of every request using built in PHP server with laravel causing Unexpected EOF

So, yesterday all was fine but today all every time a load a page a letter a briefly appears in the top left. Also, I use InterventionImage with some of my images, so I am not directly loading an image file and this a has broken those (http://ift.tt/1RyJrDy). But I also noticed that this mysterious a also appears at the begging of composer commands (http://ift.tt/1UCZoie). When I load one of these images in a new tab I get the following error: Invalid request (Unexpected EOF) I am totally stumped and would appreciate any help at all! Thanks!



via Chebli Mohamed

Relationship order in laravel 5

I am having trouble with orderBy in laravel 5, using mysql datbase. Consider the following table structure:

calendarios

id (int) | descricao (varchar) | ano (int)

4 | 'Teste' | 2016

and eventos

id (int) | descricao (varchar) | data (date) | calendario_id (int)

1 | 'Festa' | '2016-05-13' | 4

2 | 'Natal' | '2016-12-25' | 4

Then, the respective models in my laravel project. Inside my 'Calendario' model, i have the following relationship:

/**
 * 
 * @return type
 */
public function eventos(){
    return $this->hasMany(\App\Cms\Evento::class);
}

But, when i try to get the "eventos" from "calendario" and order by date, it returns in the inverse order. For example:

$calendario = \App\Cms\Calendario::findOrfail(4);
if($calendario->eventos){

    foreach($calendario->eventos()->orderBy('data', 'desc')->get() as $evento){
        echo $evento->descricao . ' - ' . Carbon::parse($evento->data)->format('d/m');
    }

}

It is showing the event with the event 'Festa - 13/05' when the intended result would be display 'Natal 25/12' first. I'm stuck with this problem for hours... Is there something I'm missing?



via Chebli Mohamed

Hidden input value should be changed when selecting a item from drop box in laravel 5

Here is my drop box and then after the hidden box. These are inside the form.

 <tr>
     <td> <b>{!! Form::label('Types', 'Type') !!}</b></td>

     <td> {!! Form::select('type', array('type' => 'type','Orange' => 'Orange', 'Red' => 'Red','Green' => 'Green'), 'type') !!}</td>
</tr>

{!! Form::hidden('color') !!}

Script is below after the form.

<script>
    $(document).ready(function () {
        $('#type').on('change', function () {
            $('#color').val($(this).val());

        });
        $('#Orange').on('change', function () {
            $('#color').val($(this).val());
        });
        $('#Red').on('change', function () {
            $('#color').val($(this).val());
        });
        $('#Green').on('change', function () {
            $('#color').val($(this).val());
        });
    });
</script>

Hidden input value get empty after the execution. Where am I wrong. Please can you help that out for me?



via Chebli Mohamed

Angular JS cropping but not resizeing

I'm currently using Andy Shora image cropper in my Laravel 5 project and was wondering if there is a way to crop the image into specific rectangle, but not resizing it to the small rectangle, meaning, if the image was 1000x1000, then, if I resize it into 100x50 rectangle, the new image size would be 1000x500.

Maybe there is there a way to find the coordinates of the original image and save the resolution without using a different script?

These are all parameters for that script:

<!-- <image-crop
    data-height="200" //shape's height
    data-width="150" //shape's width
    data-shape="square" //the shape.. square or circle
    data-step="imageCropStep"//scope variable that will contain the current step of the crop (1. Waiting for source image; 2. Image loaded, waiting for crop; 3. Crop done)
    src="imgSrc" //scope variable that will be the source image for the crop (may be a Blob or base64 string)
    data-result-blob="result" //scope variable that will contain the Blob information
    data-result="resultDataUrl" //scope variable that will contain the image's base64 string representation
    crop="initCrop" //scope variable that must be set to true when the image is ready to be cropped
    padding="250" //space, in pixels, rounding the shape
    max-size="1024" //max of the image, in pixels
></image-crop> -->



via Chebli Mohamed

Change column type using laravel migration using Doctrine DBAL gives error

I use Laravel 5.2, Php7, Apache, Windows

my migration file is "2016_03_30_095234_alter_date_update_news_table.php"

class AddSlugUpdateNewsTable extends Migration
{
    /**
     * Run the migrations.
     * php artisan make:migration add_slug_update_news_table
     * @return void
     */
    public function up()
    {
        Schema::table('news', function (Blueprint $table) {
            $table->date('slug')->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('news', function (Blueprint $table) {
            $table->dateTime('slug')->change();
        });
    }
}


But after run migrate,

$\> php artisan migrate

gives me this error!

[RuntimeException] Changing columns for table "news" requires Doctrine DBAL; install "doctrine/dbal".

what do i do?



via Chebli Mohamed

Selected drop box value not changing the another field value in laravel 5

I want to set the hidden input field value to selected drop box value. Here is my hidden field code and drop box code.

 {!! Form::hidden('color') !!}


 {!! Form::select('type', array('type' => 'type','Orange' => 'Orange', 'Red' => 'Red','Green' => 'Green'), 'type') !!}

Below is my jquery.

<script>
$(document).ready(function(){
    $('#type').on('change',function(){
        $('#color').val($(this).val());

    });
    $('#Orange').on('change',function(){
        $('#color').val($(this).val());
    });
    $('#Red').on('change',function(){
        $('#color').val($(this).val());
    });
    $('#Green').on('change',function(){
        $('#color').val($(this).val());
    });
});

But as the hidden field value it will not set the value. Why is that?



via Chebli Mohamed

Strange result in routing

I have the following set up in my route file

Route::resource('reports', 'CampaignReport\CampaignReportController');
Route::get('reports/generateExcel', array('as' => 'reports.generateExcel', 'uses' => 'CampaignReport\CampaignReportController@generateExcel'));

I am not tieing it to a Model as it is just for creating generic reports. If I output my routes I see (I have removed some of the common ones)

|        | GET|HEAD                       | reports                                                                              | reports.index                                     | App\Http\Controllers\CampaignReport\CampaignReportController@index           | auth
|        | GET|HEAD                       | reports/create                                                                       | reports.create                                    | App\Http\Controllers\CampaignReport\CampaignReportController@create          | auth
|        | GET|HEAD                       | reports/generateExcel                                                                | reports.generateExcel                             | App\Http\Controllers\CampaignReport\CampaignReportController@generateExcel   | auth
|        | GET|HEAD                       | reports/{reports}                                                                    | reports.show                                      | App\Http\Controllers\CampaignReport\CampaignReportController@show            | auth

So everything looks fine. Now in one of my views, I have the following

<td>{!! link_to_route('reports.generateExcel', 'Generate Excel', null, array('class' => 'btn btn-info')) !!}</td>

So that should trigger the generateExcel function within my controller. At the moment, my controller is like so

public function show()
{
    return "SHOW PAGE";
}

public function generateExcel()
{
    return "EXCEL GENERATED";
}

Now the strange thing is, that link to route returns SHOW PAGE for some reason, when it should return EXCEL GENERATED. However, if I make a change in my route and remove the show route e.g.

Route::resource('reports', 'CampaignReport\CampaignReportController', ['except' => ['show']]);

The same link to route will now show what it is supposed too and that is EXCEL GENERATED.

So why would the show function be called in the first instance?

Thanks



via Chebli Mohamed

Laravel 5 how to test redirect

I have a Laravel 5 app in which one controller action finishes by redirecting to a page outside the Laravel app but on the same domain. Interacting manually with the page works fine, but automating the test with PHPunit doesn't. It keeps trying to load the route and fails with 'headers already sent'.

Route

Route::post('/trials', [
    'middleware' => ['web'],
    'uses' => 'TrialsController@create'
]);

Controller

public function create(Request $request)
{
  ...
  setcookie( 'etc', $value, time() + 60, '/', "domain.com", true, true) ;
  return Saml2::login('http://ift.tt/1pbc3uW');
}

Test

public function testSuccessfulSignup(){

    $this->visit('/signup')
        ->type('test@mail.com', 'mail')
        ->type('Philip', 'first_name')
        ->type('Fry', 'last_name')
        ->press('Signup !') ;
        // ->seePageIs('http://ift.tt/1pbc3uW'); doesn't work
        // ->assertRedirectedTo('http://ift.tt/1pbc3uW'); doesn't work
}

Error

1) TrialsTest::testSuccessfulSignup
A request to [http://ift.tt/1V4P9ll] failed. Received status code [500].

/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:196
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:80
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:114
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:554
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:541
/private/var/identity/tests/TrialsTest.php:154

Caused by
exception 'ErrorException' with message 'Cannot modify header information - headers already sent by (output started at phar:///usr/local/bin/phpunit/phpunit/Util/Printer.php:134)' in /private/var/identity/app/Http/Controllers/TrialsController.php:84



via Chebli Mohamed

Validation rule to check against multiple rows

When updating location names, I need validation to check against multiple rows in the table, not just a single id.

My table looks like this:

+----+--------------+-----------+----------+
| id |     name     |    lat    |   lng    |
+----+--------------+-----------+----------+
|  1 | Location One | 53.348333 | 0.348333 |
|  2 | Location One | 57.348222 | 0.348222 |
|  3 | Location One | 57.348111 | 0.545454 |
|  4 | Location Two | 55.348554 | 0.555444 |
|  5 | Location Two | 56.348667 | 0.348333 |
|  6 | Location Two | 56.348778 | 0.111111 |
+----+--------------+-----------+----------+

Creating new locations works as expected. But I'm not sure how to set the validation rule to exclude the current location I'm trying to update - it needs to check against the 'name' column.

I was hoping something like this may work - but it doesn't.

public function rules()
{
    return [
        'name' => 'required|max:255|unique:evac_routes,name,'.$this->name,
         ...
    ];
}

In my controller I'm using Route::where('name', $route->name)->update, which works, but I can't convert this logic to the validation rule:

public function update($id, UpdateRouteRequest $request)
    {

        $route = Route::findOrFail($id);    

        $updateRows = Route::where('name', $route->name)->update([
            'name' => $request->name,
            ...
            ]);            

        return redirect('routes');    

    }



via Chebli Mohamed

Call to undefined method App\Http\Controllers\SubscriptionController::getMiddleware()

I am calling the \prelaunchroute in my application and this is how it is defined in my routes.php:

Route::get('/prelaunch', [ 'uses' => 'SubscriptionController@getReferrer', 'as' => 'subscriber.referral'], function () { return view('prelaunch'); });

But unfortunately, I am getting: Call to undefined method App\Http\Controllers\SubscriptionController::getMiddleware()

This is a draft of my SubscriptionController code:

namespace App\Http\Controllers;

use App\Http\Manager\SubscriptionManager;
use Illuminate\Support\Facades\Request;


/**
 * Class SubscriptionController
 * @package App\Http\Controllers
 */
class SubscriptionController
{
    /**
     * @var \SubscriptionManager $subscriptionManager
     */
    protected $subscriptionManager;

    /**
     * SubscriptionController constructor.
     */
    //public function __construct(SubscriptionManager $subscriptionManager)
    public function __construct(SubscriptionManager $subscriptionManager)
    {
        $this->subscriptionManager = $subscriptionManager;
    }

    /**
     * @param Request $request
     * @return void
     */
    public function subscribe(Request $request)
    {
        $this->subscriptionManager->subscribeToList($request);
    }

    /**
     * @param Request $request
     * @return void
     */
    public function unsubscribe(Request $request)
    {
        $this->subscriptionManager->unsubscribeFromList($request);
    }

    /**
     * @return void
     */
    public function getReferrer()
    {
        print_r(Input::all());
        die;
        $utm_source = \Input::get('utm_source');


        return view('prelaunch');
    }
}

Any thoughts on this one? Please bare in mind that I am fairly new to Laravel.



via Chebli Mohamed

Linking to the route error in laravel 5

I have this route:

    Route::resource('users', 'UserController');
    Route::get('/users/create', 'UserController@create');

and the controller function is:

 public function index()
  {
    $users=User::all();
    return View('users.index',compact('users'));    

 }

And i have this code in index.blade.php where shows the error:

<p>{{ link_to_route('users.create', 'Add new user') }}</p>

the error message is:

Route [users.create] not defined. (View: C:\xampp\htdocs\larapro\resources\views\users\index.blade.php)



via Chebli Mohamed

SAPUI5 For the UI and LARAVEL for backoffice

I have to begin a new project and that's 2 years ago that i'm working on SAPUI5, But for severals reasons i have to use the Framwork of Laravel to handle the database logic and controller to get and put data from and to the database.

I apprerciate a lot a powerfull of the Ui framework SAPUI5, and i would like to use it for the Front end of my app.

My question is : It is possible to handle a Server application with those 2 technologies?

My second question is : Which hosting i have to choose, because that my client want a kind of desktop app, and for this I thought to use node webkit package. And for that i have to launch a node server. In my goDaddy shared hosting i don't have this possibility.

Thank you for your help!



via Chebli Mohamed

Laravel JWT Auth fetch user if token

I'm using the jwt-auth package for Laravel. It's working great, but it seems that a user has to be authenticated or not.

For instance some routes do not require authentication, but if the token is present it should still authenticate the user. The parameters I display to user from API can vary based on the type of users access. So admins will get some additional parameters.

Right now it will always just throw token absent. But it should go through as normal and "IF" token is present, process it.

Not sure if I need to create a custom middleware for this.

class JWTAuthIfPresent
{
    public function handle($request, Closure $next)
    {
        if (JWTAuth::getToken()) {
            JWTAuth::parseToken()->authenticate();
        }

        return $next($request);
    }
}

This seems to work, but not sure if there is a better way or something already in the existing package.



via Chebli Mohamed

Redirect with Laravel 5 helper Raising 403 Error

I have a project which is running fine on 'http', we decided to use https and every thing was going fine and suddenly noticed the problem that when we submit a form to a route it gives 403 Forbidden error. The form uses Laravel FormBuilder class and I used secure=true to get the secure url to submit the form.

I'm using nginx and apache, both have the same problem.

Here is my nginx file:

server {
    listen 80;
    server_name servername
    charset utf-8;
    sendfile off;
    client_max_body_size 10m;
    index index.php;
    root /var/www/servername/public;

    location /ping.html {
            return 200 'pong';
    }

location ~ ^/billing/(.+(?:css|js|woff|woff2|ttf))$ {
            alias /var/www/billing/public/$1;
            access_log off;
    }

#billing code in laravel5
location /billing/ {
    alias /var/www/billing/public;
    ## Check for file existing and if there, stop ##
    if (-f $request_filename) {
            break;
    }

    ## Check for file existing and if there, stop ##
    if (-d $request_filename) {
            break;
    }
    index index.php;
    try_files $uri $uri/ @billing;
}
location @billing {
rewrite /billing/(.*)$ /billing/index.php?/$1 last;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    set $php_root /var/www/servername/public;
    if ($request_uri ~ /billing) {
        set $php_root /var/www/billing/public;
    }
    fastcgi_param PATH_TRANSLATED $php_root/index.php;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param REMOTE_ADDR $http_x_real_ip;
    include fastcgi_params;
    fastcgi_intercept_errors off;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
    fastcgi_read_timeout 120;
}

location / {
try_files $uri $uri/ /index.php?$query_string;
}


location ~ /\.ht {
deny all;
}
}

Any help please?



via Chebli Mohamed

Integrity constraint violation using factory relationships in laravel 5.2

I am new to testing in laravel and I'm trying to create dummy data using Model Factories. I have three tables firms, clients, and briefs. A firm has many clients and a client has many briefs. The format of clients and briefs is very similar. They both have foreign keys firm_id and client_id respectfully. Whilst doing a phpunit test I want to create an instance of a client from a firm and an instance of a brief from the client using the following code:

$client = $firm->clients()
               ->save(factory(App\SearchFirmClient::class)->create());
$brief  = $client->briefs()
                 ->save(factory(App\SearchFirmBrief::class)->create());

$client is created without a fuss but $brief throws up an error:

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null (SQL: insert into `search_firms_briefs` (`user_id`, `title`, `description`, `contact_id`, `client_id`, `updated_at`, `created_at`) values (1, Et in amet., Quo soluta ut impedit nesciunt autem. Laborum aperiam est non molestiae animi non quod. Explicabo eligendi doloribus ex quia vitae placeat ut., 0, , 2016-03-30 10:06:34, 2016-03-30 10:06:34))

The formats of both tables:

Schema::create('search_firms_clients', function(Blueprint $table)
{
    $table->increments('client_id');
    $table->integer('search_firm_id')->unsigned();
    $table->foreign('search_firm_id')->references('id')->on('search_firms')->onDelete('cascade');           
    $table->string('name');
    $table->softDeletes();
    $table->timestamps();
});

Schema::create('search_firms_briefs', function(Blueprint $table)
{
    $table->increments('brief_id');
    $table->integer('client_id')->unsigned();
    $table->foreign('client_id')->references('client_id')->on('search_firms_clients')->onDelete('cascade');         
    $table->string('title');
    $table->softDeletes();
    $table->timestamps();
});

The model factory for each:

$factory->define(App\SearchFirmClient::class, function ($faker) {
    return [
        'name'      => $faker->company,
        'email'     => $faker->companyEmail,
        'phone'     => $faker->phoneNumber,
        'address'   => $faker->address,
        'website'   => $faker->url,
    ];
});

$factory->define(App\SearchFirmBrief::class, function ($faker) {
    return [
        'user_id'       => 1,
        'title'         => $faker->sentence(3),
        'description'   => $faker->text(),
        'contact_id'    => 0,
    ];
});

The relationships:

class SearchFirm extends Model
{

    protected $table = 'search_firms';
    protected $primaryKey = 'id';

    public function clients() {
        return $this->hasMany('SearchFirmClient', 'search_firm_id');
    }
}

class SearchFirmClient extends Model
{

    use SoftDeletes;

    protected $table        = 'search_firms_clients';
    protected $primaryKey   = 'client_id';
    protected $dates        = [ 'deleted_at' ];


    public function briefs()
    {
        return $this->hasMany('SearchFirmBrief', 'client_id')->orderBy( 'updated_at', 'desc');
    }
}

class SearchFirmBrief extends Model
{

    use SoftDeletes;

    protected $table = 'search_firms_briefs';
    protected $primaryKey = 'brief_id';
    protected $touches = array('client');
    protected $dates = [ 'deleted_at'];

    public function client() {
        return $this->belongsTo('SearchFirmClient', 'client_id');
    }
}

Help me stackoverflow, you're my only hope.



via Chebli Mohamed

Get the referral source url in Laravel

I am a Laravel-newbie and have got the following piece of code in my landing page:

Route::get('/prelaunch', [ 'uses' => 'SubscriptionController@getReferrer', 'as' => 'subscriber.referral'], function () {
    return view('prelaunch');
});

What I would like to do, is to read a field such as "utm_source" from the url and store take some actions against it, such as counting the users that land into the page from twitter, fb etc.

Any suggestions on this one?



via Chebli Mohamed

How to implement autocomplete Elasticsearch in Laravel

When a word is searched, I get the result only if I completely type the word.But I would to get the suggestion when 1st two letter of the word is typed. For example if word 'Apple' is typed I get the result but I want the result when 'Ap' is type. Could someone help me in this? I am using laravel 5.2



via Chebli Mohamed

Existing database integration with Laravel 5.0

I am new to laravel. I've got the whole database designed in phpmyadmin. Now I want to integrate the existing database in Laravel. Is there any way to do that? If so then do I have to create models?



via Chebli Mohamed

URL was not found on this server laravel

project is working fine on localhost but when I upload it on server it shows

Not Found


The requested URL /yes was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request

only / route is working other route is not working on route.php file



via Chebli Mohamed

How to make a notification field in laravel 5

I want to create a notification in field for laravel 5 project. And it should be displayed in the drop down box. Can anybody help me that with code?



via Chebli Mohamed

mardi 29 mars 2016

According to the selected value of drop box I need to change the another field value in laravel 5?

Where should I implement the logic? I mean inside which class? It was not work in the controller method? SO can anybody help me please



via Chebli Mohamed

What code handles the creation of laravel's daily logs?

My daily logs have the following permissions:

-rw-rw-rw- 1 root    root    108384 Mar 29 00:30 laravel-2016-03-28.log

This causes a Failed to open stream: Permission denied error

If I delete the log file, it will be recreated with the correct permissions.

-rw-rw-rw- 1 php-fpm php-fpm    819 Mar 28 18:04 laravel-2016-03-28.log

This stackoverflow solution seems to be working,

I added the following to bootstrap/app.php:

/**
 * Configure Monolog.
 */
$app->configureMonologUsing(function(Monolog\Logger $monolog) {
    $filename = storage_path('logs/laravel-'.php_sapi_name().'.log');
    $handler = new Monolog\Handler\RotatingFileHandler($filename);
    $monolog->pushHandler($handler);
});

However, I still have new daily logs being created by root:root. These logs are not being used for anything. Where are these logs being created and why are they being created with root:root?

What code handles the creation of these daily logs?



via Chebli Mohamed

Get the highest id from a specific where clause

I have 4 records on my guests database.

enter image description here

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


I've tried

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

I got

Trying to get property of non-object


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



via Chebli Mohamed

Deploying Laravel on Azure

I am trying to move my laravel 5.2 website to azure and I am getting a 500 error.

Steps I followed:

  1. Install Composer (via azure interface)
  2. Changed PHP version to 5.6
  3. Connect from Bitbucket
  4. Fetch files succesfully
  5. Make sure there is a web.config file
  6. Change default path to site\wwwroot\public\
  7. run "composer install"

Normally, visiting the main page I would get a laravel error (since I didn't upload or create the database yet). Instead, I am getting a 500 error.

The *.azurewebsites.net page isn’t working

*.azurewebsites.net is currently unable to handle this request.

500

So, I turned on "Detailed error messages". The file generated says:

Detailed Error Information:

Module FastCgiModule

Notification ExecuteRequestHandler

Handler PHP56_via_FastCGI

Error Code 0x00000000

Any ideas on how to proceed?



via Chebli Mohamed

In Laravel 5, migration to drop composed unique key doesn't work

Trying to make a migration to drop composed unique key fails without errors.

I've created a migration with php artisan make:migration and edited the code. So I have this

public function up()
{
    Schema::table('ques_trilha_itens', function (Blueprint $table) {
        $table->dropUnique('trilha_itens_trilha_id_questao_id_unique');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('ques_trilha_itens', function (Blueprint $table) {
        $table->unique(['trilha_id', 'questao_id']);
    });
}

The string 'trilha_itens_trilha_id_questao_id_unique' is the one that is displayed as the composed unique key in MySQL. So I think that string is to be used do drop the two composed keys.

But when running php artisan migrate, nothing happens, no error messages, and the migration is not executed.

I tried substitute the string in dropUnique to give the table's name as the first term ('ques_trilha_itens_trilha_id_questao_id_unique') and nothing.

Is something I'm missing?



via Chebli Mohamed

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

I never have any problem running composer install

But this morning, I ran into this error :

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


Here is my composer.json

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


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

Any hints / suggestions on this will be much appreciated !



via Chebli Mohamed

How to add a new exception handler to Laravel without disable the default one?

I'm using Sentry to keep tracking of exceptions from a Laravel application.

Sentry's docs say I should use the following code in my application bootstrap to setup the client:

$app->configureMonologUsing(function($monolog) {
    $client = new Raven_Client('your dsn');
    $handler = new Monolog\Handler\RavenHandler($client);
    $handler->setFormatter(new Monolog\Formatter\LineFormatter("%message% %context% %extra%\n"));
    $monolog->pushHandler($handler);
});

And that works fine!

The side effect is that Laravel's default exception handler, which writes the exceptions to the file at /storage/logs/laravel.log, stopped to work after adding the new exception handler.

How can I keep both handlers?



via Chebli Mohamed

Ignore field in select Laravel Eloquent

Consider these models:

Flight Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
  protected $fillable =
  [
      'userID'
  ];    

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

User Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
  protected $fillable =
  [
      'userID', 'username', 'address'
  ];    
}   

I want to skip a column when I'm trying to use eager loading. I just want to know if something like IGNORE_FIELD FUNCTION exists, so I can do something like this:

$flightUser = Flight::with(['user', function ($q)
{
    $q->ignoreField('user.address');
}])

I know I could push the address field into the hidden array inside the User Model,

protected $hidden = ['address'];

or do the $q->select('fields') and not including the address field, but my real doubt is whether laravel has a function like the one I typed above.

NOTE

I know one field isn't that big of a deal. But my question is a simplified version of my real problem.



via Chebli Mohamed

RedisStore Call to a member function get() on null

Getting this strange error when trying to run Sessions through Redis. Other drivers like database and file work fine. There is no further stack trace for me to track from where it is originating.

FatalErrorException in RedisStore.php line 54: 
Call to a member function get() on null

Please guide.



via Chebli Mohamed

Can't access to a specfic field in JSON, saying undefined in javascript

I have a project in Laravel + socket.io , I need to access a specific field in the json being broadcasted. Here is the code.

socket.js

redis.on('message', function(channel, message) {
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event,message.data); 
});

In my client socket, I have this.

socket.on("comment-channel:App\\Events\\CommentEvent", function(message){
        alert(message.data);
 });

then this will successfully, alert this.

[{
    "id": 136,
    "content": "dffsadf",
    "user_id": "1",
    "task_id": "33",
    "created_at": "2016-03-29 10:47:19",
    "user": {
        "id": 1,
        "first_name": "Hulk",
        "last_name": "Hogan",
        "username": "",
        "email": " hulhogan@yahoo.com",
        "company_id": "1",
        "role_id": "0",
        "photo": "\/assets\/apps\/img\/photos\/lvrv5VOGRskwPHvFVakp.jpeg",
        "position": "asdfsadf",
        "phone": "+75843857834",
        "city": "",
        "country": "Singapore",
        "timezone": "",
        "created_at": "2016-03-10 04:16:24",
        "updated_at": "2016-03-10 07:54:12",
        "deleted_at": null
    }
}]

Then when I try this

alert(message.data.task_id);

or

alert(message.data['task_id']);

I get 'undefined'..

How can I access, the task_id?Thank You!!!!



via Chebli Mohamed

datatable yajra laravel eloquent not working

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

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

And this is controller code.

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

And this is my view code:

<

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

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

        ]
    });
});
</script>

In controller when I use this code $candidates = \App\Suggestion::with('candidate'); According to datatable yajra documentation http://ift.tt/1ojrMaw it’s not working butt when I use with $candidates = \App\Suggestion::with('candidate')->get(); Its working butt this is not according to datatable yajra documentation. Can any one tell what is the reason behind this. Thanks

enter code here



via Chebli Mohamed

Laravel Eloquent: Return a value which is a sum() of a hasMany() with a constraint on a hasManyThrough()

I have three tables: PurchaseOrders, PurchaseOrderDetails, and Inventory.

Each PurchaseOrder has many PurchaseOrderDetails. Each Inventory item has many PurchaseOrder "through" a match of the SKU on PurchaseOrderDetails.

If I have the SKU, I want to do a sum of all PurchaseOrderDetails.OnOrder WHERE the parent PurchaseOrder has a NULL PurchaseOrder.ClosedDate.

How can I add this to my model so I can call App\Inventory::first()->OnOrder? I can get all the PurchaseOrders using:

public function OnOrder() {
    return $this->hasManyThrough(PurchaseOrder::class, PurchaseOrderDetail::class, 'LocalSKU', 'PONumber')->whereNull('PurchaseOrders.DateClosed');
}

I'm not sure how to break that down just to the PurchaseOrderDetails and sum up the OnOrder only where the SKU matches my original Inventory item.



via Chebli Mohamed

Laravel 5.2 eager loading no working

Heres what i am doing.

$question = ForumQuestion::where('link',$ques)->with('answers')->first();
$answers = $question->answers;
$answers->load('user');
//return $answers;
return view('forum.question', compact('question','answers'));

the $answers->load('user'); eager loads corresponding user of the answer.

public function user()
    {
        if ($this->user_type == 'student') {
            return $this->belongsTo(Student::class, 'user_id');
        }else{
            return $this->belongsTo(Teacher::class, 'user_id');
        }
    }

But problem is $this->user_type gets some kind of static. If my first answer has user_type = 'teacher' then in every query it assumes as it is teacher even though it changes some time to student. Why it is static? If I don't eager load it works well.



via Chebli Mohamed

Upload image to database in laravel 5 using eloquent ORM?

I have one form which contains one file upload.

Form Id is "upload_form"

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

Using javascript onclick function and ajax to pass the image to the controller.

Ajax fn:

$.ajax({
url: 'UploadImage',
data:new FormData($("#upload_form")[0]),
type: "post",
dataType:"JSON",
async:false,

success: function (data) {

console.log(data);

      }
});
}

Routes:

Routes::post('UploadImage','UploadController@Upload');

UploadController:

public function Upload()
{
 //I want to catch the image here and save in temporary file in server 
 //and then want to save the URL in database.
 //Model Name : UserData
 //Column name: ImageUrl

}



via Chebli Mohamed

pagination totoal does not return 0 if there is no record in laravel 5

I have error in pagination total.

Actually I'm getting the results but the problem is when there is no records then it throws the following error: Undefined index: inactive_users (View: /home/vagrant/Code/krankontroll/resources/views/customer/inactive.blade.php)

If I don't have any records for inactive_users array I'm getting the above error where actually it should give "No of records 0".

My controller page code is:

$customers = Customer::getCustomerPaginated(Session::get('search'),     $data['sortorder'], $data['sortby']); 
$data['customers'] = Customer::getCustomerByStatus($customers, (Input::get('page'))?Input::get('page'):1);

And my model page code is:

public static function getCustomerByStatus($customers, $pageStart=1) 
{
    $customer_status = array();
    $customer_result = array();
    $newcustomers=array();
    foreach($customers as $customer){
        $customer_status[$customer->status][] = $customer;
        if($customer->status<>2)            
        $customer_status[3][] = $customer;
        $newcustomers[] = $customer;        
    }
    $customer_result = $customer_status;
    $perPage = 10;

    // Start displaying items from this number;
    $offSet = ($pageStart * $perPage) - $perPage;

    //Slice the collection to get the items to display in current page
    $currentPageSearchResults = $customers->slice($offSet, $perPage, true)->all();
    $collection = new Collection($currentPageSearchResults);

    // Get only the items you need using array_slice
    $pagination['all'] = new LengthAwarePaginator($collection, count($newcustomers), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));

    foreach($customer_status as $status=>$customer_state)
    {
        $itemsForCurrentPage = new Collection(array_slice($customer_state, $offSet, $perPage, true));
        if($status==0)
            $label='active_users';
        else if($status==1)
            $label='inactive_users';
        else if($status==3)
            $label='nonyearly_users';
        else
            $label='yearly_users';
            $pagination[$label] = new LengthAwarePaginator($itemsForCurrentPage, count($customer_state), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
    }
    var_dump($pagination);
    exit;
    return $pagination;
}

Can anyone help me???



via Chebli Mohamed

How to properly reference the path with newly installed packages using npm in Laravel?

I've installed ReactJS and Babel using npm in my laravel project. They are found in "node_modules" folder created by npm itself. But the problem is my react code doesn't seem to work if I import using this code:

<script src="node_modules/react/react.js"></script>
<script src="node_modules/react-dom/dist/react-dom.js"></script>
<script src="node_modules/babel-core/lib/api/browser.js"></script>

Is the format of the path correct? because if I just import using this type of code for all my imports required for ReactJS:

<script src="http://ift.tt/1KXYNNU"></script>

It seems to work if I just use the internet for getting the packages.

My react code is here:

<div id="myapp"></div>
<!-- JavaScripts -->
<script type="text/babel">
    var BuckyComponent = React.createClass({
        render: function()  {
            return(
                <h2>{this.props.user} likes to eat {this.props.food}</h2>
            );
        }
    });

    React.render(
        <div>
            <BuckyComponent user="Arth" food="Bacon"/>
            <BuckyComponent user="Arth" food="Pork"/>
            <BuckyComponent user="Arth" food="Chicken"/>
        </div>,
        document.getElementById('myapp')
    );
</script>



via Chebli Mohamed

is php dying now ? with evolution of js and node

i think many people write code in php for now , with evolution in Web technologies specially js , how this will effect on php world and developers? does the beginner or nope should learn php or leave it ? i'm aware with latest modification in php7 and latest php frameworks .

i mean by this questions the experts who saw many evolution . show your point of view ,please .



via Chebli Mohamed

Laravel CORS headers not shown if user is not auth'ed

So I'm trying to create an API using Laravel, everything was going well until it came to that point where I have to connect it with Angular on another subdomain. I'm using JWT token-based auth which works fine.

I have created a CORS middleware like this:

<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Max-Age', '10000')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    }
}

Added in Kernel.php and created Route group like this:

Route::group(['middleware' => 'cors'], function () {
    Route::group(['prefix' => 'api/v1'], function() {
        Route::get('/test', 'MemberController@test');
    });  
});

I'm trying to create a call that checks if user is authenticated and returns that to angular app so the app knows what to show.

I trued like this:

public function test()
{
    if(Auth::check()){
        echo "logged in";
    } else {
        echo "nuno";
    }
}

But that returns the page without CORS headers, but if I remove "else" statement and only leave "if auth" it will return the page with headers.

Also, another problem I have is that JWT returns 400 if the token is invalid or not supplied.



via Chebli Mohamed

How to read JsonResponse in php

How to get id from here

JsonResponse {#457 ▼
  #data: "{"bill":{"id":11,"invoice_no":"9m36r9_1459170388239"}}"
  #callback: null
}

I am getting this output from this laravel code

return Response::json($response);

I tried json_decode but not worked here, a blank output is coming.

Thanks for any help.



via Chebli Mohamed

Lravel 5.0 - (This site can’t be reached The connection was reset)

I receive the following error message in "some" of my laravel webpages project:

This site can’t be reached The connection was reset. ERR_CONNECTION_RESET

Any advise please



via Chebli Mohamed

lundi 28 mars 2016

Laravel 5 redirect to controller actions

If I want to redirect to a controller's action. Must this controller action be registered in routes.php ?



via Chebli Mohamed

How to get value from column that was changed by trigger

Im having a problem. I have a before insert trigger (MySQL) on a table that changes the value of a column. But after doing the ->save() that the triggers its supposed to be done, if I do object->number (number is the column that was set on the trigger) I get nothing, while if I look on the database number was set.

I dont know why it happens if the autoincrement id is also set during the insert and that one I can get it.

Thanks for the help



via Chebli Mohamed

Laravel 5 update without id

I have a problem in Laravel 5. When I update a record in database, I get error Unknown column 'id' in 'where clause'. In the controller, I use WHERE clause to get the record I want to update. My primary key is not id and the type is bigInteger. I've tried adding protected $primaryKey in the model but it doesn't work for bigInteger. Is there any way to use my own primary key instead of using id?



via Chebli Mohamed

Laravel Eager Loading Not Working

I have the following in my index controller:

    $recipes = Recipe::with(['color', 'glass', 'garnishes', 'recipeLines.fraction','recipeLines.unitOfMeasure','recipeLines.brand','recipeLines.product','recipeLines.ingredient', 'method', 'howServed', 'equipment', 'uom', 'products'])->where('location', $this->getLocation())
        ->whereBetween('updat', array($this->getListFromDate(), $this->getListToDate()))
        ->paginate($this->getItemsPerPage());

I thought that by using with() that Laravel would change my model relationships from individual selects to joins when Recipe::all() is called but when I look at DB::connection('remoteRecipes')->getQueryLog() I see 50 select queries instead of one.



via Chebli Mohamed

How to authenticate without database in Laravel 5.2?

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

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

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

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



via Chebli Mohamed

Running phpunit as a Laravel 5 Queued Job, endless processed loop

I'm trying to automate some of my phpunit testing with a Laravel 5 Queues Job using Process in Symfony (and exec and a few other methods).

I am able to execute phpunit just fine but doing so throws the Queue into an infinite loop of:

[2016-03-28 18:04:58] Processed: Illuminate\Queue\CallQueuedHandler@call
[2016-03-28 18:04:59] Processed: Illuminate\Queue\CallQueuedHandler@call
[2016-03-28 18:04:59] Processed: Illuminate\Queue\CallQueuedHandler@call
[2016-03-28 18:04:59] Processed: Illuminate\Queue\CallQueuedHandler@call
[2016-03-28 18:05:00] Processed: Illuminate\Queue\CallQueuedHandler@call

I've tried several ways to execute phpunit, all seem to cause this issue. Doing a Process on a ls -al or whoami work just fine.

Any help would be appreciated.

namespace App\Jobs;

use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Symfony\Component\Process\Process;


class ProcessPHPUnit extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

      $process = new Process('vendor/bin/phpunit', base_path());
      $process->run();

    }

}



via Chebli Mohamed

FatalErrorException: Input string is too long

I've started to build a new Laravel 5 app. I need a site message feature in my app, so I created one. But now when I'm trying to add messages into stack, I'll get the following error:

FatalErrorException in ExceptionHandler.php line 412: Input string is too long

Apache error log says:

Mon Mar 28 20:25:40.310761 2016] [fcgid:warn] [pid 2075:tid 3028430848] [client 127.0.0.1:56643] mod_fcgid: stderr: PHP Fatal error: Input string is too long in /Users/xxx/Development/Laravel/myapp/vendor/symfony/debug/ExceptionHandler.php on line 412, referer: http://app.dev/page/new

I call Message::set method in my controller:

Message::set('Page created');

And the Message class contains:

<?php

namespace App\Models;

use Session;

class Message {

    const MESSAGE_INFO      = 0x1;
    const MESSAGE_WARNING   = 0x2;
    const MESSAGE_ERROR     = 0x3;

    public static function set($message, $type = MESSAGE_INFO) {
        $messages = self::get(false);
        $messages[$type][] = $message;

        Session::put('app.messages', $messages);
    }

    public static function get($flush = true) {
        $default = [ self::MESSAGE_INFO => [], self::MESSAGE_WARNING => [], self::MESSAGE_ERROR => []];

        if($flush) Session::pull('app.messages', $default);
        return Session::get('app.messages', $default);
    }

    public static function isAny() {
        $messages = self::get(false);

        foreach($messages AS $store) if(!empty($store)) return true;

        return false;
    }

}

I'm so lost with this. Can someone help me with this?



via Chebli Mohamed