dimanche 31 janvier 2016

Why am i getting phpmyadmin logo in title of fresh laravel project?

by default my every fresh project in laravel has title with logo PMA (default with phpmyadmin)and then my project title how can i remove this.



via Chebli Mohamed

laravel 5.1 changing host name "NotFoundHttpException"

I just wondering why my laravel application will not work if I will change my host name ex:mynewapp.dev the error will thrown "NotFoundHttpException", but If I put it back the original host name ex: app.org , it works fine I am using homestead, I edited the homestead.yaml and my host file. I also clear the application cache.but still I cannot make it work with my new host name.

Thank you in advance.



via Chebli Mohamed

Eager loading inside eager loading in Laravel Eloquent

How to use eager loading inside eager loading? I tried make query like this: Here is my query in controller:

$user_all = User::with('universitas_has_detil')
->whereHas('universitas_has_detil', function ($query) {
    $query->where('jenjang_universitas_id_jenjang', 2)
})->get();

And here is my view:

@foreach($user->universitas_has_detil as $detil)
{{ $detil->jenjang_universitas->nama_jenjang }},
@endforeach

But the result is like this, and not efficient. enter image description here



via Chebli Mohamed

registration -> send data to two tables.

on registration i register a user to two tables - Users and Companies. Company.php and User.php have a relationship as you can see in code bellow.

in AuthController.php i use " 'user_id' => $user['id'], to pass id of new created row in users table to companies table. i know its somehow wrong but it works and i just want to know how could i create two rows at the same time with foreign key in much smarter way. i just think that i dont use that relationship properly though

company.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
    protected $fillable = [
        'ICO', 'user_id',
    ];
    public function user() {
        return $this->belongsTo('App\User');
    }
}

User.php

<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable {
    protected $fillable = [
        'firstname', 'middlename', 'lastname', 'email', 'password', 'usertype',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function company() {
        return $this->hasMany('App\Company');
    }
}

AuthController.php --> protected function create(array $data)

protected function create(array $data) {
        $user = User::create([
                    'firstname' => $data['firstname'],
                    'lastname' => $data['lastname'],
                    'middlename' => $data['middlename'],
                    'usertype' => $data['usertype'],
                    'email' => $data['email'],
                    'password' => bcrypt($data['password']),
        ]);
        $company = Company::create([
                    'ICO' => $data['ICO'],
                    'user_id' => $user['id'],
        ]);
        return $user;
    }



via Chebli Mohamed

A very weird Laravel issue

I am getting this very weird issue in Laravel.

return $this->pending($input);

When I do this, I get the data that I need.

{
  "total": 51,
  "per_page": 5,
  "current_page": 1,
  "last_page": 11,
  "next_page_url": "http://ift.tt/20g0hjT",
  "prev_page_url": null,
  "from": 1,
  "to": 5,
  "data": [
     //some data
   ]
}

However, when I tried doing this:

$response['pending'] = $this->pending($input);

I get a blank array.

{
  "pending": {}
}

Any idea why is this happening? I am sure the query is correct, because I am getting the expected result from the query.



via Chebli Mohamed

How to get unread mail count from Gmail using laravel 5.1?

How can I use mail.php file for take unread email count from gmail?Thanks in advance.



via Chebli Mohamed

samedi 30 janvier 2016

How fix image asset when remove public folder?

Hi all I am a new of laravel, After I am remove public folder (http://localhost/movie/public => http://localhost/movie) I can not put image on my laravel project with asset how can I fix.

First I am create folder in public folder uploads and then my code below:

<img src="{{asset('uploads/picc.png')}}">

And when run http://localhost/movie the image dont show,Help me please !!



via Chebli Mohamed

Laravel 5.1 - Method 'disk' not found in class \Illuminate\Support\Facade\Storage

I need to store images uploaded from a form to a project directory. But i'm having trouble using this method in my controller

Storage::disk('local')->put('image.jpg', 'Contents');

This is my controller

<?php

namespace App\Http\Controllers;

use App\Event;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

Even though i used 'Storage' class, phpstorm states that method 'disk'(or 'put' or 'delete') is not in that class. I'm using phpstorm 10

If I use like this,

use Storage;

phpstorm says undefined class 'Storage'



via Chebli Mohamed

Laravel displaying / logging errors

So I've just spent quite some time on something that should have been very quick to fix.

I'm on a local environment, with debug set to true. I was working on a php file which implements the Jsonable interface, and I got the compatibility a bit wrong. Unfortunatly, when I ran this file, it simply showed a 500 error and a completely blank, white page, without any errors.

I checked my error log, and that didn't have any errors in it (relating to this issue) either.

I found online that setting debug to true in Laravel hides sets display_errors to 0. I quickly did a ini_set('display_errors', 1) in my called controller and I got the fatal error message I was looking for!

My question is:

How can I display these fatal errors etc (not exceptions) in Laravel when debug is true, without specifying ini_set('display_errors', 1) in all my controllers?! Why does Laravel hide errors when in debug mode anyway?! It's very frustrating having an error which isn't displayed (even when in debug mode), and isn't logged!

Any help is appreciated.



via Chebli Mohamed

xroot anouar Paypal integration with Laravel 5.1

I have been follow all steps mention in this link. xroot/laravel-paypalpayment and after long days finally the example is done successfully but how to change PaymentMethod from credit_card to paypal and how the code will be ? I'm very beginner in this

this is the php code part for credit card payment

// ### Address
        // Base Address object used as shipping or billing
        // address in a payment. [Optional]
        $addr= Paypalpayment::address();
        $addr->setLine1("3909 Witmer Road");
        $addr->setLine2("Niagara Falls");
        $addr->setCity("Niagara Falls");
        $addr->setState("NY");
        $addr->setPostalCode("14305");
        $addr->setCountryCode("US");
        $addr->setPhone("716-298-1822");

        // ### CreditCard
        $card = Paypalpayment::creditCard();
        $card->setType("visa")
            ->setNumber("4758411877817150")
            ->setExpireMonth("05")
            ->setExpireYear("2019")
            ->setCvv2("456")
            ->setFirstName("Joe")
            ->setLastName("Shopper");


        // ### FundingInstrument
        // A resource representing a Payer's funding instrument.
        // Use a Payer ID (A unique identifier of the payer generated
        // and provided by the facilitator. This is required when
        // creating or using a tokenized funding instrument)
        // and the `CreditCardDetails`
        $fi = Paypalpayment::fundingInstrument();
        $fi->setCreditCard($card);

        // ### Payer
        // A resource representing a Payer that funds a payment
        // Use the List of `FundingInstrument` and the Payment Method
        // as 'credit_card'
        $payer = Paypalpayment::payer();
        $payer->setPaymentMethod("credit_card")
            ->setFundingInstruments(array($fi));

thanks in advance



via Chebli Mohamed

How to send a letter to the laravel?

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=******
MAIL_PASSWORD=******
MAIL_ENCRYPTION=ssl



ERROR

Swift_TransportException in StreamBuffer.php line 265: Connection could not be established with host "smtp.gmail.com [ #0]



via Chebli Mohamed

Laravel error. Failed to open dir: not implemented

I'm trying this script to render a gallery from all the pictures in a folder in a Laravel project. I got this error

ErrorException in ArmadiController.php line 32: opendir(http://ift.tt/1PGYtFj): failed to open dir: not implemented

this is the function in the controller that generates the error. How can i make it work or do something similar?

public function gallery()
    {
        $data = [];
        $folder_path = asset('images');
        $num_files = glob($folder_path . "*.{JPG,jpg,gif,png,bmp}", GLOB_BRACE);
        $folder = opendir($folder_path);
        if ($num_files > 0) {
            while (false !== ($file = readdir($folder))) {
                $file_path = $folder_path . $file;
                $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif' || $extension == 'bmp') {
                    $data[] = $file_path;
                }
            }
        } else {
            return "the folder was empty !";
        }
        closedir($folder);
        return $data;
    }



via Chebli Mohamed

List out subcategories under parentcategory based on product

I tried to display category that has subcategories within it. This is the sample structure of my categories:

Electronic
-Computer
-Phone
-Gadget

Grocery
-Food
-Drinks

This is my products table migration:

   Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->decimal('price')->nullable();
        $table->timestamps();
    });

This is my categories table migration

   Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('parent_id')->nullable();
        $table->string('name')->nullable();
        $table->string('description')->nullable();
        $table->timestamps();
    });

and this one is the category_product which acts as for many to many table between category and product:

    Schema::create('category_product', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('product_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->timestamps();
    });

I have setup all the relationship. Here are my models:

This is my category model:

class Category extends Model
{
    protected $table = 'categories';

    protected $fillable = [
        'name',
    ];
    public function products()
    {
        return $this->belongsToMany('App\Product');
    }

