mardi 28 février 2017

Call to undefined function bzdecompress PHP

I have an Ubuntu 16.04 server with PHP7 + nginx running. I already have a project in PHP Laravel 5.1 running in my local enviroment (Windows with Xampp) and everything is running great. I have a PHP script that uses the function bzdecompress of Bzip2 but then, in the server just crash and show this message:

Call to undefined function App\Http\Controllers\bzdecompress() 

I don't see instructions of how install this library (if needed) or how to load it or check at least that is loaded. Thank you very much!



via Chebli Mohamed

how i display image when i uplaod it using this code in laravel 5.1

I store imagepath in database like this http://localhost/shopping/public/src/img/46.png

my code :
     $imageName = $product->id . '.' . 
            $request->file('image')->getClientOriginalExtension();
            $request->file('image')->move(public_path('src/img/'.$imageName));
            $product->imagePath=$imagepath;
            $product->save();



via Chebli Mohamed

unable to create directory in laravel 5.1 when upload image?

Error : Unable to create the "http:/localhost/shopping/public/src/img/" directory

my code :
$imageName = $product->id . '.' . 
        $request->file('image')->getClientOriginalExtension();
                $request->file('image')->move(
        url().'/public/src/img/', $imageName
        );



via Chebli Mohamed

ModelNotFoundException in Builder.php line 129: No query results for model [Fully\Models\Package]

I am having trouble calling a controller and routing.

My route:

Route::group(array('prefix' => LaravelLocalization::getCurrentLocale()), function () {

Route::group(array('prefix' => '/admin',
                   'namespace' => 'Admin',
                   'middleware' => ['before', 'sentinel.auth', 'sentinel.permission'] ), function () { // auth = stop directly accessing admin


//      PACKAGE

    Route::resource('package', 'PackageController', array('before' => 'hasAccess:package'));
    Route::get('package/{id}/delete', array('as' => 'admin.package.delete',
        'uses' => 'PackageController@confirmDestroy', ))->where('id', '\d+');

My controller:

class PackageController extends Controller
{
protected $package;
protected $packageCategory;
protected $activity;
protected $destination;
protected $perPage;

public function __construct(PackageInterface $package, PackageCategoryInterface $packageCategory, ActivityInterface $activity, DestinationInterface $destination)
{
    //codes

}

public function index()
{
    //index codes
}

public function suggested()
{

    return view('backend.package.suggested');
}

My menu.blade.php

<a href=""> View all packages</a>
<a href=""> Add new package</a>   
<a href=""> Suggested package</a>

What I am trying to achieve: In the controller i created a new function suggested, which should return a view when the link is clicked in the menu.blade.php. However when I click on the link the url in the browser shows localhost/en/admin/package/suggested but at no veil throws an exception error as described above. I want to know if i can create a new function in the controller and call it or not? How do I make this run ?



via Chebli Mohamed

lundi 27 février 2017

Sending mail error in laravel 5.1

i am trying to send email in laravel 5.1 but it give me folloiwng error.

Swift_TransportException in AbstractSmtpTransport.php line 383: Expected response code 250 but got code "530", with message "530-5.5.1 Authentication Required. Learn more at 530 5.5.1 http://ift.tt/2dX5gUh o1sm938569pgf.63 - gsmtp "

i have tried 2-Step verification and http://ift.tt/1oME4BN also trun on. But still getting the error

anyone can help me for that?



via Chebli Mohamed

Query if a relationship exists with conditions in Laravel

I have a model Foo that contains a hasMany relationship to Bar.

I have a query similar to the following:

$r = Foo::with(['bar' => function($query) {
    $query->where('someProp', '=', 10);
})->get()

However, I want to only return the Foo object if item has a Bar object that satisfies the query.

I'm aware that you can do something like this:

$r = Foo::has('bar')
    ->with(['bar' => function($query) {
        $query->where('someProp', '=', 10);
    })->get();

But that checks if any bar items exists. Not if a bar item exists with someProp = 10

How can I do this?



via Chebli Mohamed

Run a raw SQL statement to rename an index in a Laravel migration

I want to run the following raw SQL statement in a Laravel migration:

RENAME INDEX offer_venue_id_fk_idx TO offers_venue_id_index

How can I do this?



via Chebli Mohamed

Rename an index in Laravel 5

I want to rename an index in Laravel 5.

In a previous migration a column was created for table named a like so:

$table->unsignedInteger('foo')->index('blah');

I want to rename the index so that it uses the default Laravel notation.

i.e. I want to rename the blah index to a_blah.

I know how to rename a normal column, like so:

$table->renameColumn('from', 'to');

But the documentation does not mention how to rename indexes.

How can I do this?



via Chebli Mohamed

jeudi 23 février 2017

Unable to add foreign key in Laravel

In a laravel migration file I have the following code:

   Schema::table('stripe_customers', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
   });

'user_id' is an existing unsigned integer column in the table 'stripe_customers'.

'id' is a primary key column in 'users'.

However when I run the migrate command I get the following error message:

  [Illuminate\Database\QueryException]                                                                      
  SQLSTATE[HY000]: General error: 1005 Can't create table 'thedealerapp.#sql-47a_78859' (errno: 150) (SQL:  
   alter table `stripe_customers` add constraint stripe_customers_user_id_foreign foreign key (`user_id`)   
  references `users` (`id`))                                                                                

  [PDOException]                                                                                      
  SQLSTATE[HY000]: General error: 1005 Can't create table 'thedealerapp.#sql-47a_78859' (errno: 150)  

Why is this happening?



via Chebli Mohamed

Scrapped data contains jquery conflicting with angular app

The Scenario-:

I am scrapping a website go display a form inside my angular application. I am using php to scrap this data, Which send me the html as a string through a rest api.

Inside my angular application i use $sce.trustAsHtml(scrappedView) to compile the string to html and display the actual form on my application dashboard.

Now the problem-:

The page which is scrapped from another website contains jQuery 1.11.0, My application uses angular 1.4.

When the view is loaded inside my app no functionality/operation inside the form work. However on doing a POC inside a jquery application the for works perfectly fine.

My guess is that the jQuery and angular are conflicting due to the same Identifier($). Is their a way where i can avoid this conflict through angularjs, or any workarounds at all.



via Chebli Mohamed

NotFoundHttpException in RouteCollection.php line 161 in laravel

i just wirte code in routes.php as below

 Route::get('/', function () {
    return 'Hello World';
});
Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});
 Route::post('foo/bar', function () {
    return 'Hello World';
});

Route::put('foo/bar', function () {
 //
});

Route::delete('foo/bar', function () {
   //
 });

and it gererate error:... Sorry, the page you are looking for could not be found.NotFoundHttpException in RouteCollection.php line 161:1)in RouteCollection.php line 161.2)at RouteCollection->match(object(Request)) in Router.php line 533 at Router->findRoute(object(Request)) in Router.php line 512. AND OTHER ERROR



via Chebli Mohamed

Laravel: Mail send not working

If i do this in Laravel 5.1

Route::get('test_email', function(){
  Mail::raw(
        "",
        function ($mail) {
            $mail->from('info@test.com');
            $mail->to('test@test.com', 'test');
         }
   );
});

The email is sent to MAIL_TO_ADDRESS set into .env. It ignore the to value. Why?



via Chebli Mohamed

mardi 21 février 2017

How to effectively reuse a form that utilizes a date field in Laravel 5.1

I am working with a form that is being used in both the create and edit views. I have a date field and I want to set the default value depending on the view it is being used in. In the case of the create view I want to have the default set to today, and in the edit view I want to display the value stored in the database. Here is my code:

{!! Form::date('calibration_due_date', isset($tool->calibration_due_date)?$tool->calibration_due_date->format('Y-m-d'): Carbon\Carbon::now()->toDateString(), array('class' => 'form-control', 'required')) !!}

The problem is on the create view, it is not displaying todays date as expected, it is actually displaying a date from one of several items stored in the database...very randomly, it's not the first record, or the last, but record number 7. I have dumped the $tool variable and have confirmed that it is not set (I get an error confirming this) and when I change the code to this:

{!! Form::date('calibration_due_date', Carbon\Carbon::now()->toDateString(), array('class' => 'form-control', 'required')) !!}

I get today's date as expected. As you can see I am using the Carbon plugin as well as the HTML collective.



via Chebli Mohamed

SQLSTATE[HY000]: General error: 1364 Field 'category' doesn't have a default value (SQL: insert into `posts`

i recently start with laravel i try to create record by add values and but i get this error

QueryException in Connection.php line 647:
SQLSTATE[HY000]: General error: 1364 Field 'category' doesn't have a 
default value (SQL: insert into `posts` (`title`, `content`, 
`updated_at`, `created_at`) values (tip, tip, 2017-02-21 10:25:28, 
2017-02-21 10:25:28))

can anyone tell me where is my error



via Chebli Mohamed

lundi 20 février 2017

Laravel SQL query returning wrong results

I have this SQL Query with Laravel Query builder

$this->candidate->select('candidates.*', 'candidates.id as candidate_id', 'mj.interviewScheduledDate')
            ->join('candidates_positions', 'candidates_positions.candidate_id', '=', 'candidates.id')
            ->leftJoin(DB::raw("(SELECT mat1.* FROM matches AS mat1
                                    JOIN (SELECT candidate_id, MAX(id) AS id FROM matches GROUP BY candidate_id) 
                                    AS mat2 ON mat1.candidate_id = mat2.candidate_id AND mat1.id = mat2.id)
                                    AS mj"), function ($join) {
                $join->on("candidates.id", "=", "mj.candidate_id");
            })
            ->where(function ($query) {
                $query->where("mj.stage", "<", "4")
                    ->whereNull('mj.stage', "or");
            })
            ->groupBy('candidates.id')

            ->paginate(Config::get('match.pagination'));