    public function parent()
    {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('App\Category', 'parent_id');
    }

}

This is my product model:

class Product extends Model
{
   public function categories()
   {
     return $this->belongsToMany('App\Category');
   }
}

This is my ProductController.php, I'm able to display all parents category with its subcategories using this code:

public function show($id)
 {   
      $product = Product::findOrFail($id); 
      $categories = Category::with('children')->get();
      return view('products.show', compact('product','categories'));

 }

So my product.shows.blade looks like this:

@foreach($categories as $item)
    @if($item->children->count() > 0 )
        <li>
            {{ $item->name }}
            <ul>
                @foreach($item->children as $submenu)
                    <li>{{ $submenu->name }}</li>
                @endforeach
            </ul>
        </li>
    @endif

@endforeach

//OUTPUT:

Electronic  
 Computer
 Phone
 Gadget

Grocery
 Food
 Drinks

But let say that this particular product (called Product 1) has the parent category of Electronic and the subcategory is Computer and Phone which I already attached them in the database. This is the overview of the data from the database:

products table

categories table

category_product table

How do I display the category of Product 1 with its parent and subcategories? I want the output to be like

Product 1 

Category:
 Electronic
  Computer
  Phone



via Chebli Mohamed

Laravel handle default route if optional parameter is not in the list

I define optional parameter "type" in the route and limit acceptable values (A,B or C) with where clause:

Route::get('test/{type?}', ['uses' => 'MyController@index'])->where('type', 'A|B|C');

If type value is different to A,B or C (e.g. "X") framework returns error page:

NotFoundHttpException in RouteCollection.php

In such case I would like to ignore received optional parameter and handle route as it is with no specified parameter i.e.: test/

How can it be implemented?



via Chebli Mohamed

Laravel 5.1 Format date BEFORE being put in array inside controller

I have the following code in my controller:

$gecko_id = Gecko::where(compact('user_id', 'name'))->first()->id; 
$weight = Weight::where(compact('user_id', 'gecko_id'))->orderBy('weighed_date', 'desc')->take(7)->get()->reverse();
$gecko = Gecko::where(compact('user_id', 'name'))->first();

return view('gecko.show')
    ->with('gecko', $gecko)
    ->with('dates', $weight->lists('weighed_date'))
    ->with('amounts', $weight->lists('gecko_weight'));

Which is sending data to my view for a chart i'm plotting. My dates list is outputting the following data format:

["2015-06-01","2015-05-01","2015-04-01","2015-03-01","2015-02-01","2015-01-01"]

Ideally I would like to format this before it is passed to the view so it's more readable. So say 2015-06-01 would be be reformatted into 01/06/2016 - I know how to do this in the usual PHP way, but because I'm putting the data into an array, I'm unsure on the best way of achieving my goal.



via Chebli Mohamed

One to Many relationship in Laravel Eloquent giving undefine method

I am having the said problem when defining one to many relationship with two models, the Student and Enrollment. When accessing the table from another table using :

$enrollment->students()->first_name

Can someone help me on this.

Enrollment

    protected $fillable = [
    'subject_code',
    'subject_description',
    'section',
    'schedule',
    'room_no',
    'no_of_units'
];

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

Student

   protected $fillable = [
    'student_id',
    'first_name',
    'last_name',
    'middle_name',
    'birthdate',
    'fathers_name',
    'mothers_name',
    'phone_no',
    'degree_id',
    'city_id',
    'address'
];

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

Here's the table for the students and enrollment accordingly

        Schema::create('enrollments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('student_id');
        $table->string('subject_description');
        $table->string('subject_code');
        $table->time('schedule');
        $table->string('room_no');
        $table->integer('no_of_units');
        $table->string('section');
        $table->timestamps();
    });

           $table->increments('id');
        $table->integer('student_id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('middle_name');
        $table->date('birthdate');
        $table->string('fathers_name');
        $table->string('mothers_name');
        $table->string('phone_no');
        $table->string('address');
        $table->integer('city_id');
        $table->integer('degree_id');
        $table->timestamps();
    });



via Chebli Mohamed

vendredi 29 janvier 2016

Laravel 5 How to run a php file via scheduler

First time ever setting up a cron/scheduler. How do I run a php file with the scheduler? This is what I see in Laravel's documentation...

Entered the following command via Putty/SSH...

php /path/to/artisan schedule:run >> /dev/null 2>&1

Now... In the Kernel.php file... do I simply add the path to the php file that I want to run in the statement below?

$schedule->exec('node /home/forge/script.js')->daily();



via Chebli Mohamed

Laravel method not recieving post data on $request

On Laravel 5.1 a method is not recivieng the post data.

This is my method where $request does not store the data sent by post.

class ProjectCommentController extends Controller
{
    public function store(Request $request,$projectId)
    {
    $this->validate($request, [
        'description' => ['required'],
        'status' => ['required'],
        'profile_id' => ['required']
    ]);

    $project = Project::findOrFail($projectId);

    return $project->comments()->save(new Comment([
        'description' => $request->input('description'),
        'status' => $request->input('status'),
        'profile_id' => $request->input('profile_id')
    ]));
    }
}

This is how I call it from my test:

public function testProjectCommentCreation()
{
$category = factory(\App\Category::class)->create();

$project = factory(\App\Project::class)->create([
    "category_id" => $category->id
]);

$profile = factory(\App\Profile::class)->create();


$comment = factory(\App\Comment::class)->make([
    "profile_id"=>$profile->id
]);

$this->post(route('api.projects.comments.store', ['projects' => $project->id]), $comment->jsonSerialize(), $this->jsonHeaders)
    ->seeInDatabase('comments', ['project_id'=>$project->id,'description'=>$comment->description])
    ->assertResponseOk();
 }

This is what $comment->jsonSerialize() stores:

array(3) {
'description' =>
string(10) "zFG8bW7EIz"
'status' =>
string(6) "active"
'profile_id' =>
int(629)
}

And this is my route:

Route::resource('projects.comments','ProjectCommentController',['only'=>['index','store']]);

My method recieves $projectId from the URL and that is working but the request comes empty, without the data I send from $comment->jsonSerialize()



via Chebli Mohamed

Laravel Model protected $dateFormat - How to remove seconds?

Platform: Laravel 5.1

Database: MySQL

I'm also using Fractal Transformers for transforming my returned data to JSON objects.

After putting this protected $dateFormat = 'Y-m-d H:i'; in my Model(note the missing :s) Carbon is throwing errors:

exception 'InvalidArgumentException' with message 'Trailing data' in C:\project1\vendor\nesbot\carbon\src\Carbon\Carbon.php:425

According to the documentation this should work: http://ift.tt/1m1Ra3D

I've tried the following:

  • Change my MySQL table structure from TIMESTAMP to DATETIME- no change
  • Changing the returned value with substr($time, 0, -3) - got errors
  • Asking in Gitter for help, got this:

I might be using a different Persistence that doesn't use the MySQL format

What does this mean?

How do I make sure Carbon::now() or MySQL is creating timestamps without seconds?

OR

How do I return only Y-m-d H:i?



via Chebli Mohamed

Laravel 5.1 randomly dropping session data

I have a strange issue with a Laravel 5.1 application.

Intermittently, it’s dropping session data. I’m detected this by writing some middleware that writes the contents of the session for that request to the log file. Although the session ID (Session::getId()) doesn’t change, the value of _token in the session data retrieved with Session::all() does.

As I say, this happens intermittently. I can refresh the same URL multiple times, and then randomly on one refresh the session data’s gone, and the _token value’s different from the previous requests.

What would cause this? I’ve also noticed the flash object isn’t in the “dropped” session data.

Below is a snippet of the log. You can see the content of the session_data key randomly changes “shape” in the last two lines, but the session ID remains constant.

Also, not sure if it’s pertinent, but I have DebugBar enabled.

Screen-shot



via Chebli Mohamed

str_ireplace with arrays and excludes and a limit on replacements

In one of my projects the customer demands that their brandname in the content must be followed by the 'Registered' trademark everytime it occurs in the content.

I really don't like this because the elevated '®' is very ugly and legally not really necessary. Once per page (somewhere on top) is enough.

I have created a function to somply with their wishes:

function replaceWith($content)
{
    // Array with replacements to use
    // (removes also ® already in the physical content)

    $replaces => [
        '®'         => '',
        'brandname' => 'BRANDNAME<sup>&reg;</sup>'
    ],

    // Array with excludes (I do not want url's etc to change too)
    $excludes => ['a', 'img', 'href']

    list($search, $replace) = array_divide($replaces);

        // Using simplehtmldom to load the DOM
        $html = new \Htmldom();
        $html->load($content);

        if (!empty($html))
        {
            foreach ($html->find('text') as $element)
            {
                if (!in_array($element->parent()->tag, $excludes))
                {
                    $element->innertext = str_ireplace($search, $replace, $element->innertext);
                }
             }
         $result = (string)$html;
     }
    $html->clear();
    return $result;
}

Now I like to change this because I want only the first occurence to be changed instead off all. There is no limit available on str_ireplace. I have found some workarounds but they all work with strings or integers as values, not with arrays as search and replace values.



via Chebli Mohamed

laravel update from 5.1 to 5.2 composer update error

I am trying to update laravel from 5.1 to 5.2 . I followed the instruction as according to update doc but I am getting this error when running composer udpate:

Error Output: PHP Fatal error: Call to undefined method Illuminate\Foundation\Application::bindShared() in /my_app/vendor/illuminate/html/HtmlSe rviceProvider.php on line 36

I've looked up this issue and saw that people were getting this issue when updating to version 5.1 and saw that the method bindShared has been replaced with singleton(), but I don't want to mess with vendor files. Here is my config/app.php providers and aliases arrays:

'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Auth\AuthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    Illuminate\Hashing\HashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    Illuminate\Html\HtmlServiceProvider::class,

    /*
     * Application Service Providers...
     */
    App\Providers\AppServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,
    App\Providers\ViewComposerServiceProvider::class,
    Laracasts\Flash\FlashServiceProvider::class,
    Baum\Providers\BaumServiceProvider::class

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App'       => Illuminate\Support\Facades\App::class,
    'Artisan'   => Illuminate\Support\Facades\Artisan::class,
    'Auth'      => Illuminate\Support\Facades\Auth::class,
    'Blade'     => Illuminate\Support\Facades\Blade::class,
    'Bus'       => Illuminate\Support\Facades\Bus::class,
    'Cache'     => Illuminate\Support\Facades\Cache::class,
    'Config'    => Illuminate\Support\Facades\Config::class,
    'Cookie'    => Illuminate\Support\Facades\Cookie::class,
    'Crypt'     => Illuminate\Support\Facades\Crypt::class,
    'DB'        => Illuminate\Support\Facades\DB::class,
    'Eloquent'  => Illuminate\Database\Eloquent\Model::class,
    'Event'     => Illuminate\Support\Facades\Event::class,
    'File'      => Illuminate\Support\Facades\File::class,
    'Hash'      => Illuminate\Support\Facades\Hash::class,
    'Input'     => Illuminate\Support\Facades\Input::class,
    'Inspiring' => Illuminate\Foundation\Inspiring::class,
    'Lang'      => Illuminate\Support\Facades\Lang::class,
    'Log'       => Illuminate\Support\Facades\Log::class,
    'Mail'      => Illuminate\Support\Facades\Mail::class,
    'Password'  => Illuminate\Support\Facades\Password::class,
    'Queue'     => Illuminate\Support\Facades\Queue::class,
    'Redirect'  => Illuminate\Support\Facades\Redirect::class,
    'Redis'     => Illuminate\Support\Facades\Redis::class,
    'Request'   => Illuminate\Support\Facades\Request::class,
    'Response'  => Illuminate\Support\Facades\Response::class,
    'Route'     => Illuminate\Support\Facades\Route::class,
    'Schema'    => Illuminate\Support\Facades\Schema::class,
    'Session'   => Illuminate\Support\Facades\Session::class,
    'Storage'   => Illuminate\Support\Facades\Storage::class,
    'URL'       => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View'      => Illuminate\Support\Facades\View::class,
'Form'      => Illuminate\Html\FormFacade::class,
'Html'      => Illuminate\Html\HtmlFacade::class,
'Carbon'    => 'Carbon\Carbon',
'Flash'     => Laracasts\Flash\Flash::class,

],

and here is my composer.json:

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"repositories": [{
    "type": "vcs",
    "url": "http://ift.tt/1WRC127"
    }],
"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.2.*",
    "doctrine/dbal": "^2.6@dev",
    "illuminate/html": "^5.0@dev",
    "laracasts/flash": "dev-master",
    "fairholm/elasticquent": "dev-feature/laravel-5",
    "baum/baum": "~1.1"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "phpspec/phpspec": "~2.1",
    "symfony/dom-crawler": "~3.0",
    "symfony/css-selector": "~3.0"

},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-install-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ],
    "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"
},
"minimum-stability": "dev",
"prefer-stable": true
}

any idea what I should do to fix this? I started with a 5.1 version install of laravel.



via Chebli Mohamed

Laravel 5.1 - Generate a unique 10 alphanumeric character code upon save to database

I'm working in Laravel 5.1 and saving a gecko to a database (note that i will update my code soon when i'm on my break).

I have an idea floating around in my head that I would like to create a unique 10 character alphanumeric string to save to each gecko.

I know that I can generate random strings easily inside Laravel, and my plan was to add it in the controller and do a validation rule for it inside my model - but i didn't want it to flag an error to the screen that a random string couldn't be generated, as it should do all this behind the scenes and continue until it can create one.

Is there a proper practice into achieving something like this?

Thanks for any info, Andy



via Chebli Mohamed

Laravel 5.1 - How to access dynamic URI segment in Controller and Route

Team,

I am using Laravel 5.1, In which I have to use URI segment feature same as Codeigniter

Like eg. URL - http://ift.tt/1nsgz7q....

Want to access those parameters user_id, user_type, user_role in controller and also want to manage the Route file.

Can anyone guide me how to do this in LARAVEL?

Thanks in Advance



via Chebli Mohamed

Error Message are not being sent to Blade. Laravel 5.2.12

I am using Laravel 5.2.12

I have a request class like below.

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

    public function rules()
    {
        return [
            'UserName'      =>  'required|min:5|max:50',
            'Password'      =>  'required|confirmed|min:5|max:100',
        ];
    }

    public function response(array $errors){
        print_r($errors);
        return \Redirect::back()->withErrors($errors)->withInput();
    }
}

This request class is being used to validate the data during registration in the inbuilt template of Laravel. Below are the methods

public function postRegister(RegisterRequest $request)
//            **Check here** ^^^^^^^^^^^^^^^
{
    return $this->register($request);
}

We can find the path for this method below.

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

Below is the code written in Register page.

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

What's the problem ?

Error messages are not displaying in register Blade.

What have I tried so far ?

In the request class, there is below method.

public function response(array $errors){
    print_r($errors);
    //die();
    return \Redirect::back()->withErrors($errors)->withInput();
}

Although it prints when I enable die() but it never sends the error message in blade.



via Chebli Mohamed

Laravel 5.1 format date array for chart.js data

Apologies, I can't upload my controller code right now but I'm hoping you can help with the info I can give you.

I'm using chart.js to plot a line graph of data. I'm passing the values from my controller for the data points and the date that matches the date point.

In my view I'm receiving the following array from the controller:

["2015-06-01","2015-05-01","2015-04-01","2015-03-01","2015-02-01","2015-01-01"]

Which is then being encoded into JSON. Now, should I be attempting to format the date into something a bit more readable inside the controller or inside the view?



via Chebli Mohamed

Date formatting two different times with same code

I'm using FullCalendar to display employee shifts in a calendar form.

I'm using tooltips to display a very brief summary of their shift which works fine, and then when I click on the event it loads up a modal with the full information about the shift.

For some reason calling event.end.format("h:mm a") in the EventRender function to produce the tooltip gives me the correct finishing time for that person, yet when trying to produce the same for the modal in the EventClick function I get a different result.

Maybe I'm missing something, but I've been at it for hours trying to debug it and cannot work it out as the code is exactly the same for producing the time. All the events come from a JSON feed (and the time is correct everywhere else) yet, for example, the expected outcome of event.end.format("h:mm a") is 4:30 pm (and is displayed correctly in the tooltip) comes out as 12:30 am in the modal and I am still using event.end.format("h:mm a").

Full code for my calendar below:

<script>
    $(document).ready(function() {

    $('#calendar').fullCalendar({
        header:{
        left:"prev,next today",
        center:"title",
        right:"month,agendaWeek,agendaDay"},
        eventLimit:false,

        eventClick:  function(event) 
        {
            $('#modalTitle').html(event.title);
            $('#modalBody').html("<p><strong>Start:</strong> " + event.start.format("h:mm a") + "</p>" +
                                    "<p><strong>Finish:</strong> " + event.end.format("h:mm a") + "</p>" +
                                    "<p><strong>Lunch Duration:</strong> " + event.total_breaks + " minutes </p>" +
                                    "<p><strong>Shift Type:</strong> " + event.shift_status + "</p>"
                                    );
            $('#eventUrl').attr('href',event.url);
            $('#fullCalModal').modal();
        },
        defaultDate: moment().format("YYYY-MM-DD"),
        editable: false,
        displayEventEnd: true,
        events: {
            url: 'calendar/test',
            error: function() 
            {
                alert("error");
            },
            success: function()
            {
                console.log("successfully loaded");
            }
        },
        loading: function(bool) 
        {
            console.log("loading");
        },
        eventAfterRender: function (event, element) 
        {
        $(element).tooltip({title:event.title + " working " + event.start.format("h:mm a") + " to " + event.end.format("h:mm a") + ". " + event.end.subtract({hours:event.start.format("H"), minutes:event.start.format("m")}).format("H") + " hours and " + event.end.subtract({hours:event.start.format("H"), minutes:event.start.format("m")}).format("m") + " minutes worked.", container: "body"});
        }       
    });

    });