This returns wrong results, where the Generated query from same Query builder returns correct results. $candidate->toSql() returns below query. even tried removing group by statements. It didn't help

SELECT
      `candidates`.*,
      `candidates`.`id` AS `candidate_id`,
      `mj`.`interviewScheduledDate`
    FROM `candidates`
      INNER JOIN `candidates_positions` ON `candidates_positions`.`candidate_id` = `candidates`.`id`
      LEFT JOIN (SELECT mat1.*
                 FROM matches AS mat1
                   JOIN (SELECT
                           candidate_id,
                           MAX(id) AS id
                         FROM matches
                         GROUP BY candidate_id)
                     AS mat2 ON mat1.candidate_id = mat2.candidate_id AND mat1.id = mat2.id)
        AS mj ON `candidates`.`id` = `mj`.`candidate_id`
    WHERE (`mj`.`stage` < ? OR `mj`.`stage` IS NULL)
    GROUP BY `candidates`.`id`
    LIMIT 10 OFFSET 0

Correct Results enter image description here

Laravel Returned Results enter image description here



via Chebli Mohamed

laravel controller update not working

i am using RESTful Resource Controllers and update function is not working properly.

if generate a link like this and nothing happens http://localhost:8000/medication/3?_token=Sv0mblJUcWppsO6roWiXOzZzcFOqlgMBIzJoy3HW&medicine=a&dosage=a&howOften=aaa&forWhat=a&doctor=a&vaccination=a&shots=a

my view code(for testing only) is

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                </button>
                <h4 class="modal-title custom_align" id="Heading">Edit Your Medication</h4>
            </div>

            <form role="form" action="/medication/3" method="PUT" class="f1">
            
            <div class="modal-body">

                <div class="form-group">
                    <input type="text" name="medicine" class="form-control" placeholder="Medicine">
                </div>
                <div class="form-group">
                    <input type="text" name="dosage" class="form-control" placeholder="Dosage">
                </div>
                <div class="form-group">
                    <input type="text" name="howOften" class="form-control" placeholder="How often do I take it">
                </div>
                <div class="form-group">
                    <input type="text" name="forWhat" class="form-control" placeholder="what it is for?">
                </div>
                <div class="form-group">
                    <input type="text" name="doctor" class="form-control" placeholder="Prescribing Doctor">
                </div>
                <div class="form-group">
                    <input type="text" name="vaccination" class="form-control" placeholder="Vaccination">
                </div>
                <div class="form-group">
                    <input type="text" name="shots" class="form-control" placeholder="Shots">
                </div>
            </div>

            <div class="modal-footer ">
                <button type="submit" class="btn btn-success btn-lg btn-update" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
            </div>
            </form>

        </div><!-- /.modal-content --> 
    </div><!-- /.modal-dialog -->

</div>

Controller code is

public function update(Request $request, $id)
{
    $row = $id;

    $data = array('medicine' => $request->medicine,
                    'dosage' => $request->dosage,
                    'howOften' => $request->howOften,
                    'forWhat' => $request->forWhat,
                    'doctor' => $request->doctor,
                    'vaccination' => $request->vaccination,
                    'shots' => $request->shots);

    $ex = ProfileInformation::insertInformation($row, $this->user, $this->TABLE_NAME, $data);
    if($ex){//executed properly
        return redirect('/medication');
    } else {
        return redirect('/customer');
    }

}

I'm not using that standard id primary key of laravel but still want to stick with resource controller. i don't understand why nothing is happening. if there is a query error then it should atleast go to my redirect code.



via Chebli Mohamed

Uploading a video with URL Laravel 5.1

i have a form where i add an image and a video but what i wanna try is uploading it to the DB with a youtube URL, and then watch it on the web app. I am also worried if i send this it uploads me twice the image ?

This is my store function (saving it through file) video and image.