</script>

Can anyone help point out why I am getting the incorrect time inside the modal for the event end time?



via Chebli Mohamed

jeudi 28 janvier 2016

laravel 5.1 queues undefined function in handle() but working in constructor

I use Laravel 5.1 queues to process large images. I've a very strange behavior since when I call a function "imagettfbbox" in the constructor it works. But obviously I need to make it work in the "handle" but there I got an error.

public function __construct()
{
    //TEST
    $font_path = public_path('/fonts/roboto/Roboto-Thin.ttf');

    imagecreate(10,10); //works!
    imagettfbbox(10, 0, $font_path, 'test'); //works!
}

public function handle() //GenerateImage $generator, Image $img
{
    //TEST
    print 'OK'; //gets printed
    $font_path = public_path('/fonts/roboto/Roboto-Thin.ttf');

    imagecreate(10,10); //works!
    imagettfbbox(10, 0, $font_path, 'test'); //CRASHES!
}

I get the 'OK' printed and then the error "Call to undefined function App\Jobs\imagettfbbox()". It is a very strange behavior since some image functions work other not. I've GD installed and everywhere outside handle the code works. Any clue what I'm missing here?



via Chebli Mohamed

Laravel route not working with file extension

I am trying to create a route in Laravel 5.1 that will work for a generic permalink.

Route::get('{generic_url}.html', 'Frontend\CMSController@generic');

When I go to a URL say /this-is-my-page.html I get a 404 page that does not originate from within Laravel (my custom 404 page does not appear). However, when I go to /http://ift.tt/1OTpYOT everything works fine.

I believe that this problem is originating from the configuration of the server. My .htaccess is as follows:

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

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

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

As I am still developing this solution, I am using the php -S localhost:8000 command to launch the web server. Could that be the cause of my problem? Is there something wrong with the default configuration? Should I move my development to a "real" server?



via Chebli Mohamed

Update not working on laravel 5.1 using resource

Im getting Getting MethodNotAllowedHttpException in RouteCollection.php line 219:Store, create, edit are all working but when trying to update I get the error above.

{!! Form::model($enrollment['method'=>'POST','route'=>['/enrollment',$enrollment->id],'class'=>'form-horizontal']) !!}

                <div class="form-group">
                    <label for="subject_code" class="col-md-3 control-label">Subject Code</label>
                    <div class="col-md-8">
                        <select class="form-control" name="_method" value="PUT" id="subject_code">
                            <option value="{{ $enrollment->subject_code }}">{{ $enrollment->subject_code }}</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->subject_code }}">{{ $subject->subject_code}}</option>
                            @endforeach 
                        </select>
                    </div>

                </div>

                <div class="form-group">
                    <label for="subject_description" class="col-md-3 control-label">Subject description</label>
                    <div class="col-md-8">
                        <select class="form-control" name="subject_description" id="subject_description">
                            <option value="{{ $enrollment->subject_description }}">{{ $enrollment->subject_description }}</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->subject_description }}">{{ $subject->subject_description}}</option>
                            @endforeach 
                        </select>
                    </div>

                </div>


                <div class="form-group">
                    <label for="subject_code" class="col-md-3 control-label">Subject Code</label>
                    <div class="col-md-8">
                        <select class="form-control" name="subject_code" id="subject_code">
                            <option value="{{ $enrollment->section }}">{{ $enrollment->section}}</option>
                            @foreach($sections as $section)
                                <option value="{{ $section }}">{{ $section }}</option>
                            @endforeach
                        </select>
                    </div>

                </div>


                <div class="form-group">
                    <label for="subject_code" class="col-md-3 control-label">Subject Code</label>
                    <div class="col-md-8">
                        <select class="form-control" name="subject_code" id="subject_code">
                            <option value="{{ $enrollment->schedule }}">{{ $enrollment->schedule }}</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->schedule }}">{{ $subject->schedule}}</option>
                            @endforeach 
                        </select>
                    </div>

                </div>  

                <div class="form-group">
                    <label for="subject_code" class="col-md-3 control-label">Subject Code</label>
                    <div class="col-md-8">
                        <select class="form-control" name="subject_code" id="subject_code">
                            <option value="{{ $enrollment->no_of_units }}">{{ $enrollment->no_of_units }}</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->no_of_units }}">{{ $subject->no_of_units}}</option>
                            @endforeach 
                        </select>
                    </div>

                </div>
                <div class="form-group">
                    <div class="col-md-7 col-md-offset-3">

                        <button type="submit" class="btn btn-success">
                            <i class="fa fa-save"></i>
                            &nbsp;Save Changes
                        </button>

                        <button type="submit" class="btn btn-danger">
                            <i class="fa fa-times-circle"></i>
                            &nbsp;Delete
                        </button>
                    </div>
                </div>                                                                              
{!! Form::close() !!}

Here's my EnrollmentController:

    public function update(EnrollmentRequest $request, $id)
{
    $enrollment = Enrollment::findOrFail($id);
    $enrollment->update($request->all());
    return redirect('/enrollment');
}

routes.php

// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

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

Route::resource('enrollment','EnrollmentController');



via Chebli Mohamed

Flash session not found with Angular

I am working with angular and laravel. I want to use flash session of Laravel in ng-view. I dont know how to do it. I have an error "Class session not found".

I import Angular.

<script type="text/javascript" src="/public/assets/js/angular.min.js"></script>

I use routeProvider to load views

Example:

when('/registro', {
    templateUrl: '/public/templates/registro/index.php'
 })

In the view

<?php echo Session::get('data') ?>



via Chebli Mohamed

Laravel Eloquent: Raw query with a like clause gives Indeterminate datatype: 7 ERROR

I've got a seemingly simple query like so:

$query = $org->products()
    ->select ("products.*");

$searchString = 'abc';
if ($searchString) {
    $query->whereRaw(DB::raw("products.name like '%?%'"), [$searchString]);
}

$productCount = $query->count();

This generates a QueryException:

2/2
QueryException in Connection.php line 651:
SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR: could not determine data
type of parameter $2 (SQL: select count(*) as aggregate from "products" where 
"products"."org_id" = 3586397f-ebe4-4c07-af72-63edb7cbe1a7 and 
"products"."org_id" is not null and products.name LIKE '%abc%')

If I change the whereRaw clause to:

 $query->whereRaw(DB::raw("products.name like ?"), ['%' . $searchString . '%']);

The query executes properly. What could be going on here?

PS:

I know it's best to use query builder for such clauses, like so:

 $query->where("products.name", "like", '%' . $searchString . '%');

However, this query above is the reduced form of a more complex query where using DB:raw() with a LIKE clause is unavoidable (perhaps, I should ask a separate question about that)



via Chebli Mohamed

How do I pass a parameter to a controller action within a Laravel Package?

Within a Laravel package I made, I want to redirect the user to a controller action that requires a parameter (within the same package).

Controller:

public function postMatchItem(Request $request, $id)
{
    $this->validate($request, [
        'item_match' => 'required|numeric|exists:item,id',
    ]);

    $spot_buy_item = SpotBuyItem::find($id);

    $item = Item::find($request->input('item_match'));

    $price = $item->getPrice();

    $spot_buy_item_response = new SpotBuyItemResponse();
    $spot_buy_item_response->spot_buy_item_id = $id;
    $spot_buy_item_response->spot_buy_id = $spot_buy_item->spot_buy_id;
    $spot_buy_item_response->item_id = $item->id;
    $spot_buy_item_response->user_id = $spot_buy_item->user_id;
    $spot_buy_item_response->spot_buy_price = $price;
    $spot_buy_item_response->created_ts = Carbon::now();
    $spot_buy_item_response->save();

    return redirect()->action('Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getPart', [$id]);
}

The action in the redirect is the same path I use in my routes.php file to direct the user to this controller action

Route:

Route::get('/part/{id}', 'Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getPart')->where('id', '[0-9]+');

I've tried variations of this path without success, including SpotBuyController@getPart like the documentation suggests (http://ift.tt/1P0uYyR)

Note: I got this to work by naming my route in routes.php and using return redirect()->route('route_name', [$id]);, but I still want to know how to pass a package controller action to the ->action() function.



via Chebli Mohamed