$data = $request->all();
        $image = $request->file('image');
        $video = $request->file('video');

        if($image)
        {
            $data['image'] = $image->getClientOriginalName();
        }

        $company_outstand = new CompanyOutstand($request->all());
        $company_outstand->fill($request->all());
        $company_outstand->image = $data['image'];
        $company_outstand->save();

        if($company_outstand->image){
            $path = public_path() . '/image/company_outstand/' . $company_outstand->id;
            if( ! File::exists($path)) {
                File::makeDirectory($path, 0775, true, true);
            }
            $imageName = $company_outstand->image;
            $request->file('image')->move($path, $imageName);

        }

        if($video)
        {
            $data['video'] = $video->getClientOriginalName();
        }

        $company_outstand = new CompanyOutstand($request->all());
        $company_outstand->fill($request->all());
        $company_outstand->video = $data['video'];
        $company_outstand->save();

        if($company_outstand->video){
            $path = public_path() . '/video/company_outstand/' . $company_outstand->id;
            if( ! File::exists($path)) {
                File::makeDirectory($path, 0775, true, true);
            }
            $videoName = $company_outstand->video;
            $request->file('video')->move($path, $videoName);

        }

My form view for edit and create:

<div class="form-group">
    {!! Form::label('text', 'Texto') !!}
    {!! Form::text('text', null, ['class' => 'form-control', 'placeholder' => 'Texto', 'required']) !!}
</div>
<div class="form-group">
    {!! Form::label('order', 'Orden') !!}
    {!! Form::text('order', null, ['class' => 'form-control', 'placeholder' => 'Orden', 'required']) !!}
</div>
<div class="form-group">
    {!! Form::label('Imagen ') !!}
</div>
<div class="form-group">
    @if( ! isset($company_outstand->image))
        <div class="col-sm-6">
            {!! Form::file('image', null, array('class' => 'image')) !!}
        </div>
    @else
        <div class="col-sm-6">
            <img class="thumbnail" src="/image/company_outstand//" width="200" height="100">
            {!! Form::text('image', $company_outstand->image, array('class' => 'image hidden')) !!}
            {!! Form::file('image', null, array('class' => 'image', 'form-control')) !!}
        </div>
    @endif
</div>
<div class="form-group">
    @if( ! isset($company_outstand->video))
        <div class="col-sm-6">
            {!! Form::file('video', null, array('class' => 'video')) !!}
        </div>
    @else
        <div class="col-sm-6">
            <img class="thumbnail" src="/video/company_outstand//" width="200" height="100">
            {!! Form::text('video', $company_outstand->video, array('class' => 'video hidden')) !!}
            {!! Form::file('video', null, array('class' => 'video', 'form-control')) !!}
        </div>
    @endif
</div>
<div class="form-group">
    {!! Form::submit('Guardar', ['class' => 'btn btn-primary']) !!}
</div>



via Chebli Mohamed

dimanche 19 février 2017

cleaning framework/sessions folder after every request

As I found my framework/sessions folder becoming bulkier. Because laravel creating session files on every request. I am using laravel 5.1 . I don't want sessions on all requests. or I want to delete framework/sessions files automatically after each request is completed. I tried session->flash. But files are still there.

a:3:{s:6:"_token";s:40:"AXqkhlwBwbJGcfG3l8ZVzN991HQnYwfioQUd38Mz";s:9:"_sf2_meta";a:3:{s:1:"u";i:1487576780;s:1:"c";i:1487576780;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}



via Chebli Mohamed

When I have to use service provider and service container in laravel?

I don't know what is the importance of service provider and service container in the laravel. and how to use them in my applications?



via Chebli Mohamed

samedi 18 février 2017

Resources under 'public' is not accessible from sub-domain

I have a Laravel 5.2 setup accessible from multiple sub-domains but using different database. i.e.

Domain : sample.com,      DB : sample-db
Domain : test.sample.com  DB : test-db

to change DB connection based on domain, I setup a middleware. Which is perfectly working.

Now, sample.com was previously setup and is working perfectly fine and able to access all resources under public directory. but test.sample.com is not able to access any resources from public directory.



via Chebli Mohamed

Class 'App\Http\Controllers\Image' not found - HomeController.php line 53 - Laravel 5.1

This is the error i get when i submit my create code. Looks like my public_path is not being respected by the store function, so it looks for a controller called Image... Hope you guys can help me find out the error.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Flash;
use File;
use App\Home;

class HomeController extends Controller
{

    public function store(Request $request)
    {

        $data = $request->all();
        $image = $request->file('image');

        if($image)
        {
            $data['image'] = $image->getClientOriginalName();
        }

        $home = new Image($request->all());
        $home->fill($request->all());
        $home->image = $data['image'];
        $home->save();

        if($home->image){
            $path = public_path() . '/image/homes/' . $home->id;
            if( ! File::exists($path)) {
                File::makeDirectory($path, 0775, true, true);
            }
            $imageName = $home->image;
            $request->file('image')->move($path, $imageName);

        }
        Flash::success("Se ha agregado un nuevo slider con exito");
        return redirect()->route('home.index');
    }
}

My public path is -> public/image/homes

Create function:

@section('main-content')
<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3>Crear slider</h3>
                </div>

                <div class="panel-body">
                    {!! Form::open(['route' => 'home.store', 'method' => 'POST', 'files' => true]) !!}

                        @include('home.form')

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

Actual form:

<div class="form-group">
    {!! Form::label('text', 'Texto') !!}
    {!! Form::text('text', null, ['class' => 'form-control', 'placeholder' => 'Texto', 'required']) !!}
</div>
<div class="form-group">
    {!! Form::label('order', 'Orden') !!}
    {!! Form::text('order', null, ['class' => 'form-control', 'placeholder' => 'Orden', 'required']) !!}
</div>
<div class="form-group">
    {!! Form::label('Imagen ') !!}
</div>
<div class="form-group">
    @if( ! isset($home->image))
        <div class="col-sm-6">
            {!! Form::file('image', null, array('class' => 'image')) !!}
        </div>
    @else
        <div class="col-sm-6">
            <img class="thumbnail" src="/image/stores//" width="200" height="100">
            {!! Form::text('image', $home->image, array('class' => 'image hidden')) !!}
            {!! Form::file('image', null, array('class' => 'image', 'form-control')) !!}
        </div>
    @endif
</div>
<div class="form-group">
    {!! Form::submit('Guardar', ['class' => 'btn btn-primary']) !!}
</div>



via Chebli Mohamed

Deep linked values for a page in Laravel database models

A page has multiple elements and they are linked using the page_to_elements table. Each element has multiple element_fields and are linked using the element_to_element_fields. Each element_field has a type and are linked using the element_to_element_fields table. The values of each element_field within the element has a value (eitehr in value_char, value_text or value_num) that is stored in the element_values table.

Below is how the database structure is:

pages:
id|name

elements:
id|name

element_fields_types (sql_type can be char, text or num):
id|name|sql_type

element_fields (names can be title, intro, content, link, number, etc etc):
id:element_field_type_id|name

element_to_element_fields:
id|element_id|element_field_id

page_to_elements:
id|page_id|element_id

element_values:
id|page_id|element_id|page_to_element_id|element_field_id|value_char|value_text|value_num

What I am looking for is a good hasManyToMany solution to get all values when I request a page id. I now have multiple loops and array creations to get a structure like this (where the values are from the correct column name based on what was set in the element_fields):

$page = array(
    'elements' => array(
        [0] => array(
            'element_name_here' => array(
                'fields' => array(
                    [0] => array(
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value'
                    ),
                    [1] => array(
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value'
                    ),
                    [2] => array(
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value'
                    ),
                )
            )
        ),
        [1] => array(
            'element_name_here' => array(
                'fields' => array(
                    [0] => array(
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value'
                    ),
                    [1] => array(
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value'
                    ),
                    [2] => array(
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value',
                        'field_name_here' => 'Field value'
                    ),
                )
            )
        ),

    )
);

So I need something like below to produce above array:

$page = Page::find($id);
print_r($page->getValues->toArray());

I have some experience with belongsToMany or hasManyToMany, but never this deep.

Any help would be much appreciated.



via Chebli Mohamed

belongsToMany on not primary field

For example i have 4 tables:
buildings
id, title, ...
rooms
id, building_id, title, ...
companies
id, title, ...
companies_to_buildings
company_id, building_id

and i want to get companies from the room model.
From building model i can do something like

class Building extends Model
{
    public function companies(){
        return $this->belongsToMany('App\Company', 'company_building');
    }
}

or

class Building extends Model
{
    public function companies(){
        return $this->belongsToMany('App\Company', 'company_building', 'building_id', 'company_id');
    }
}

but if i do this in room model, it would not work. it will try to find rows in companies_to_buildings table where companies_to_buildings.building_id=room.id. how can i get companies from the room model?



via Chebli Mohamed

vendredi 17 février 2017

laravel pass 2 dimensional array in view

i want to pas an array in the view view

controller code is

$data['medications'] = array('medicine' => 'meds',
                             'dosage' => 'dosage');

return view('medications.index', $data);

i cant retrieve it in view using for each

@foreach($medications as $data)
  //this results in "Trying to get property of non-object"
  //this results in "Illegal string offset 'medicine'"
@endforeach



via Chebli Mohamed

How do I match an array against Eloquent-Relationship via logical AND? Laravel 5.1

Imagine there is a Table with some posts which hasMany(tags), which in reverse belongsTo(posts). The tags-Table contains

id, post_id, tag
 1,      42, Foo
 2,      42, Bar
 3,      53, Bar
 4,      53, Baz
 5,      64, Bar

Then there is an array

$array = ['Bar','Baz','Qux']

How do I get the posts, for which all tags are in $array?
In this example, the result should contain the posts [53,64], but not 42, because Foo is not in $array.

In other words: how do I make a logical AND through Eloquent? A logical OR is no problem, e.g.:

Posts::with('tags')
->whereHas('tags', function($q) {
    $q->whereIn('tag', $array);
})
->get();

But this also returns post 42, as it has the tag Bar.



via Chebli Mohamed

How can I use php-FFMpeg in laravel 5.1 to convert uploaded GIF image to video format automatically?

I have installed php-ffmpeg in my localhost Laravel setup, but I need help on how to use ffmpeg with Laravel 5.1.

I need this to convert gif image into .mp4 video format automatically. (Example: Gif uploaded in 9gag.com)

Please also suggest if there is any alternative solution to the requirement.



via Chebli Mohamed

Request not showing all data in array

I am using laravel 5.1 and I am in the middle of the problem.

enter image description here

<script type="text/javascript">
var counter=0;
$(document.body).on('click',".popCategory",function(){

var appendcategory="";
if(counter<100){
counter++;
 appendcategory+='<input type="text" class="form-control"   name="category['+counter+']" placeholder="Category" value="545454" />';
$('.category_append').append(appendcategory);
 }
 })
</script>

As shown in image I have appended the category with the help of jquery and when I submit the form I get the result as shown in below: enter image description here

The problem is that I only get one value when I have submitted three value of category . you can see the inspect element below:

enter image description here

Can someone help me?



via Chebli Mohamed

mercredi 15 février 2017

Laravel date_format rule not working

I am trying to use a datetime format rule for my input like this:

H:i:s

My model rule looks like this:

    public static $rules = [
        ...
        'start'    => [
            'min:8',
            'date_format:"H:i:s"',
        ],
    ];

And in my controller I call it like this:

        $validator = Validator::make($request->all(), Product::$rules);

        if($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator);
        }

If I dd($validator) I get following:

  #rules: array:7 [▼
     ...
    "start" => array:2 [▼
      0 => "min:8"
      1 => "date_format:"H:i:s""
    ]
  ]

I insert 00:h:01 into the input field but I did not get any error message.



via Chebli Mohamed

Laravel Database charset and collation

In Laravel, Everytime, while running the website,

"set names 'utf8' collate 'utf8_unicode_ci'"

is executing.

How can I avoid this ? Instead of doing this in the code. We have configured in the database itself. How can I remove charset and collation in database configuration ?

> config/database.php
> 
> 'database' => [
>     'driver'    => 'mysql',
>     'host'      => env('DB_HOST', 'localhost'),
>     'port'      => env('DB_PORT'),
>     'database'  => env('DATABASE'),
>     'username'  => env('DB_USERNAME', 'forge'),
>     'password'  => env('DB_PASSWORD', ''),
>     'charset'   => 'utf8', // Need to remove or make ''
>     'collation' => 'utf8_unicode_ci', // Need to remove or make ''
>     'prefix'    => env('DB_PREFIX', ''),
>     'strict'    => false, ],



via Chebli Mohamed

mardi 14 février 2017

url always return http://localhost

I have below code in notification file

url('/#/account-activation', $this->token)

which returns http://localhost/#/account-activation/79f6a3fa2357ee789b8c

here problem is: my xampp server localhost is set as localhost:85 but i always get the url without port.

In order to fix that, I set the APP_URL=http://localhost:85 in .env file and same thing was done in config/app.php

But still same issue. Please suggest



via Chebli Mohamed

Laravel 5: Alternative for Eloquent's 'orWhere' method for querying collections

So I have a collection of products ($this->products) which I'm getting as a result of a Model query and I want to filter it by some of its attributes values. The problem is that Laravel doesn't have a method like orWhere for collections like Eloquent does for querying models. Also I want to use the LIKE %{$searching_for}% wildcard and I'm not sure how to use it (if possible at all) to filter my collection.

This is the code I tried to filter my collection with which obviously throws an Exception that orWhere method doesn't exist:

$products = $this->products
        ->where("field1", "LIKE %{$searching_for}%")
        ->orWhere("field2", "LIKE", "%{$searching_for}%")
        ->orWhere("field3", "LIKE", "%{$searching_for}%")
        ->orWhere("field4", "LIKE", "%{$searching_for}%");

I'd like to query the Model directly but I just store the $products collection in Session so I can use it anywhere I need, I don't want to query the database too often so I'm searching for a solution to somehow filter the existing collection.



via Chebli Mohamed