Avoiding duplicate code in two controllers in Laravel 5.1

I have a route in Laravel 5.1 that will accept a generic permalink and will need to determine what object it belongs to (for example is it a permalink for a "Blog" or a "Story"?).

The route looks like this:

// .... Every other route in the routes.php file //
Route::get('{generic_url}', 'CMSController@generic');

Then the code in the my controller looks like this:

public function generic($generic_url) {
    $blog = Blog::where('permalink', $generic_url)->first();
    if(!is_null($blog)) {
        // Load a blog entry page
    }

    // Something basically the same as above but for Story
}

I also have this route in my routes.php file to view a blog post:

Route::get('/blog/{blog_id}', 'BlogController@view');

The purpose of that second route was for me rough in the view a blog post page as well as a quick way for me to debug a particular post.

I am hoping to avoid having to put view code in two separate controllers. My first thought was to try and find a way to have CMSController call the view action in the BlogController. It sounds like a terrible idea to me and some searching around confirms that it is a terrible idea.

My question is, what is the best way to handle this situation?



via Chebli Mohamed

Ugrading Laravel 5.1

Hello I am facing problem in upgrading the laravel 5.1 to 5.2. I have added "require": { "php": ">=5.5.9", "laravel/framework": "5.2.*" }, in my project composer.json

Screenshot of error



via Chebli Mohamed

How to Get Current Address accurately using Google Maps?

Im trying to get my current location but the problem is the address which the marker points is only the nearest street where I am now. How can I get my place accurately?

Heres the screen shot. Thanks in advance :) Click here



via Chebli Mohamed

Shared sections in master layout containing db data

In my Laravel 5.1 app, I have a master layout with a shared section, let's say a sidebar with a list of the 5 most recent site posts. The section content is dynamic (elaborated from a db query), but identical on every website page.

To obtain this, in the master layout I could @include a sub-view containing the sidebar code, but that would still mean repeating the same db query in each controller action, which is a lot of code repetition. I'm sure there is a smarter way to obtain this, but I couldn't figure it out. Any help would be really appreciated.



via Chebli Mohamed

Getting MethodNotAllowedHttpException in RouteCollection.php line 219: on laravel

Im getting the errors above. I tried to read on other forums with the same problem but with no luck. My create, store and edit are working. However when updating my form im getting the error above. Can someone help me on this. Thanks

{!! Form::open(['method'=>'POST','url'=>['/enrollment',$enrollment->id],'class'=>'form-horizontal']) !!}

                <div class="form-group">
                    <label for="subject_code" class="col-md-3 control-label">Subject Code</label>
                    <div class="col-md-8">
                        <select class="form-control" name="_method" value="PUT" id="subject_code">
                            <option value="{{ $enrollment->subject_code }}">{{ $enrollment->subject_code }}</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->subject_code }}">{{ $subject->subject_code}}</option>
                            @endforeach 
                        </select>
                    </div>

                </div>

                <div class="form-group">
                    <label for="subject_description" class="col-md-3 control-label">Subject description</label>
                    <div class="col-md-8">
                        <select class="form-control" name="subject_description" id="subject_description">
                            <option value="{{ $enrollment->subject_description }}">{{ $enrollment->subject_description }}</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->subject_description }}">{{ $subject->subject_description}}</option>
                            @endforeach 
                        </select>
                    </div>

                </div>


                <div class="form-group">
                    <label for="subject_code" class="col-md-3 control-label">Subject Code</label>
                    <div class="col-md-8">
                        <select class="form-control" name="subject_code" id="subject_code">
                            <option value="{{ $enrollment->section }}">{{ $enrollment->section}}</option>
                            @foreach($sections as $section)
                                <option value="{{ $section }}">{{ $section }}</option>
                            @endforeach
                        </select>
                    </div>

                </div>


                <div class="form-group">
                    <label for="subject_code" class="col-md-3 control-label">Subject Code</label>
                    <div class="col-md-8">
                        <select class="form-control" name="subject_code" id="subject_code">
                            <option value="{{ $enrollment->schedule }}">{{ $enrollment->schedule }}</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->schedule }}">{{ $subject->schedule}}</option>
                            @endforeach 
                        </select>
                    </div>

                </div>  

                <div class="form-group">
                    <label for="subject_code" class="col-md-3 control-label">Subject Code</label>
                    <div class="col-md-8">
                        <select class="form-control" name="subject_code" id="subject_code">
                            <option value="{{ $enrollment->no_of_units }}">{{ $enrollment->no_of_units }}</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->no_of_units }}">{{ $subject->no_of_units}}</option>
                            @endforeach 
                        </select>
                    </div>

                </div>
                <div class="form-group">
                    <div class="col-md-7 col-md-offset-3">

                        <button type="submit" class="btn btn-success">
                            <i class="fa fa-save"></i>
                            &nbsp;Save Changes
                        </button>

                        <button type="submit" class="btn btn-danger">
                            <i class="fa fa-times-circle"></i>
                            &nbsp;Delete
                        </button>
                    </div>
                </div>                                                                              
{!! Form::close() !!}

Here's my EnrollmentController:

    public function update(EnrollmentRequest $request, $id)
{
    $enrollment = Enrollment::findOrFail($id);
    $enrollment->update($request->all());
    return redirect('/enrollment');
}

routes.php

// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

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

Route::resource('enrollment','EnrollmentController');



via Chebli Mohamed

Auth::user() is null after user Creation :: Laravel 5.2

I have a Route like below.

Route::group(['middleware' => ['web', 'auth']], function() {
   Route::get('/My', array('uses' => 'AccountController@MyAccount', 'as' => 'Profile')); 
});

We have a file with the name of RegisterUser.php at this Path:

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

After creating the user, redirecting user to a below Url

http://localhost/public/My

My code is like below.

public function register(RegisterRequest $request)
{
    Auth::guard($this->getGuard())->login($this->create($request->all()));
    //print_r(Auth::user());//Auth::user() is Not Null here
    //die();
    return \Redirect()->route('Profile');
}

but this always send user to Login Page. I also checked in Controller Action and Auth::user() is null

public function MyAccount() {
    echo '<pre>';
    print_r(\Auth::user()); //It shows null value
    echo '</pre>';
    die();
    return View("Account.Profile");
}

Am I missing something ?



via Chebli Mohamed

How to stop bootstrap modal from closing after authentication fail in laravel 5.1?

I have a bootstrap modal for login but when ever it fails it redirects to auth/login and the modal closes. So how would I stop the modal from closing when the authentication fails and how will I stop it from redirecting back to auth/login?

My login form:

<form action="{{ URL::to('auth/login')}}" method="POST">

{!! csrf_field() !!}

<div class="left-form__form">
    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="mdl_email" name="email">
        <label class="mdl-textfield__label" for="mdl_email">Email ID</label>
    </div>
    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="password" id="mdl_password" name="password">
        <label class="mdl-textfield__label" for="mdl_password">Password</label>
    </div>
    <div class="left-form__form--bottom">
        <button type="submit" class="btn-style1 mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--accent">
            login
        </button>
        <a href="javascript:void(0);" class="fgt-pwd">forgot password?</a>
    </div>
    <a href="#" class="register-link">New to srsgrocery? <span>SIGNUP</span></a>
</div>
</form>

The modal :

@if(Auth::guest())
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 top-right">
        <span class="call-icon"></span>
        <span class="call-text">Call to Order: 1800-419-2777</span>
        <a href="" title="" class="login" data-toggle="modal" data-target="#loginRegisterModal">Login |</a>
        <a href="" title="" class="register" data-toggle="modal" data-target="#loginRegisterModal">Register</a>
    </div>
    @else
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 top-right">
        <span class="call-icon"></span>
        <span class="call-text">Call to Order: 1800-419-2777</span>
        <a href="{{URL::to('myaccount')}}">My Account </a>                        
        <a href="{{URL::to('auth/logout')}}">Logout</a>
    </div>
@endif



via Chebli Mohamed

mercredi 27 janvier 2016

php artisan not responding after upgrading laravel 5.1 to 5.2

php artisan not responding after upgrading laravel 5.1 to 5.2.

I followed the upgrade guide here http://ift.tt/1ZUwpUI

Even composer update gives an error at

Generating autoload files
> php artisan clear-compiled
Could not open input file: artisan
Script php artisan clear-compiled handling the post-update-cmd event returned with an error


  [RuntimeException]
  Error Output:

What might be the problem?



via Chebli Mohamed

Split Database column value

I'm fetching data from database. I'm saving my data in string format like this

23,32

while fetching data from database my output is like

[{"transaction_id":"28,34"}]

but i want the out put in this format

[{"transaction_id":"28"},{"transaction_id":"34"}]

I'm not able to find the proper solution



via Chebli Mohamed