Issue in set monolog in Laravel

I use this for logging . I tried to configure log rotation on but I'm stuck. I know how to do this with Laravel, I'm trying to create my own rotating log file in Laravel using Monolog, however, the file rotation is not working and I don't know why.

/* controller file */

use Illuminate\Http\Request;
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;

public function getSheduled(){     
    $log = new Logger('getSheduled');
    $log->pushHandler(new RotatingFileHandler(storage_path().'/logs/cron_log/custom_log.log',2, Logger::INFO)); 
    $log->info(json_encode($followup_shedule_data));

}

It seemed pretty straightforward to me, but it's simply not working. The log files are being generated correctly but when When I see their output it give me like this:

/*text file */

    [2017-02-14 12:24:46] getSheduled.INFO: [] [] []

I don't want last 2 array from array.Please answer



via Chebli Mohamed

Laravel 5.* - Collections - Recursive merge / Merge in depth

Is it possible to recursively merge two eloquent collections in Laravel 5.* when they themselves have child collections?

For example if i had two collections like this:

$collection1 = collect([
   'sub1' => collect(['foo','bar']),
   'sub2' => collect(['umm','what'])
]);

$collection2 = collect([
   'sub1' => collect(['hello','world']),
   'sub2' => collect(['nice','day'])
]);

And then i were to then to do something similar to the merge function:

$collection3 = $collection1->merge($collection2, 'recursive');

Is it possible to get an output the equivalent to this?

$collection3 = collect([
   'sub1' => collect(['hello','world','foo','bar']),
   'sub2' => collect(['nice','day','umm','what'])
]);

I can write a custom function to do this but i am interested to see if Laravel has something out of the box to handle it!



via Chebli Mohamed

Unexpected Case Sensitive Issue Laravel

i am working on a Laravel project and started receiving some unexpected issues.

I am running a script through cron job, and there is an If condition in the script:

if($bride->photographer == 'yes'){
    // Code goes here
}

the problem is...
till yesterday everything was working fine, but from today it stopped working, when i started debugging then i came to know that it is not working for the values = "Yes", means which starts with capital Y, that means now it has started behaving as Case Sensitive.

But i am wondering what has been changed in one day. If it is not working now then why was it working before?

May be there is something which i am not aware of, please let me know what's wrong with that.

Thanks.



via Chebli Mohamed

retrieve single row in LARAVELusing eloquent

i am using laravel 5.1 and want to retrieve a single row in the database then manipulate it after.

my current code is

$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();

foreach($profiles as $profile ){
$data['address'] = $profile->address;
}

why cant i do it like this?

$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();

$data['address'] = $profiles->address;

am i using a wrong function or something? thanks in advance.



via Chebli Mohamed

lundi 13 février 2017

Eloquent query in not returning object that I know exists?

I am running the following Eloquent query in a function, and nothing is being returned.

$foo = Foo::whereId(idHere)->first();       
Log::info($job);

Null is being returned, and I know that the object exists, I can access it in other places (controllers, views, etc.) Am I not including something that needs to be included in order to make Eloquent queries work? Here is what the include looks like at the top of this file:

use App\Core\Models\Foo;
use Log;
use Carbon\Carbon;
use BAR\Http\Controller; //CUSTOM CONTROLLER THING, NOT THE PROBLEM



via Chebli Mohamed

dimanche 12 février 2017

TokenGuard class always need api_token

I am using AngularJs and Laravel 5.3

In the default guard, I changed the web guard to api. Finally it looks like below.

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

when i send the request using username and password from Angular Js....I always get invalid credentials because..

TokenGuard class has a method called validate which expects api_token value but I am on the login page.

I am assuming that in order to get the token, I need $this->guard(web) in login method?

Is it correct approach or Am I missing something?



via Chebli Mohamed

samedi 11 février 2017

Laravel 5.1 - Unable to delete file

I have the following code:

Storage::delete(public_path($file->path));

But I get error:

File not found at path: C:\wamp\www\laravel\acme\public\img/logos/1486846424_acme.gif

When I check the directory I can see the file is there so why I'm I unable to delete it. I've tried the php unlink function too and I get same error.



via Chebli Mohamed

Merge eloquent collection with query in Laravel?

Is it possible to merge an eloquent collection with a query builder?

In this example, I've got 3 tables. An images table, a tag table, and an images_tag table. I also have eloquent relationships in both the Images and Tag models.

Tag.php:

class Tag extends Model {

 protected $table = 'tags';

 public $timestamps = false;

 protected $fillable = [
    'tagname',
 ];

 public function Images() {
    return $this->belongsToMany('CommendMe\Models\Images');
 }  

}

Images.php:

public function tags() {
    return $this->belongsToMany('CommendMe\Models\Tag');
}   

What I'd like to do is something like this:

$tag = Tag::where('tagname', $query)->first();

$imagesWithTag = $tag->images;

$imagesWithoutTag = Images::where('title', 'LIKE', "%{$query}%");

$images = $imagesWithTag + $imagesWithoutTag
   ->whereIn('mature', [0, $mature])
   ->where('created_at', '>=', Carbon::now()->subHours($withinHours))
   ->orderBy($orderByString, 'desc')
   ->Paginate(50);     

Essentially just taking the query (which returns an array from the images table), and the collection (which also returns an array from the images table), combine and sort the results.

Is this possible?



via Chebli Mohamed

Laravel 5.1 - Return First Error From FormRequest Validation

I have the following form request:

class FileRequest extends Request
{

   public function authorize()
   {
      return true;
   }

   public function rules()
   {

      $rules = [];

      if($this->file_type == 'image')
         $rules['file'] = 'required|image|mimes:jpg,jpeg,gif|max:244|image_size:>=360,>=180';
    else
         $rules['file'] = 'required|mimes:doc,pdf,docx,txt,rtf|max:1000';

      return $rules;

   }

   public function messages()
   {
      $messages = [
        'file.image_size' => 'The image size is incorrect.'
      ];

      return $messages;
   }

   public function response(array $errors)
   {
        $content = "<textarea data-type=\"application/json\">{\"ok\": false, \"message\": \"" . $errors[0] . "\" }</textarea>";
         return response($content);

    }



}

How do i return the first error from the errors array.

When I manually create a validator I'm able to do the following: $validator->errors()->first() but this doesn't work when using a FormRequest class. Doing errors[0] simply gives me an offset exception error.

I'm using an iframe submit which is why I need to return the response as above.

Any help appreciated.



via Chebli Mohamed

vendredi 10 février 2017

Validating fields conditionally using Laravel

I have the following validation rules for Laravel:

return [
    'offer_type' => 'required|in:permanent,temporary',
    'start_date' => 'required_if:offerType,temporary|date_format:d/m/Y',
    'end_date' => 'required_if:offerType,temporary|date_format:d/m/Y|after:start_date',
];

Basically, if the offer_type is temporary, a start_date and end_date is required and must follow the d/M/Y format. Also, the end_date must be after the start_date.

If the offerType is permanent, there is no need to validate start_date or end_date as they are not even used.

The issue I have is that it if the user sends data like the following:

  • offerType: permanent
  • startDate: foo
  • endDate: bar

Then Laravel will raise a validation error, even though start_date and end_date does not need to be validated, as the offer type is permanent.

How can I make Laravel only validate start_date and end_date if offer_type is temporary.



via Chebli Mohamed

jeudi 9 février 2017

Get certain attributes from an Eloquent model when converting to an Array in Laravel

I have a model (e.g. User).

I can easily convert it to an array like so:

$user->toArray()

However, this gives all the attributes. I only want attributes x, y and z.

We can use the hidden and visible attributes of the model to hide/show values, as described here: http://ift.tt/2lpnNN8

However, I don't want to use this because this is more of a one off situation. Not a regular occurrence.

The pluck method is ideal, but this only applies to Collections, not Models.



via Chebli Mohamed

Avoid Eloquent model event from being triggered multiple/ infinite times using Laravel

I have the following code:

AppServiceProvider:

User::saved(function (User $user) {
    return $user->modifiedEvent();
});

User::deleted(function (User $user)   
    return $user->modifiedEvent();
});

In my User model I have:

    public function modifiedEvent()
    {
        $stage = $this->isDirty('terms_and_conditions') 
             && $this->terms_and_conditions !== null ? 'completed' : 'incomplete';
        $this->stage_terms_and_conditions = $stage;
        return $this->save();
    }

The issue I have is that the modifiedEvent also modifies the model, which means we get an infinite loop!

Whats the best way to make sure that this event is not triggered multiple times due caused by the event it self.



via Chebli Mohamed

Cors Is Needed, but how do I do it with Middle ware in Laravel 5.3?

So I have the following middle ware (similar to this question):

<?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-Headers', 'Content-Type, X-Auth-Token, Origin')
            ->header('Access-Control-Expose-Headers', 'X-Total-Count')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }

}

Seems simple, its registered:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        // ...
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'cors' => \App\Http\Middleware\Cors::class,
        // ...
    ];
}

The route uses it:

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

So by now we have everything working, great. Excellent. Now lets throw a wrench into our blog api, in the constructor lets do:

public function __construct(BlogsEntity $blogsEntity, BlogService $blogService, BlogValue $blogValue) {
    $this->blogsEntity  = $blogsEntity;
    $this->blogsService = $blogService;
    $this->blogValue    = $blogValue;

    $this->middleware('api.auth', ['only' => ['blogs', 'edit', 'delete']]);
    $this->middleware('api.blog.validation', ['only' => ['create', 'edit']]);
}

Ok so the first middle ware, since we will be calling the blogs method is the api.auth. What does that look like:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class ApiAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return response()->json(['status' => 401, 'error_message' => 'You cannot access this route.']);
        }


        return $next($request);
    }
}

So you might be thinking, well ya - you are getting the error:

Fetch API cannot load http://ift.tt/2kTDsUc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ift.tt/2k8SpNR' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Because you are not setting CORS on the api auth request. So I did:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class ApiAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return response()->json(['status' => 401, 'error_message' => 'You cannot access this route.'])
                ->headers( 'X-Total-Count', 0 );
        }


        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin')
            ->header('Access-Control-Expose-Headers', 'X-Total-Count')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

Same issue.

I have middle ware that affects specific routes and I have cors that affects all api routes. So how do I fix this?

I thought I was doing this right, the request coming in for any route, has all the associated headers on them If I remove the middle ware from the constructor, this works perfectly, no issue. If I remove the "only on blogs" part, its works perfectly. No issue.

The Cors middle ware is on every route for the api section. Yet some routes have specific middle ware that are triggered on specific actions that when enabled cause this cors issues, but when disabled do not.

help.



via Chebli Mohamed

Laravel 5: How to verify if values separated by comma from a database table field are contained in an array?

So, basically I have a field in a table from my database which contains some values separated by comma (something like: "value1, value2, value3"). I need to check somehow if one or more of these values are contained in an array of values and retrieve the model(s). I'd like a solution using Eloquent Model Query to achieve this, if not possible with Model Query, then a Query Builder solution will be okay as well, or maybe something alternative.



via Chebli Mohamed

Laravel save multiple record at once

have a problem to save multiple records at once. This is my form

    {!! Form::open(array('url'=>'pipeline/save?return='.$return, 'class'=>'form-horizontal','files' => true , 'parsley-validate'=>'','novalidate'=>' ')) !!}
    @foreach($destinazioni as $destinazione)
    <div class="col-md-2 col-md-offset-2 text-left">
        <input type="text" name="destination[]" readonly class="form-control" value=""/>

    </div>

    <div class="col-md-6 text-left">
        <select name="target[]" class="form-control">
        <option value="Nessuna">Seleziona...</option>
        @foreach($campi->keys() as $target)
        <option value="">  </option>
        @endforeach
        </select>
    </div>
    @endforeach
        @if(!empty($profilo->set_attributi))
            @foreach($profilo->attributi as $attributo)
            <div class="col-md-2 col-md-offset-2 text-left">
                <input type="text" name="destination[]" readonly class="form-control" value=""/>
            </div>
            <div class="col-md-6 text-left">
        <select name="target[]" class="form-control">
        <option value="Nessuna">Seleziona...</option>
        @foreach($campi->keys() as $target)
        <option value="">  </option>
        @endforeach
        </select>
    </div>
    @endforeach
@endif
<div style="clear:both"></div>  


                  <div class="form-group" style="margin-top:5%">
                    <label class="col-sm-4 text-right">&nbsp;</label>
                    <div class="col-sm-8">  
                    <button type="submit" name="apply" class="btn btn-info btn-sm" ><i class="icon-checkmark-circle2"></i> </button>
                    <button type="submit" name="submit" class="btn btn-primary btn-sm" ><i class="icon-bubble-check"></i> </button>
                    <button type="button" onclick="location.href='' " class="btn btn-warning btn-sm "><i class="icon-cancel-circle2 "></i>   </button>
                    </div>    

                  </div>

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

This is controller where i try to handle inserting of data:

$rules = $this->validateForm();
    $validator = Validator::make($request->all(), $rules);  
    if ($validator->passes()) {
        $request = array('destination' => $request->input('destination'), 'target' => $request->input('target'));
        foreach ($request as $req) {
            $destination = new Pipeline;        
            $destination->destination = $req->destination;
            $destination->target = $req->target;
            $destination->save();
        }

        return Redirect::to('pipeline')->with('messagetext',\Lang::get('core.note_success'))->with('msgstatus','success');

But actually i get Try to get proprety of non object error. I have also tried with Pipeline::insert($data) method but it return wrong names of column error



via Chebli Mohamed

mercredi 8 février 2017

Laravel 5.1 logs out when firing multiple ajax requests

My Laravel 5.1 installation keeps logging out randomly when I fire multiple ajax requests. This is solved by using Redis as session driver, but since this installation is running on Xampp (Windows) I can't use that. I already tried to switch to database session driver but that did not sove the issue.

I'm running PHP5.6.

Any help is appreciated.



via Chebli Mohamed

laravel, how can I ignore a special route?

how can I ignore special routes with nginx server. for example I have a.com address and I want Ignore a.com/abc



via Chebli Mohamed

mardi 7 février 2017

API Laravel through Java application

I have a LARAVEL API coded in PHP with MYSQL Database but i want to create a Desktop App for few users, but for this i have to call my API with token csrf how can i do that

I tried like that

(It is a test class)

    package com.trying.text;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;

public class Main {
    private final static String USER_AGENT = "Mozilla/5.0";
    private static String csrf;
    @Override
    public void start(Stage primaryStage) {

    }

    public static void main(String[] args) throws Exception {

        System.out.println("Testing 1 - Send Http GET request");
        sendGet();
        System.out.println("Testing 2 - Send Http POST request");
        sendPost();

    }

    public static void connectionHttp(){

    }

    // HTTP GET request
        private static void sendGet() throws Exception {

            String url = "http://ift.tt/2ko0YHN";

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            con.setRequestMethod("GET");

            //add request header
            con.setRequestProperty("User-Agent", USER_AGENT);

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // strip out your required data with a regex
            Pattern pattern = Pattern.compile(".*<input type=\"hidden\" name=\"_token\" value=\"(.*?)\">.*");
            Matcher matcher = pattern.matcher(response.toString());

            if (matcher.find()) {
                System.out.println(matcher.group(1));
                csrf = matcher.group(1);
                sendPost();
            }
            //print result
            System.out.println(response.toString());

        }

        // HTTP POST request
        private static void sendPost() throws Exception {

            String url = "http://ift.tt/2kDR9nu";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            String urlParameters = "name=test&password=test&_token=" + csrf;

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());

        }
}

I succeed to make a get call when i don't have to give to him a csrf (The first call is route that didn't under web middleware (Laravel for security and more..) But when i need to call an adress that need a csrf i try to get the csrf of one page that i know that had a csrf hidden input but i don't sicced to send a post request.

I have a 500 HTTP response.



via Chebli Mohamed

lundi 6 février 2017

automated logout function using laravel 5.1

am a fresher developer , actually my task is to set a automatic expiry account in php laravel 5.1, i tried it with middleware but it downs the sever speed, ok give me some ideas, actuallly wat iam searching is, if i registering into a site, at that time am inserting a current time in db, after creating user log, am triying to logging , so once i regstred as a new user, that account login access will be deactivated within 24 hours , by comparing the time which you inserted time while regstr.????????



via Chebli Mohamed

samedi 4 février 2017

Laravel occasionally failing to read cache

I am using laravel caching (the remember() method) on a website with a code like this:

$postedItems = Cache::remember('home_posted_items', $this->cacheTimes['postedItems'], function() {

    /* the stuff that prepares data */

    return ['items' => $items, 'firstItemNumber' => $firstItem];
});

The problem is that sometimes (every few days, I'd say) cached file seems to become corrupted and as a result I have downtime until the cache expires (unless I clear it manually).

Here is a part of the error stack that might be relevant:

[2017-02-04 22:01:34] production.ERROR: ErrorException: unserialize(): Error at offset 131059 of 131062 bytes in /home/path/to/app/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php:78
Stack trace:
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'unserialize(): ...', '/home/path/to/...', 78, Array)
#1 /home/path/to/app/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php(78): unserialize('a:2:{s:7:"item...')
#2 /home/path/to/app/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php(47): Illuminate\Cache\FileStore->getPayload('home_posted_ite...')
#3 /home/path/to/app/vendor/laravel/framework/src/Illuminate/Cache/Repository.php(98): Illuminate\Cache\FileStore->get('home_posted_ite...')
#4 /home/path/to/app/vendor/laravel/framework/src/Illuminate/Cache/Repository.php(202): Illuminate\Cache\Repository->get('home_posted_ite...')
#5 [internal function]: Illuminate\Cache\Repository->remember('home_posted_ite...', 1, Object(Closure))
#6 /home/path/to/app/vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php(318): call_user_func_array(Array, Array)
#7 /home/path/to/app/bootstrap/cache/compiled.php(6089): Illuminate\Cache\CacheManager->__call('remember', Array)
#8 /home/path/to/app/app/Http/Controllers/HomeController.php(197): Illuminate\Support\Facades\Facade::__callStatic('remember', Array)

How to solve this problem?

From experience I know that clearing the cache solves the problem. So it seems that the issue is some corruption in files. I think if I could notice "the file is unreadable" and just clear the cache (Cache::forget(...)), it should solve the problem.

What would be the best way to notice such error? It seems that all the logic of retrieving the file is hidden inside the remember() method. Should I just unwrap it and use other methods, something like the following?