How to make Laravel 5 redirect to Angular routes without the hash (#)?

I am using Laravel 5 with Angular.

By default Angular add /#/ to the URL.

I don't like that /#/ so I removed it using $locationProvider.html5Mode(true); from Angular.

Now whenever I try to visit an Angular URL, Laravel refuse to redirect me and instead it causes an error NotFoundHttpException saying:

Sorry, the page you are looking for could not be found.

NotFoundHttpException in RouteCollection.php line 161:

And this is very logical because the route is not defined in the Laravel's route file.

How to solve this?!

More Details:

  • When I visit http://ift.tt/1npFV65 everything works fine (laravel knows it's Angular route and then Angular get rid of the # so the URL become http://ift.tt/1SLoKJc without an error).
  • When I visit http://ift.tt/1SLoKJc Laravel display the error NotFoundHttpException.


via Chebli Mohamed

Laravel Eloquent display group data

How do I group and display same column values if I have this kind of table results in my database using Laravel Eloquent.

ID | ITEM | QTY
1  | 123  | 5
2  | 123  | 6
3  | 456  | 2
4  | 678  | 8

and the results will be :

ID | ITEM | QTY 
1  | 123  |  5
   | 123  |  6
2  | 456  |  2
3  | 678  |  8    


via Chebli Mohamed

How to delete multiple records using Laravel Eloquent

Now this, from what I can see, should have been simple.

I want to be able to delete multiple records from the database. I have the id's of all the records I wish to delete. I call the resource.destroy route using comma separated list of ids (id is of postgres type uuid), like so:

Request URL:http://ift.tt/20taZ3g
Request Method:DELETE

On the other end, my controller action looks like so:

public function destroy($id)
{
    try {
        $ids = explode(",", $id);
        $org->products()->find($ids)->delete();
    }
    catch(...) {
    }
}

This gives me the following error:

BadMethodCallException in Macroable.php line 81:
Method delete does not exist.

in Macroable.php line 81
at Collection->__call('delete', array()) in ProductsController.php line 251
at Collection->delete() in ProductsController.php line 251
at ProductsController->destroy('62100dd6-7ecf-4870-aa79-4b132e60c904,c4b369f1-d1ef-4aa2-b4df-b9bc300a4ff5')

I have verified that find() is returning a collection of products matching the specified ids.

What am I missing?

PS: 1. The model Product has several belongsTo relationships with other models. 2. The product.destroy code works fine if I pass it a single id



via Chebli Mohamed

Request validation allways passes on Laravel using Dingo/Api

I'm using dingo/api package.

Controller:

public function register(RegisterUserRequest $request)
{
    dd('a');
}

And for example the email field is required:

<?php namespace App\Http\Requests;


class RegisterUserRequest 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 [
            'email' => 'required'
        ];
    }
}

So I send a request without the email, and still getting the "a" response.

I also tried to extend Dingo\Api\Http\Request instead of App\Http\Request, but still the same.



via Chebli Mohamed

Laravel - Setting session variables when using Basic Auth

I'm implementing an API so that clients can access our system. I'm currently using Auth Basic for authentication. Is there a way for me to set additional session variables when they authenticate this way?

There are session variables we usually set when they log in from the login page, and so there is functionality that depends on those values. So I'll need a way to set those same variables, but when using the Auth Basic middleware.



via Chebli Mohamed

Retriving old values with many-to-many association

I usually use old function at my view files to retrieve old values when editing an entity. For example:

    {!! Form::model($shop, [
'action' => ['ShopController@update', 
$shop->id], 
'method' => 'patch']) !!}
            {!! Form::text('name', old('name')) !!}
            {!! Form::submit('Save', array('class' => 'btn')) !!}
    {!! Form::close() !!}

This works fine to simple fields, but this does not seem to work with 'many to many' (belongsToMany) relations. Supposing that a relation of this kind results in an array of objects, how can I retrieve them in the view without generating a lot of code?

I was thinking something like this, in a multiselect, for a shop that has a many-to-many relation with products:

{!! Form::select('products[]', $allProducts, old('products[]')) !!}

This does not seem to work because there are no products in the model, but through a relation model like: ShopProduct.

Anyone know a clever way to do this?



via Chebli Mohamed

Laravel 5.1 create not working

I am new in larval and I am learning Laravel 5.1 .I'm watching a tutorial video and in video teacher is using this code to insert data in database :

<?php

namespace App\Http\Controllers;

use App\comments;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CommentController  extends Controller
{
    public function getCommentNew()
    {
        $data = array(

            'commenter' => 'soheil' ,
            'comment  ' => 'Test content' ,
            'email'     => 'soheil@gmail.com' ,
            'post_id'   =>  1 ,
        ) ;
        comments::create( $data );
    }


}

I am doing the steps like him but I have a problem , all fields ecept created_at and updated_at will be empty like this :

enter image description here

this is my comments model :

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
    protected $fillable = ['commenter,email,post_id,comment,approved'];
    public function post(){
        return $this->belongsTo('App\posts');
    }
}

and this is migration :

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCommentsTable extends Migration
{
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedinteger('post_id');
            $table->string('commenter') ;
            $table->string('email') ;
            $table->text('comment') ;
            $table->boolean('approved');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('comments');
    }
}



via Chebli Mohamed

laravel 5.1 character error request

I've a problem whem I request the name of the input text form. My $request->input('name'); return the text with a character error.

Artist name: Aláfia

Blade template:

<form action="artist" method="POST" name="form-artist" id="form-artist" enctype="multipart/form-data">
   <input type="text" name="name" id="name" />
   <input type="file" name="image" id="image" multiple="multiple">
</form>

Controller:

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

Result: Aláfia

The charset of the file and html is correct (utf-8). Someone can help me?



via Chebli Mohamed

Laravel blade dynamic directory

I am working on a modular structure such as below

modules
    module
        controllers
        models
        views

However I am struggling to figure out how to load views from a dynamic directory, for instance there could be 20 different modules each one loading views from their own directory, is this possible with the way blade renders templates at the moment?



via Chebli Mohamed

Laravel 5.1: How to set Route for update record

I am new in laravel. I am working with laravel 5.1

I am stuck into routing of laravel. I used Form/Html for insert/update. But i stuck in routing of update record.

Here is route for redirect to edit page in routes.php

Route::get('/company/edit/{id}','CompanyMasterController@edit');

In my CompanyMasterController.php

public function edit($id)
   {
      $company = CompanyMasters::find($id);

      return view('companymaster.edit',  compact('company'));
   }

My action in edit.blade.php

{!! Form::model($company,['method' => 'PATCH','action'=>['CompanyMasterController@update','id'=>$company->id]]) !!}

and rout for this action in routes.php

Route::put('/company/update/{id}','CompanyMasterController@update');

My controller action for update.

public function update($id)
   {
        $bookUpdate=Request::all();
        $book=  CompanyMasters::find($id);
        $book->update($bookUpdate);
        return redirect('/company/index');
   }

Now when i click on submit button i gives me

MethodNotAllowedHttpException in RouteCollection.php

I don't know what's going on. can anyone helps me.



via Chebli Mohamed

not getting image file ,getting only name of file

i am uploading images /files on upload multiple image but it only shows image name not their mime type using java script

<input type='file' name='data[Expensedetail][description]["+i+"][expense_file][]' id='expense_file"+i+"' style='display: none' multiple='true'>

where 'i' is value of array coming in loop i = 0,1,2,3 ... everything works fine and i am getting this result on post [images details][1]

[1]: http://ift.tt/1TnkXRR and using

$finfo = finfo_open(FILEINFO_MIME_TYPE);
 echo finfo_file($finfo, $file); //$file is the file name coming in above image in array
echo $file;

failed to open stream: No such file or directory



via Chebli Mohamed

How to make Request default in Laravel 5.1 when none is given

I am using Laravel 5.1 and I need to make a default value when in field is none given.

So the view looks like:

<form name="search" method="POST" action="/s">
    Country<input name="country" type="text">
    Field<input name="field" type="text">
    <button type="submit" type="button">Search</button>
    <input name="_token" value="{{ csrf_token() }}" type="hidden">
</form>

The controller looks like:

public function extendedPost(Request $request){
        $data = $request->all();
        $request->input('field', 'Random');
        dd($data);
}

In Laravel 5.1 Documentation we have:

You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request:

$name = $request->input('name', 'Sally'); http://ift.tt/1nndB44

So when I have something in "Field" I have:

array:21 [▼
  "country" => ""
  "field" => "dddd"
  "_token" => "XeMi"
]

But when the "Field" is empty I have

 array:21 [▼
      "country" => ""
      "field" => ""
      "_token" => "XeMi"
    ]

Instead of

 array:21 [▼
      "country" => ""
      "field" => "Random"
      "_token" => "XeMi"

Thanks for helping me



via Chebli Mohamed

Laravel 5.1 - Update name for current entry, must be unique to current User ID

I've got this code below in my GeckoRequest file. It works for the most part, however if I try to update an entry and keep the name as it is currently it fails saying that the name needs to be unique... Which it is as no other entries have this name apart from the current entry loaded in the edit form.

What is the best thing for me to do to check that the name is unique for the current user but also allow me to update the same entry without changing the name?

public function rules()
{
    switch($this->method())
    {
        case 'GET':
        case 'DELETE':
        {
            return [];
        }
        case 'POST':
        {
            return [
                'morph' => 'required',
                'sex' => 'required',
                'genetics' => 'required',
                'name' => "required|unique:geckos,name,NULL,id,user_id," . \Auth::user()->id
            ];
        }
        case 'PUT':
        case 'PATCH':
        {
            return [
                'morph' => 'required',
                'sex' => 'required',
                'genetics' => 'required',
                'name' => "required|unique:geckos,name,NULL,id,user_id," . \Auth::user()->id
            ];
        }
        default:break;
    }
}



via Chebli Mohamed

mardi 26 janvier 2016

Deploying a Laravel App on Azure

I am having a problem deploying my laravel 5.1 app, i don't have a customized deployment script... I already added the web.config file as specified in this tutorial

I have already installed composer. I already increased the composer timeout to 2000. The problem is that until now the deployment is still loading and it has been hours passed.

i'm using azure web app service.



via Chebli Mohamed

Unencrypted cookie in Laravel

I need to read a cookie in JS set by my Laravel app. Is there a way to do this in Laravel (as opposed to setting it directly through PHP) without overriding classes?



via Chebli Mohamed

How to make dynamic fields from user input in laravel?

i'm having a lost here when i want to make dynamic fields based on user input. for example this is the field to receive user input to create a blank field:

 {!! Form::open(array('url' => 'home')) !!}
    <div class="form-group">
        {!! Form::label('n', 'Parameter') !!}
        {!! Form::number('n', null, ['class' => 'form-control', 'placeholder' => 'How Many Parameter to create ?']) !!}
    </div>
    {!! Form::submit('Submit', ['class' => 'btn btn-primary']) !!}
    {!! Form::close() !!}

after submitting. there should be a blank fields as many as the input above. i've searched some reference, but there isn't much further information about the code that i can get. and i'm in a dilema. i'm hoping for a help. thankyou



via Chebli Mohamed

Laravel / Cartalyst Sentinel Authentication not detecting the user as logged in

I'm on Laravel 5.1 using Cartalyst's Sentinel as my authentication system. I'm using angular on my front-end.

I have a form at http://domain.com/login that sends a POST request to api.domain.com/login. If the user has entered correct credentials api.domain.com/login returns {'success': true} which my front-end looks at and eventually forwards to http://ift.tt/10RfXwH

This is where the problem arises. The relevant portion of my dashboard controller:

if( Sentinel::check() ) {
    return view('dashboard');            
} else {

    return redirect()->route('login');
}

is not detecting the user as logged in. And keeps sending me back to domain.com/login

I suspect this is happening because the logging in part is happening at api.domain.com and we're checking to see if the user is logged in at domain.com and the browser isn't sending the relevant sentinel cookies. The Sentinel docs doesn't mention anything about this.

If my suspicions are correct how can I allow Sentinel authenticate a user for both api.domain.com and domain.com? If my suspicions aren't correct, what is happening here?



via Chebli Mohamed

Eloquent best way to deal with unpublished content

I'm trying to deal with a case where the columns in one of my tables have a status, which is either draft or published.

Is there an easy way to specify somehow in the model that it should only get the published ones by default?

It would be great if I could get the drafts too with some condition.



via Chebli Mohamed

Laravel 5.1 - DRY Create/Edit form when using a JSON object

I have a create form and edit form that incredibly similar, in fact there is only one key difference between them and this is where I need some help.

I want to extract the form into a partial so that I'm not repeating myself with it however I have a bit of an issue.

I'm saving a genetics array (genetics[]) to my DB as a JSON object, it can look like below for example:

{
    "Bell-Albino":"BA",
    "Rainwater-Albino":"na",
    "Tremper-Albino":"na",
    "Murphys-Patternless":"mp",
    "Eclipse":"EC",
    "Marble-Eye":"na",
    "Blizzard":"b",
    "Mack-Snow":"na",
    "Super-Snow":"SS",
    "Gem-Snow":"na",
    "TUG-Snow":"na",
    "Line-Bred-Snow":"na",
    "Enigma":"EN",
    "White-and-Yellow":"WY",
    "Wildtype":"na",
    "Giant":"na"
}

Below is an extract of code for the Bell-Albino field to show you how the rest of them are set up in the create view. I have to set the key for the value. Upon submission with errors, the Request::old() does what it needs to do and retains the value absolutely fine. This works fine and isn't broken:

<label for="genetics">Bell Albino</label>
<?php $options = array('na' => 'N/A', 'BA' => 'Visual', 'ba' => 'Recessive'); ?>
{!! Form::select(
    'genetics[Bell-Albino]', 
    $options, 
    Request::old('genetics[Bell-Albino]'), 
    array('class' => 'form-control')) 
!!}

And similarly, here is the same bit of code from the edit view. Once again, this works fine but it isn't DRY which is what concerns me.

<label for="genetics">Bell Albino</label>
<?php $options = array('na' => 'N/A', 'BA' => 'Visual', 'ba' => 'Recessive'); ?>
{!! Form::select(
    'genetics[Bell-Albino]', 
    $options, 
    $genetics[0]['Bell-Albino'], 
    array('class'=>'form-control')) 
!!}

In order for the genetics array values to be shown/displayed/selected properly when the page loads I had to json_decode my field value into a different array like this above my form:

<?php $genetics[] = json_decode($gecko->genetics, true); ?>

For those interested, so you know how the decoded object looks, this is the dump of $genetics:

array:1 [▼
  0 => array:16 [▼
    "Bell-Albino" => "BA"
    "Rainwater-Albino" => "na"
    "Tremper-Albino" => "na"
    "Murphys-Patternless" => "mp"
    "Eclipse" => "EC"
    "Marble-Eye" => "na"
    "Blizzard" => "b"
    "Mack-Snow" => "na"
    "Super-Snow" => "SS"
    "Gem-Snow" => "na"
    "TUG-Snow" => "na"
    "Line-Bred-Snow" => "na"
    "Enigma" => "EN"
    "White-and-Yellow" => "WY"
    "Wildtype" => "na"
    "Giant" => "na"
  ]
]

Now from the 2 pieces of code above you can see that the only real difference is where I'm using Request::old(). Is there any way to achieve a DRY way of using this form with a JSON object?



via Chebli Mohamed

Validation rules work with html form, but not with phpunit test

I wrote a test class for my api to check if everything is still working. But at one point it fails:

//post exam
$this->post('modul/foo/exam', [
    'date' => '01-01-2016'
])
    ->assertResponseStatus(200);

//post exam again
$this->post('modul/foo/exam', [
    'date' => '01-01-2016'
])
    ->assertResponseStatus(422);

I have a validation rule for date

'date' => 'date:required|unique:exams,date,NULL,id,modul_id,' . \Route::input('modul')->id,

it says that you can only create one exam for a date for one modul. When I echo out the id i get 1 on both cases.

But when I test the second test returns 200, not 422.

The rule works perfectly when I use it with my html form, so is there something special by testing?



via Chebli Mohamed

Laravel 5.1 - Overloaded routes

I have a homegrown, Laravel 5.1 base application on top of which I build specific applications. The base application uses a named route for login, naturally called "login", which listens for GET /login.

In one of my specific applications, I attempted to overload that route to send the requests to a different controller. It seemed to work for a while, but then it started going to the base application's controller again. I'm sure I changed something to break it, but the problem is that I can't figure out how to fix it again.

My base application routes are all defined in app/Http/Routes/core.php. The relevant route:

Route::get('login', [
    'as' => 'login',
    'uses' => '\MyVendor\Core\Http\Controllers\AuthController@getLogin'
]);

My specific application routes are defined in app/Http/Routes/application.php. The relevant route:

Route::get('login', [
    'as' => 'login',
    'uses' => 'App\AuthController@getLogin'
]);

My app/Http/routes.php adds these routes like this:

require 'Routes/application.php';
require 'Routes/core.php';

No matter which order I require those files, the core route is the one that goes into effect.

My goal is to have the routes defined in 'Routes/application.php' take precedence over any "conflicting" routes in 'Routes/core.php'. Is this possible? How?

EDIT: I just switched this back to have 'core.php' required first, and now the request is going to the right controller. I'm positive this wasn't working a minute ago...

EDIT 2: This is actually a multi-site instance of Laravel 5.1. I have multiple 'application.php' routes files, one for each domain. They were being required inside of a domain route block. Because the 'core.php' routes were needed for each site, that file was required outside of the domain blocks. When it is included inside of the domain block, everything works as expected, i.e. the most recent definition for a route is the effective route. Does this behavior sound like a bug? Can anyone explain why it behaves this way?



via Chebli Mohamed

Laravel : Display the data in a table

I have a form this form is for the employees and each employee have a payment for each year,the admin should fill the data and save it, also the previous data should be filled on the right place on the form otherwise if there is no data the input field should be empty, here is what should data look like :

enter image description here

but what I get is this: enter image description here

MY CODE : Controller

$years = Year::with('employeeData')->get();

    $indicators = Indicator::all();
 return view('sustainability-data.input-data', compact('years', 'indicators'));

View

@foreach($employees as $index=>$employee)
                    <tr>
                        <td>{{$employee->name}}</td>
                        @foreach($years as $year)
                            <td>
                                @foreach($year->employeeData as $datum)
                                        @if($datum->employee_id == $employee->id)
                                            {!! Form::text('row[$index][value]' ,$datum->value,['class' => 'form-control']) !!}
                                        @endif

                                @endforeach
                            </td>
                        @endforeach

anyone have an idea how to solve this before I lose my mind , I tried many ways but I failed to solve this problem



via Chebli Mohamed

Cannot read property 'hasTime' of undefined

I'm using FullCalendar to display staff hours on a Calendar.

I'm pulling the events via an ajax call like so:

"events": function(start, end, timezone, callback) {

  //create the data to be sent
  var objectToSend = {
    "start_date": start.format("YYYY-MM-DD"),
    "finish_date": end.format("YYYY-MM-DD"),
  };

  //craft and make the request
  $.ajax({
    url: 'calendar/test',
    data: objectToSend,
    type: 'POST',
    cache: false
  }).done(function(data) {
    //on success call `callback` with the data
    callback(data)
  })
}

This works perfectly fine, however I am getting an error showing in my console "Uncaught TypeError: Cannot read property 'hasTime' of undefined" and that this is coming from fullcalendar.min.js:6.

I'm not very fluent in JavaScript, but my searching suggests that I either haven't provided the right dates or have junk data in there.

As far as I can tell I am providing all the right data. The function generating the data looks like so:

public function test(Request $request) {
  $start_date = Input::get('start_date');
  $finish_date = Input::get('finish_date');

  $shifts = Roster::whereBetween('date', array($start_date, $finish_date)) - > get();

  foreach($shifts as $shift) {
    $start = $shift - > date.
    ' '.$shift - > start_time;
    $finish = $shift - > date.
    ' '.$shift - > finish_time;

    $events[] = array(
      'title' => $shift - > staff - > first_name,
      'start' => Carbon::createFromFormat('Y-m-d H:i:s', $start) - > toDateTimeString(),
      'end' => Carbon::createFromFormat('Y-m-d H:i:s', $finish) - > toDateTimeString(),
      'id' => $shift - > id,
      'allDay' => false
    );
  }

  return json_encode($events);
}

which outputs:

[{"title":"Gemma","start":"2016-02-01 18:00:00","end":"2016-02-01 22:00:00","id":1,"allDay":false},
{"title":"Gemma","start":"2016-01-26 18:00:00","end":"2016-01-26 22:00:00","id":49,"allDay":false}]

Can anyone spot what I am doing wrong? I am simply trying to use this to render my events for the given month.

Edit: output of console.log(data)

It prints out:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

Opening this up I get:

0: Object

Opening this up I get:

allDay: false
end: "2016-02-01 22:00:00"
id: 1
start: "2016-02-01 18:00:00"
title: "Gemma"



via Chebli Mohamed

lundi 25 janvier 2016

Laravel ORM - Custom GroupBy Month JSON Response

I currently I have a model like this-

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserSlidePhoto extends Model
{
    protected $table="users_slides_photos";
    protected $fillable=['user_id','social_image_id','original_image_name','provider_key','provider_id','thumbnail_name'];

    public $timestamps = true;

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

And a controller like this-

public  function rearrangePhotoMonth(Request $request)
{
    //$ordering = $request->input('ordering');
    $thumbs = url('/uploads/userfiles/thumbs/')."/";
    $images = url('/uploads/userfiles/images/')."/";
    return UserSlidePhoto::where('user_id', Auth::id())
                  ->selectRaw(
                                "id,
                                CONCAT('".$thumbs."',thumbnail_name) AS thumbnail_url,
                                CONCAT('".$images."',original_image_name) AS original_image_url"
                              )
                  ->get();
}

And I am getting JSON response like this-

[
  {
    "id": 2,
    "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-YgLYcr5DsB3kHjpa7cxcznjiEFdzeF.png",
    "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-YgLYcr5DsB3kHjpa7cxcznjiEFdzeF.png"
  },
  {
    "id": 4,
    "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-A7rlDeFmMybmXNUtcxKyEtzM9TPywq.png",
    "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-A7rlDeFmMybmXNUtcxKyEtzM9TPywq.png"
  },
  {
    "id": 1,
    "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-Xfvn6b8rnE4loZjZOlv14c0FZYVT3A.png",
    "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-Xfvn6b8rnE4loZjZOlv14c0FZYVT3A.png"
  },
  {
    "id": 7,
    "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-aZa54HnAqwY2DPMlSVI2UpbRohVTlY.png",
    "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-aZa54HnAqwY2DPMlSVI2UpbRohVTlY.png"
  }
]

But I like to get response like this-

[
  {
    "month": "January 2015",
    "data": {
      {
        "id": 6,
        "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-WujsXF8iNSuwxQX4QRebKkOqFinlJV.png",
        "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-WujsXF8iNSuwxQX4QRebKkOqFinlJV.png"
      },
      {
        "id": 8,
        "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-VcgQcjoi0iXM2YOqhgt0fYUZf8kwsE.png",
        "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-VcgQcjoi0iXM2YOqhgt0fYUZf8kwsE.png"
      },
      {
        "id": 5,
        "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-r6jxeFfV7nnLrMxO5l88sC7Pt0Xq1A.png",
        "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-r6jxeFfV7nnLrMxO5l88sC7Pt0Xq1A.png"
      }
    }
  },
  {
    "month": "March 2015",
    "data": {
      {
        "id": 2,
        "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-YgLYcr5DsB3kHjpa7cxcznjiEFdzeF.png",
        "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-YgLYcr5DsB3kHjpa7cxcznjiEFdzeF.png"
      },
      {
        "id": 9,
        "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-ivnXQ5ZA1y2mVVxcRtmH3UFd41Xdg3.png",
        "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-ivnXQ5ZA1y2mVVxcRtmH3UFd41Xdg3.png"
      }
    }
  },
  {
    "month": "January 2016",
    "data": {
      {
        "id": 3,
        "thumbnail_url": "http:\/\/localhost:8000\/uploads\/userfiles\/thumbs\/2-NfMq71wghF7Al3Fn4KS3SG9ylC4ayo.png",
        "original_image_url": "http:\/\/localhost:8000\/uploads\/userfiles\/images\/2-NfMq71wghF7Al3Fn4KS3SG9ylC4ayo.png"
      }
    }
  }
]

Can anyone please help?



via Chebli Mohamed

JWT Token Expiry inconsistent

I'm still new to laravel, api, as well as JWT. Is there anyone using tymon jwt?

I have been troubling with the Token Expiry. When ever it gets expired, it shows 2 different kinds of errors. Usually, it is just plainly {message: "token_expired"} with a status code of 401, which is fine. But, sometimes it shows up this kind of error, wherein it says it comes from a PayloadValidator, and which I could not trap where I can trigger this. It is a problem for me because its status code is 500 and our frontend developers do not want status code 500.

I would like to make it 400, or rather just have a consistent error response Is there anyone here could help me understand why there 2 kinds of error? How were these encountered?

Inconsistent TokenExpiry Response



via Chebli Mohamed

Fatal error: Class 'Artisaninweb\SoapWrapper\ServiceProvider' not found

how to fix this problem in laravel 5.1. Did I forgot something in following this steps http://ift.tt/WwvM9R . Also I'm a little bit confused where to put this register class alias:

class_alias('Artisaninweb\SoapWrapper\Facades\SoapWrapper', 'SoapWrapper');

Thanks! :)



via Chebli Mohamed

Laravel 5.1 Session not working

i have Session in my Controller store

public function store(Request $request)
{
\Session::push('store_pos.items',$request->all());
print_r(\Session::get('store_pos.items')); // This is show array
exit;
}

public function create()
{
$items = \Session::get('store_pos.items');
print_r($items); // in this syntax not show array
}

why session in function create not show ? I've been using the session put but still does not appear

Thanks



via Chebli Mohamed