if (!($postedItems = @Cache::get('home_posted_items'))
{
    // prepare data

    $postedItems = ['items' => $items, 'firstItemNumber' => $firstItem];

    Cache::put('home_posted_items', $postedItems, $this->cacheTimes['postedItems']);
}



via Chebli Mohamed

Laravel 5.1 - Eloquent parameter bindings being applied in wrong order?

I have the following update query which consists of a sub-query join (I had to use DB:Raw as I was unable to find any documentation to accomplish via any other method - unless someone can show me some other way to achieve it).

However, because the table/model being updated uses timestamps, a value for updated_at is also being added and messes up the order of the parameter bindings?

OrderItemProduct::from('order_item_product as t1')
        ->join(DB::Raw('(
           SELECT t1.product_id as product_id
                , MIN(t1.created_at) as created_at
                , MIN(t1.order_item_id) as order_item_id
             FROM order_item_product t1
      INNER JOIN order_items t2 on t1.order_item_id = t2.id
      INNER JOIN orders t3 on t2.order_id = t3.id
           WHERE t1.product_id = ?
             AND t1.available > 0
             AND TIMESTAMPADD(DAY,t1.valid_days,t1.created_at) > now()
             AND t3.user_id = ?
        GROUP BY t1.product_id) AS t2'), function($join)
        {
                $join->on('t1.order_item_id', '=', 't2.order_item_id');
                $join->on('t1.created_at', '=', 't2.created_at');

         })
        ->setBindings([$productId, $userId])
        ->decrement('t1.available');

Below is what I end up with when I die n dump the query log:

array:1 [▼
   0 => array:3 [▼
     "query" => """
       update `order_item_product` as `t1` inner join (\r\n
                 SELECT t1.product_id as product_id\r\n
  \t                  , MIN(t1.created_at) as created_at\r\n
  \t\t                , MIN(t1.order_item_id) as order_item_id\r\n
  \t\t             FROM order_item_product t1\r\n
             INNER JOIN order_items t2 on t1.order_item_id = t2.id\r\n
             INNER JOIN orders t3 on t2.order_id = t3.id\r\n
                  WHERE t1.product_id = ?\r\n
                    AND t1.available > 0\r\n
                    AND TIMESTAMPADD(DAY,t1.valid_days,t1.created_at) > now()\r\n
  \t                AND t3.user_id = ?\r\n
               GROUP BY t1.product_id) AS t2 ON `t1`.`order_item_id` = `t2`.`order_item_id` 
                   AND `t1`.`created_at` = `t2`.`created_at` 
                   SET `t1`.`available` = `t1`.`available` - 1, `updated_at` = ?
       """
     "bindings" => array:3 [▼
         0 => "2017-02-04 09:41:22"
         1 => 1
         2 => 1
     ]
     "time" => 2.9
   ]
]

As you can see inside the bindings array a value for updated_at is automatically added by eloquent at index 0 and so it's ending up being bound to the first parameter placeholder inside the query which is incorrect.

How can I fix this?



via Chebli Mohamed

QueryException in Connection.php line 662: : Integrity constraint violation: 1048 Column 'content' cannot be null

I use laravel 5.1 with this how can I do?

  1. I use laravel 5.1 with this how can I do? I use laravel 5.1 with this how can I do?

    strong textin Connection.php line 662 at Connection->runQueryCallback('insert into statuses (content, user_id, updated_at, created_at) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46'), object(Closure)) in Connection.php line 618 at Connection->run('insert into statuses (content, user_id, updated_at, created_at) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46'), object(Closure)) in Connection.php line 391 at Connection->statement('insert into statuses (content, user_id, updated_at, created_at) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46')) in Connection.php line 347 at Connection->insert('insert into statuses (content, user_id, updated_at, created_at) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46')) in Processor.php line 32 at Processor->processInsertGetId(object(Builder), 'insert into statuses (content, user_id, updated_at, created_at) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46'), 'id') in Builder.php line 1843 at Builder->insertGetId(array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46'), 'id') at call_user_func_array(array(object(Builder), 'insertGetId'), array(array('content' => null, 'user_id' => '1', 'updated_at' => '2017-02-04 14:36:46', 'created_at' => '2017-02-04 14:36:46'), 'id')) in Builder.php line 1015 at Builder->__call('insertGetId', array(array('content' => null, 'user_id' => '1', 'updated_at' => '2017-02-04 14:36:46', 'created_at' => '2017-02-04 14:36:46'), 'id')) in Model.php line 1592 at Model->insertAndSetId(object(Builder), array('content' => null, 'user_id' => '1', 'updated_at' => '2017-02-04 14:36:46', 'created_at' => '2017-02-04 14:36:46')) in Model.php line 1561 at Model->performInsert(object(Builder), array()) in Model.php line 1452 at Model->save() in HasOneOrMany.php line 317 at HasOneOrMany->create(array('content' => null)) in StatusesController.php line 34 at StatusesController->store(object(Request)) at call_user_func_array(array(object(StatusesController), 'store'), array(object(Request))) in Controller.php line 256 at Controller->callAction('store', array(object(Request))) in ControllerDispatcher.php line 164 at ControllerDispatcher->call(object(StatusesController), object(Route), 'store') in ControllerDispatcher.php line 112 at ControllerDispatcher->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)) in Authenticate.php line 45 at Authenticate->handle(object(Request), object(Closure)) at call_user_func_array(array(object(Authenticate), '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 102 at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114 at ControllerDispatcher->callWithinStack(object(StatusesController), object(Route), object(Request), 'store') in ControllerDispatcher.php line 67 at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\StatusesController', 'store') 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 102 at Pipeline->then(object(Closure)) in Router.php line 710 at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 673 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 102 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 53 at require_once('/var/www/sample/public/index.php') in server.php line 21

this is the end!



via Chebli Mohamed

vendredi 3 février 2017

Leverage browser caching for Laravel 5.1 application

Recently I was checking my web application loading speed (which is build using Laravel 5.1). And I came across Leverage browser caching. So I googled it to find a solution to this and I found a solution but it doesn't seem to work.

It was mentioned to add the following code:

<IfModule mod_expires.c>
  ExpiresActive on

# Perhaps better to whitelist expires rules? Perhaps.
  ExpiresDefault "access plus 1 month"

# cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
  ExpiresByType text/cache-manifest "access plus 0 seconds"

# Your document html
  ExpiresByType text/html "access plus 0 seconds"

# Data
  ExpiresByType text/xml "access plus 0 seconds"
  ExpiresByType application/xml "access plus 0 seconds"
  ExpiresByType application/json "access plus 0 seconds"

# Feed
  ExpiresByType application/rss+xml "access plus 1 hour"
  ExpiresByType application/atom+xml "access plus 1 hour"

# Favicon (cannot be renamed)
  ExpiresByType image/x-icon "access plus 1 week"

# Media: images, video, audio
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType image/jpg "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"

# HTC files (css3pie)
  ExpiresByType text/x-component "access plus 1 month"

# Webfonts
  ExpiresByType application/x-font-ttf "access plus 1 month"
  ExpiresByType font/opentype "access plus 1 month"
  ExpiresByType application/x-font-woff "access plus 1 month"
  ExpiresByType image/svg+xml "access plus 1 month"
  ExpiresByType application/vnd.ms-fontobject "access plus 1 month"

# CSS and JavaScript
  ExpiresByType text/css "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"

  <IfModule mod_headers.c>
    Header append Cache-Control "public"
  </IfModule>

</IfModule>

in .htaccess inside the public directory. But I still get recommendation for Leverage browser caching. Please help me with this. I am unable to find a solution to this.

Sites where I checked for page loading speed are:

  1. Google page speed
  2. gtmetrix.com

Thank you



via Chebli Mohamed

Laravel: Change format of Carbon dates in models when converted to JSON

Currently, when I convert a model to JSON, all Carbon date fields are casted like so:

"end_time": {
    "date": "2017-02-03 23:59:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/London"
}

I want it casted using the Atom notation. This can be done in carbon like so:

$order->end_time->toAtomString()

where $date is a Carbon date.

How can I make a model convert dates in the atom format when converting it to JSON?

I am aware that it is possible to append data like so: http://ift.tt/2kq3Q5e

But this does not change the format of an existing value?



via Chebli Mohamed

jeudi 2 février 2017

Memcached - "No Memcached servers added" after upgrading to ubuntu 16.04

Does upgrading from ubuntu 14.04 to 16.04 affect multi-server memcached?

I have a Laravel 5.1 application which utilizes memcached to manage sessions across multiple servers, specifically two web servers and a database server.

After upgrading the OS on each server from ubuntu 14.04 to 16.04 and installing the latest version of mariadb (10.1.*), our laravel application now returns the following error:

[RuntimeException] No Memcached servers added.

My config files have not changed and neither have the ip addresses of any of the servers. Debugging laravel's MemcachedConnector.phpshows the server details being passed to the Memcached class but the output of Memcached::getVersion() returns false.

I am at a loss as to why this has suddenly stopped working, any assitance would be appreciated.



via Chebli Mohamed