mercredi 30 septembre 2015

Overridden core class does not work when in artisan

In a fresh Laravel build, I cannot get overridden IoC bindings to work everywhere in the application.

Suppose a service provider that overrides a core class, e.g. cache:

class NewServiceProvider extends ServiceProvider
{
    protected $defer = true;

    public function register()
    {
        $this->app->bind('cache', function($app) {
            return new \stdClass; // demo purpose
        });
    }

    public function provides()
       {
        return ['cache'];
    }
}

The provider is then added at the bottom of app.providers config.

Now modify routes.php to the following and go check the result:

Route::get('/', function () {
    dd(app('cache'));
});

// Results in an empty stdClass being shown. It works!

However, fire up artisan tinker and do the same:

$ php artisan tinker
>>> app('cache')
=> Illuminate\Cache\CacheManager

Suddenly the override isn't working anymore...

The same behavior is encountered when processing event listeners...

Is this normal behavior and am I overlooking something? Or is this some kind of bug?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1GjjyCp
via IFTTT

Cache entire HTML response in Laravel 5

I am trying to cache entire response using middleware

Steps i followed

Generated two middleware

  • AfterCacheMiddleware
  • BeforeCacheMiddleware

With in BeforeCacheMiddleware:

public function handle($request, Closure $next)
{            
        $key = $request->url();
        if(Cache::has($key)) return Cache::get($key);
        return $next($request);
}

With in AfterCacheMiddleware

public function handle ($request, Closure $next)
{       
    $response = $next($request);
    $key = $request->url();       
    if (!Cache::has($key)) Cache::put($key, $response->getContent(), 60);
    return $response;
}

Registered middleware in $routeMiddleware array of kernal.php

'cacheafter' => 'App\Http\Middleware\AfterCacheMiddleware',
'cachebefore' => 'App\Http\Middleware\BeforeCacheMiddleware',

With in routes.php i am calling this dummy routes like this

Route::get('middle', ['middleware' => 'cachebefore', 'cacheafter', function()
{
    echo "From route";
}]);

Issue:

only cachebefore middleware is getting called. cacheafter is not getting called at all

Can anyone suggest what i am missing here ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1O9qERP
via IFTTT

How do I build a dynamic ranking system ?(Laravel-5)

I'm trying to build a ranking system that allows users to go up in rank by accumulating points. Is it possible to update the rankings upon user ranking up immediately? How can I do this if I account for several hundred users hitting the database at the same time?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1hcBaJw
via IFTTT

Undefined property: stdClass::$**** in One to Many Relationships Laravel 5

I am new to Laravel and I am creating a Laravel5 project where the Voters is related to a City in one to many relationships: every voter has only one City while City has many voters

My Table looks like this

//voters

Id Name City_id

//city

Id Name 

And inside App/Models

//city.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
/**
*The table associated with the model
*
*/
protected $table = 'city';

/**
* indicates if the model should be timestamped
* @var bool
*/

public $timestamps = false;

 public function voters()
 {
    return $this->belongsTo('App\models\Voters');
 }
}

voters.php

 <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Voters extends Model
{
 protected $table = 'voters';

 public function city()
 {
    return $this->hasMany('App\Models\City');
 }
}

I can accessed all voters in the controller this way

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class VotersController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
  public function index()
  {
     $voters = DB::table('voters')->get();
     return view('voters.all_voters',['voters' => $voters] );
  }
 }

But the problem is the voter's city return an error

Undefined property: stdClass::$city (View: .....

The blade template

<div class="table-responsive">
<table class="table table-hover table-bordered table-condensed">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Profession</th>
            <th>City</th>
            <th>Province</th>
            <th>Region</th>
            <th>Island</th>
        </tr>
    </thead>
    <tbody>
        @foreach($voters as $voter)
        <tr>
            <td>{{ $voter->firstname }}</td>
            <td>{{ $voter->birthday }}</td>
            <td>{{ $voter->profession_id }}</td>
            <td>{{ $voter->city->name }}</td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        @endforeach
    </tbody>
</table>

How to properly display related field for this kind of relationships in Laravel?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LRameC
via IFTTT

Create using save() is causing database duplicates in Laravel

I have very similar code that is functioning without a hitch elsewhere in my Laravel app, but for some reason the below code is creating two $paypal_object database entries that are identical except for the payment_id field:

DonateController.php

public function mimic()
{
    try {
        //This block is the addOrder function from the pizza tutorial
        $paypal_object = new Paypal();
        //The user who is making the payment
        $paypal_object->user()->associate(Auth::user());
        $paypal_object->amount = 50.00;
        $paypal_object->description = "new subscription";
        $paypal_object->state = $payment->getState();
        $paypal_object->payment_id = $payment->getId();
        $paypal_object->save();
    } catch (Exception $ex) {
        $message = $ex->getMessage();
        $messageType = "error";
    }
    exit;
}

Database Results (with test data) enter image description here

I've condensed the above code from my controller a little. If you'd like to see more of my code, let me know and I'd be happy to provide it. My theory right now is that for some reason my mimic() method is getting run twice, but I'm not sure how to test to see if that's true beyond including this in the above code, but it's not giving me any results this time:

    echo '<script>console.log(' . json_encode("Testing to see how many times this message appears.") . ');</script>';

Even if it is running twice, I'm not sure how that's happening or where to check. I'm guessing it could well be another problem entirely, but I don't know what.

Thanks in advance for any help.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1O3jld2
via IFTTT

Laravel core class override in Service Provider not working in event listeners and Artisan Tinker

I created a service provider that overrides Laravel's Cache:

protected $defer = true;

public function register()
{
    $this->app->singleton('cache', function ($app) {
        return new CustomCacheManager($app);
    });
}

public function provides()
{
    return ['cache'];
}

If I run a call that constructs the cache like Cache:: or app('cache') in a request that outputs to the browser, all works fine and my own implementation of CustomCacheManager is working.

However in event listeners or even in artisan tinker my override isn't working and Laravel's own core class is being used.

Am I doing something wrong here? How can I make the override persistent across the whole application?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KSCCt9
via IFTTT

Laravel routes accepts only specific format

I'm using laravel 5.1 and I would like to know if I could only allow specific route format in my routes.php?

The route format should look like this (strict):

http://ift.tt/1O8KDAk

Wherein 2015-09 is year-month. It should only accept this format (as stated above). Having a different format will only redirect to the homepage. Example:

http://ift.tt/1O8KA7E
http://ift.tt/1QLIZSF
http://ift.tt/1QLJ20H
http://ift.tt/1QLJ20J
http://ift.tt/1QLIZSH

So in my routes I have this:

Route::get('archive/{date}', 'ArchiveController@index');

I saw on the documentation that regular expressions could be used but I'm not sure how would I be able to do it.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QLIZSL
via IFTTT

Unit testing with [Laravel 5]

I would appreciate if someone can show me how can I test this method inside my controller:

class CommentController extends Controller {

    protected $update;

    function __construct(Comment $update) {
        $this->update = $update;
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update(UpdateCommentRequest $request) {
        if (Input::get('task') == 'updateComment') {
            if ($this->update->find(Input::get('id'))
                            ->update(['text' => $request->get('text')])) {
                return json_encode(array('success' => true));
            }
        }
    }

This is update route: /api/project/



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1N2bqxY
via IFTTT

Laravel 5 , submit form doesnt work

i have a problem...

I can't submit a form with laravel , actualy nothing even happens , no errors is shown... Page just stays the same as it was...

This is my route file:

Route::resource('/', 'WebsiteController');

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

This is file with form:

<div class="col-lg-12">
                {!! Form::open(['url' => '/']) !!}
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group wow fadeInLeft">
                            {!! Form::text('name',null,['class'=>'form-control','placeholder'=>'Your name *','id'=>'name']) !!}
                        </div>
                        <div class="form-group wow fadeInLeft">
                            {!! Form::text('email',null,['class'=>'form-control','placeholder'=>'Your email *','id'=>'email']) !!}
                        </div>    
                        <div class="form-group wow fadeInLeft">
                            {!! Form::text('phone',null,['class'=>'form-control','placeholder'=>'Your phone *','id'=>'phone']) !!}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group wow fadeInRight">
                            {!! Form::textarea('message',null,['class'=>'form-control','placeholder'=>'Your message *','id'=>'message']) !!}    
                        </div>
                    </div>
                    <div class="clearfix"></div>
                        <div class="col-lg-12 text-center wow bounceIn">
                            {!! Form::submit('Click Me!') !!}
                        </div>
                </div>    
                {!! Form::close() !!}

                @if ($errors->any())
                <ul class='alert alert-danger' style='list-style: none;'>
                    @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
                @endif
            </div>

This is my CreateContactRequest file:

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateContactRequest 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 [
                    'name'  => 'required|min:3',
                    'phone' => 'required',
                    'email' => 'required|email',
                    'message' => 'required'
    ];
}

}

And finally, this is my store method in WebsiteController:

public function store(CreateContactRequest $request)
{
            $this->createContact($request);

}

Included files on top of the WebsiteController file:

use App\Contact;
use App\Http\Requests;
use App\Http\Requests\CreateContactRequest;
use Illuminate\HttpResponse;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Request;

Any help is welcomed and appreciated,thanks in advance...



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1WyYhOw
via IFTTT

Getting TokenMismatchException in VerifyCsrfToken.php line 53 in CRUD made using appzcoder/crud-generator in laravel 5.1

I've tried many solutions I can found on the stackoverflow and laracast. But my problem is slightly different, I get this TokenMismatchException in VerifyCSrfToken.php exception, but once I refresh the page, this error is gone and I'm able to submit the form properly. This has been happening every time, I fill the form, I get the exception and when I refresh, the error is gone. I'm using LaravelCollective for form generation. I've tried clearing all 3 types of cache. I've also tried adding the line manually, but this doesn't do any good, it actually led to same line twice in code as HTML generator has added this line itself, I removed it, still nothing is working. Here's code of my create.blade.php file.

@extends('layouts.master')

@section('content')

<h1>Contact Us</h1>
<hr/>

{!! Form::open(['url' => 'contact', 'class' => 'form-horizontal']) !!}
<div class="form-group">
                    {!! Form::label('name', 'Name: ', ['class' => 'col-sm-3 control-label']) !!}
                    <div class="col-sm-6">
                        {!! Form::text('name', null, ['class' => 'form-control']) !!}
                    </div>
                </div><div class="form-group">
                    {!! Form::label('email', 'Email: ', ['class' => 'col-sm-3 control-label']) !!}
                    <div class="col-sm-6">
                        {!! Form::text('email', null, ['class' => 'form-control']) !!}
                    </div>
                </div><div class="form-group">
                    {!! Form::label('phone', 'Phone: ', ['class' => 'col-sm-3 control-label']) !!}
                    <div class="col-sm-6">
                        {!! Form::text('phone', null, ['class' => 'form-control']) !!}
                    </div>
                </div><div class="form-group">
                    {!! Form::label('message', 'Message: ', ['class' => 'col-sm-3 control-label']) !!}
                    <div class="col-sm-6">
                        {!! Form::textarea('message', null, ['class' => 'form-control']) !!}
                    </div>
                </div>

<div class="form-group">
    <div class="col-sm-offset-3 col-sm-3">
        {!! Form::submit('Submit', ['class' => 'btn btn-primary form-control']) !!}
    </div>    
</div>
{!! Form::close() !!}

@if ($errors->any())
    <ul class="alert alert-danger">
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
@endif

@endsection



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LQ647h
via IFTTT

Getting TokenMismatchException in VerifyCsrfToken.php line 46: when uploading an image using Elfinder

Im using Laravel 5 with CKEditor and Elfinder to create a WYSIWYG editor in a CMS. Ive got the file browser up and running, but i cant get the file upload to work. I have the upload tab, but when I click Send to Server I get the following:

TokenMismatchException in VerifyCsrfToken.php line 46:

Any ideas why this is happening?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KS2Iwm
via IFTTT

Laravel Token Signature could not be verified

I'm using Laravel/Lumen as an API for the backend of a webapp and run into a hiccup.

In an example I have a route that does not need the user to be authenticated. But I do want to check in the routes controller if the user visiting has a valid token.

So I wrote the following:

    if ($tokenFetch = JWTAuth::parseToken()->authenticate()) {
        $token = str_replace("Bearer ", "", $request->header('Authorization'));
    } else {
        $token = '';
    }

I believe the above will check the Bearer token is valid else it will return a blank variable.

The following is my entire Controller.

public function show($url, Request $request)
    {

        if ($tokenFetch = JWTAuth::parseToken()->authenticate()) {
            $token = str_replace("Bearer ", "", $request->header('Authorization'));
        } else {
            $token = 'book';
        }
        return response()->json(['token' => $token]);
    }

The Problem

If I a pass in a valid Token Bearer, it returns the token but if I pass in an invalid one I get the following error:

TokenInvalidException in NamshiAdapter.php line 62:

Token Signature could not be verified.

If I don't pass a token at all:

JWTException in JWTAuth.php line 195:

The token could not be parsed from the request

Is there a way to check if a token is passed and if it has then check if its valid, but also if one has not been passed then return a blank return?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KS2Ko3
via IFTTT

Accessing object properties in PHP

I am trying to access properties of a custom object in PHP:

<?php

namespace App\Classes;

use Illuminate\Database\Eloquent\Model;

class AED extends Model {

    protected $table = 'aeds';
    protected $fillable = ['owner', 'street', 'postal_code', 'locality', 'latitude', 'longitude', 'annotation_type'];
    public $timestamps = true;

    public $id;
    public $owner;
    public $object;
    public $street;
    public $postalCode;
    public $locality;
    public $latitude;
    public $longitude;
    public $annotation_type;
    public $distance;

    public function set($data) {
        foreach ($data as $key => $value) {
            if(property_exists($this, $key)) {
                $this->$key = $value;
            }
        }
    }
}

The code to access these properties:

<?php
namespace App\Transformer;

use App\Classes\AED;
use League\Fractal\TransformerAbstract;


class AEDTransformer extends TransformerAbstract {
    public function transform(AED $aed) {
        return [
            'data' => $aed->owner
        ];
    }
}

When I call the function, I get this as a response:

{
data: [
{
data: null
}
],
meta: "TestMeta"
}

The strange thing is, when I just var_dump the object I get the full info:

...
 protected 'original' => 
    array (size=11)
      'id' => int 1
      'owner' => string 'Owner 1' (length=7)
      'object' => string 'Object 1' (length=8)
      'street' => string 'Street 1' (length=8)
      'postal_code' => string '11111' (length=5)
      'locality' => string 'Locality 1' (length=10)
      'latitude' => float 100
      'longitude' => float 100
      'annotation_type' => string '1' (length=1)
      'created_at' => string '0000-00-00 00:00:00' (length=19)
      'updated_at' => string '0000-00-00 00:00:00' (length=19)
...

So the data can be taken from the database as expected and is being received as well. Why does the accessing not work then and I receive a "null".

Best



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1O2qx9g
via IFTTT

How to query pivot table using Eloquent in Laravel 5

I have a many-to-many relationship between my client and tag tables. A client can have many tags, and each tag can be related to multiple clients.

On the client show view, i'm trying to display the client info plus all tags associated to this client.

How do I change the query below to retrieve the client row with all its related tags?

public function show($id)
{
    $client = Client::findOrFail($id);

    return view('clients.show')->with(['client' => $client]);
}

Client model

public function clienttag()
{
    return $this->belongsToMany('App\Clienttag');
}

Clienttag model

public function client()
{
    return $this->belongsToMany('App\Client');
}

Client_clientags table migration

public function up()
{
    Schema::create('client_clienttag', function(Blueprint $table)
    {
        $table->integer('client_id')->unsigned();
        $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');

        $table->integer('clienttag_id')->unsigned();
        $table->foreign('clienttag_id')->references('id')->on('clienttags')->onDelete('cascade');

        $table->timestamps();
    });
}   



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1O2f1dZ
via IFTTT

Unti testing ajax, check returned json [Laravel 5 ]

I want to test my controller, I need to see which json returned:

Here is my controller method:

public function update(UpdateCommentRequest $request)
{
        if(Input::get('task') == 'updateComment')
        {
            if(Comment::find(Input::get('id'))
                    ->update(['text' => $request->get('text')]))
            {
                return json_encode(array('success' => true));
            }
        }

}

Here is my test try:

public function testHome()
    {
        $this->be(User::find(1));
        $response = $this->call('PUT', '/api/project/1/comment/1/comments/1', array(
            'text' => 'testjjjjjjjjjjjjjjjjjjjjjjjjjjjj',
            'projectID' => 1,
            'id' => 246,
            'level' => 0
        ));
        dd($response);

Even if my test pass it will not return any content... What is right way to assert if I get succesful ajax request?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KS3nNo
via IFTTT

How can I properly call any math related function in a class/controller?

I tried to use the factorial php build in function gmp_fact() in one of my function in my class/controller.

I keep getting:

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

Does anybody know why ? or How do I fix it ?

How's come I can use other functions like strlen, str_split, and so on ... ?

Do I need to include any kind of Math library or something ?


My Controller

<?php

namespace App\Http\Controllers;
use View, Input, Redirect;

class CodeController extends Controller {

    public function getFactorial($num)
    {
        $fact = 1;
        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;
        return $fact;
    }

    public function codingPuzzle()
    {
        return View::make('codes.puzzle');
    }

    public function codingPuzzleProcess()
    {

        $word     = strtoupper(Input::get('word'));
        $length   = strlen($word);
        $max_value = ($length * 26);
        $characters = str_split($word);

        $num = 1 ;
        $index = 1;

        sort($characters);

        //dd($characters);

        foreach ( $characters as $character) {
            $num += gmp_fact($index) * $index;
            $index ++;


        }

        return Redirect::to('/coding-puzzle')
            ->with('word', $word )
            ->with('num', $num )
            ->with('success','Submit successfully!');

    }


}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1haPuSS
via IFTTT

Call to undefined function App\Http\Controllers\ [ function name ]

In my controller, I create a function getFactorial

public static function getFactorial($num)
{
    $fact = 1;
    for($i = 1; $i <= $num ;$i++)
        $fact = $fact * $i;
    return $fact;
}

Then, I use it like this

public function codingPuzzleProcess()
{

    $word     = strtoupper(Input::get('word'));
    $length   = strlen($word);
    $max_value = ($length * 26);
    $characters = str_split($word);

    $num = 1 ;
    $index = 1;

    sort($characters);

    foreach ( $characters as $character) {
        $num += getFactorial($index) * $index;
        $index ++;
    }

    return Redirect::to('/coding-puzzle')
        ->with('word', $word )
        ->with('num', $num )
        ->with('success','Submit successfully!');

}

For some reason, I keep getting this error

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

Can someone please teach me how to fix this error ?

Much appreciated in advance.


CodeController.php

<?php

namespace App\Http\Controllers;
use View, Input, Redirect;

class CodeController extends Controller {


    public function codingPuzzle()
    {
        return View::make('codes.puzzle');
    }

    public static function getFactorial($num)
    {
        $fact = 1;
        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;
        return $fact;
    }


    public function codingPuzzleProcess()
    {

        $word     = strtoupper(Input::get('word'));
        $length   = strlen($word);
        $max_value = ($length * 26);
        $characters = str_split($word);

        $num = 1 ;
        $index = 1;

        sort($characters);

        foreach ( $characters as $character) {
            $num += getFactorial($index) * $index;
            $index ++;
        }

        return Redirect::to('/coding-puzzle')
            ->with('word', $word )
            ->with('num', $num )
            ->with('success','Submit successfully!');

    }


}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LkarZy
via IFTTT

Laravel Fractal Manager

I wrote a transformer class for outputting data in an API:

APPTRANSFORMER:

<?php
namespace App\Transformer;

use App\Classes\AED;
use League\Fractal\TransformerAbstract;

class AEDTransformer extends TransformerAbstract {
    public function transform(AED $aed) {
        return [
            'owner' => $aed->owner,
            'street' => $aed->street,
            'latitude' => $aed->latitude,
            'longitude' => $aed->longitude,
            'annotationType' => $aed->annotation_type
        ];
    }
}

And a controller method to get the data requested:

CONTROLLER:

// Show specific AED
public function show($id) {
    // Find AED by ID
    $aed = AED::find($id);
    $rawData = $this->respondWithItem($aed, new AEDTransformer);
    $meta = ['meta' => 'TestMeta'];
    $data = array_merge($rawData, $meta);

    if (!$aed) {
        return $this->respondNotFound("AED existiert nicht.");
    }

    return $data;
}

When I call the URL I get the error:

ErrorException in AEDTransformer.php line 16: Argument 1 passed to App\Transformer\AEDTransformer::transform() must be an instance of App\Classes\AED, null given, called in /home/vagrant/Projects/MFServer/vendor/league/fractal/src/Scope.php on line 307 and defined

AED CLASS:

<?php
namespace App\Classes;

use Illuminate\Database\Eloquent\Model;

class AED extends Model {

    protected $table = 'aeds';
    protected $fillable = ['owner', 'street', 'postal_code', 'locality', 'latitude', 'longitude', 'annotation_type'];
    public $timestamps = true;

    public $id;
    public $owner;
    public $object;
    public $street;
    public $postalCode;
    public $locality;
    public $latitude;
    public $longitude;
    public $annotation_type;
    public $distance;

    public function set($data) {
        foreach ($data as $key => $value) {
            $this->{$key} = $value;
        }
    }
}

I think it must be something with the "extends Model" in the AED Class but I do not see the reason why. It is just an extension. Or do I look at the wrong place and understand the message wrongly?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LPbkbj
via IFTTT

How to set headers for forwarded request

My controller's methods require a header to be set, e.g. X-Authorization. After a new object has been created (store action), I do a forward to show the newly created object (show action):

$request = Request::create(route('api.v1.b.show', ['booking' => 4]), 'GET');
Request::replace($request->input());
return Route::dispatch($request);

The forwarding works ok if I disable the authorization check, but it fails otherwise. ie. the header has gone. I would like to copy the request header, which I can get with Request::header('X-Authorization') into the forwarded request. Is it possible?

I have tried without success to do $request->header('X-Authorization', 'xxxxx'). Also tried PHP's header() before the dispatch and didn't work.

Any ideas? Cheers



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1FElA5g
via IFTTT

After updating composer the illuminate/HTML package got uninstalled ,

I updated my composer while trying to install some packages , The composer actually uninstalled everything else and installed some of the packages,

Now when I am doing

php artisan serve 

Its saying illuminate\html\htmlserviceprovider not found .

My composer looks like this

"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "illuminate/html": "~5.0",
         "bestmomo/scafold": "dev-master",
        "guzzlehttp/guzzle": "~5.3|~6.0"
    },

Before the Website was running fine .

Can any one help me out , I tried to reinstall the HTML packages but it says nothing to be downloaded

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JCrSNO
via IFTTT

Laravel 5.1 - AJAX POST is not working

I want to have a AJAX post request. So, what I have one is like it-

$(document).ready(function()
{
    var baseURL = $('meta[name=base_url]').attr("content")+'/';
    var lastClicked = 0;
    var token = $('meta[name=csrf_token]').attr("content");

    $( "#button_yes,#button_no" ).click(function()
    {
        var now = new Date();
        if(now - lastClicked > 10000)
        {
            lastClicked = now;
            console.log('Done');
            $.ajax(
            {
                headers: { 'X-CSRF-TOKEN': token},
                url: baseURL+"add_votes",
                success: function(result)
                {
                    alert(result);
                    console.log(result);
                    console.log(token);
                },
                method: "POST",
                data:
                {
                    _token:         token,
                    uuid : $('meta[name=webniar_ID]').attr("content")
                },
            });
        }
    });
});

So, more specifically-

            $.ajax(
            {
                headers: { 'X-CSRF-TOKEN': token},
                url: baseURL+"add_votes",
                success: function(result)
                {
                    alert(result);
                    console.log(result);
                    console.log(token);
                },
                method: "POST",
                data:
                {
                    _token:         token,
                    uuid : $('meta[name=webniar_ID]').attr("content")
                },
            });

But I am getting a 407 Error

enter image description here

enter image description here

Can anyonehelp me please?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JCbk8t
via IFTTT

Laravel Refreshing JWT tokens

I have a small Lumen / Laravel app that is just used as an API. I am able to sign in and set JWT tokens but after a period of time they timeout, I was expecting them to refresh each time an Endpoint was hit.

I've been looking at the docs for Tymon's JWT-AUTH but I cannot seem to get it to work.

Below is an example of one of my end points which return an array of all the users in the db. But when the token timesout the endpoint returns the error You don't have previleges to view all users

I'd be very grateful if someone was able to advise me or show me how to make my code refresh a token when someone is hitting an endpoint.

Inside Controller

public function index(Request $request)
    {

        $user = JWTAuth::parseToken()->authenticate();

        if(! $user->isAdmin() ) {
            return $this->error_respond(['error' => "You don't have previleges to view all users"]);
        }

        $users = $this->repository->findAllWithPlan();
        return $this->respond(['users' => $users]);
     }

Inside Routes.php

$app->group(['middleware' => 'jwt.auth'], function ($app) {


            /**
             * Show All users
             */
            $app->get('users', ['as' => 'user.all', 'middleware' => 'cors', 'uses' => 'App\Http\Controllers\UserController@index']);



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1N0lbg8
via IFTTT

Swift Mailer with queue in laravel 5 for console command

I am working on Saas application (Developing in Laravel 5) where each saas client has separate database where they can story their own smtp setting in email_setting table. I would like to create console command to queue email and send it. For that if the client A has sending email then mail needs to gone from his smtp setting. Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1O1sump
via IFTTT

How to authenticate user manually from cookie in laravel 5?

I am working on websockets, i am using Rachet. Whenever a user tries to establish a connection, i need to authenticate. My backend uses laravel 5 for all http authentification.

My server code is like this :

    public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) {
       if (null === $request) {
            throw new \UnexpectedValueException('$request can not be null');
       }
       $cookie = $request->getCookie('laravel_session'); 
//do authentification with cookie if possible

I tried to use laravel

Auth::user()

I got following error :

Call to member function user() on null

Whenever i try to connect to websockets from browser, it will use ws protcol and rachets server, so laravel routes are never getting called. Is that the reason i am getting an error when i try to use Auth::user() ?

Can i use that cookie to verify if user is logged in? Is there any other solutions? What will be the security risks involved?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1WxmVz8
via IFTTT

Laravel get wrong table while querying

I try to insert some data to the new table that I have create but laravel choose wrong reverse table. Instead of job_contract get contract_job.

QueryException in Connection.php line 636: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'job.contract_job' doesn't exist (SQL: insert into contract_job (contract_id, job_id) values (2, 4))

I am new in laravel. Is anyone know the way that laravel defines the names of tables



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QKHLXY
via IFTTT

Where to put custom Exception classes in Laravel

What is the best place to put your custom Exception classes in Laravel. I mean that are there some best practices and preferred ways for this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1N0fjDw
via IFTTT

500 Internal Server Error when method PUT in angularjs

PROBLEM

Hello, long time ago I got 500 Internal Server Error when I use method PUT in angularjs (I'm trying to update list name), but still don't know how to fix it and make update work. Please help me.

ERROR

When I'm changed list name and hit enter in console shows error PUT http://localhost/anydo/anydocopy/anydocopy/public/lists/1 500 (Internal Server Error). I checked Network->Preview in google chrome and there shows TokenMismatchException in VerifyCsrfToken.php line 53:. So anybody know where is problem?

CODE

routes.php

Route::group(['middleware' => 'cors'], function () {
    Route::get('tasks', 'TasksController@index');
    Route::get('lists', 'ListsController@index');
    Route::get('lists/{id}', 'ListsController@show');
    Route::post('lists', 'ListsController@store');
    Route::put('lists/{id}', 'ListsController@update');
    Route::post('lists/{id}', 'TasksController@store');
    Route::delete('lists/{id}', 'ListsController@delete');
    });

midleware cors.php

class Cors
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->headers->set(
            'Access-Control-Allow-Headers',
            'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, x-xsrf-token, X-Requested-With'
        );
        $response->headers->set('Access-Control-Allow-Credentials', 'true');
        $response->headers->set('Access-Control-Allow-Methods', '*');
        return $response;
    }
}

controller

public function update($id, CreateListsRequest $request)
{
    $response = Lists::findorfail($id)->update($request->all());

    return Response($response, 201);
}

VerifyCsrToken.php (just because there show error)

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

angular

  $scope.updatel = function($event){
            console.log($event.keyCode);
            console.log($scope.editlist);
            if ($event.keyCode == 13) {
                var list = {
                  name: 'Test'
                };

                $http({
                    method: 'PUT',
                    url: 'http://localhost/anydo/anydocopy/anydocopy/public/lists/1',
                    data: list
                })
                    .success(function () {
                        console.log('true');
                        $http({
                            method: 'GET',
                            url: 'http://localhost/anydo/anydocopy/anydocopy/public/lists'
                        })
                            .success(function (d) {
                                console.log(d);
                                $scope.listsdata = d;
                            });
                    })
                     .error(function () {
                     console.log(list);
                     console.log('false');

                    });

html

 <div ng-repeat="lists in listsdata.lists">
                    <div id="DIV_24" close-on-outside-click="div.popup_information">
                        <button ng-click="lists.show = !lists.show" id="MORE_BUTTON">:</button>
                        <div class="popup_information" ng-show="lists.show">
                                <button id="DELETE_BUTTON" ng-click="del_list(lists)">X</button>
                                <button id="EDIT_BUTTON" ng-click="edbut.show = !edbut.show">E</button>
                        </div>
                        <input type="text" id="edit" ng-model="editlist" ng-show="edbut.show" ng-keydown="updatel($event)" onkeydown="hideshow(document.getElementById('edit'))" class="form-control" style="font:24px bold;" value="{{lists.name}}" />
                        <a href="#/{{lists.id}}">
                            <div id="DIV_25">
                                <label class="test" style="font-weight: normal" ng-show="!edbut.show" close-on-outside-click="test">{{lists.name}} </label>
                            </div>
                            <div id="DIV_26">
                            </div>
                        </a>
                    </div>

                </div>

I know that mby too much code, but I don't understand how to fix this error and where I did mistake, so I just give you all code I'm working with. If need any other code, please ask in comments.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QKCLm7
via IFTTT

Laravel 5 setting route parameter from middleware

The problem: I'd like to resolve slugs, if a slug has been used as a route parameter instead of an id.

Attempted Solution: I'm currently getting a parameter from the request in my middleware and trying to set it back to the request. But it seems that this isn't passed to the route (it is passed to subsequent middleware)

Route:

Route::get('view_events/{gid}', array('as' => 'view_events','middleware' => ['auth','resolveGroupSlug','groupAdmin'], function($gid) 
{
    $user = Auth::user();
    $group = Team::find($gid);
    echo $gid;
      //get this user's relationship to group
    $group["team_user"] = Users_team::findComposite($gid,$user["id"]);
    $events = Helpers::getEvents($gid,0);
    return View::make('view_events', array('user' => $user, 'group' => $group, 'events' => $events));
}));

Middleware (resolveGroupSlug):

public function handle($request, Closure $next)
    {
        //convert a string gid to id number
        if (is_string ($request->gid)) {
            $group = Team::where('slug', '=', $request->gid)->firstOrFail();
            $request['gid'] = $group->id;
            echo $request->gid;
        }
        return $next($request);
    }

Any ideas how to set a route parameter in middleware? Or if there is just an easier way of doing this.

(No, i'm not going to copy paste the middleware code into every route i need this in!)

Thanks!!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1O7dcy0
via IFTTT

Laravel Autocomplete retruning undefined offset: 0

I am trying to implement autocomplete in on of the forms using Laravel.

My route is setup as:

Route::get('employee/getReportAuth', 'EmployeeController@getAuthority');

View:

<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
     <input class="mdl-textfield__input" type="text" name="reportTo" id="reportTo" />
     <label class="mdl-textfield__label" for="reportTo">Reporting Authority</label>
</div>

Javascript:

$("#reportTo").autocomplete({
    source: "{{url()}}/employee/getReportAuth",
    minLength: 3,
    select: function(event, ui) {
        $('#reportTo').val(ui.item.value);
    }
});

Controller:

public function getAuthority() {
        $term = Input::get('term');
        $reportTo = array();
        $search = Employee::where('firstName', 'like', '%'.$term.'%')->get();
        foreach ($search as $result) {
            $reportTo[] = $result;
        }
        return Response::json($reportTo);
    }

However, irrespective of the route or controller. As soon as the autocomplete function is triggered, the network tab in the inspect element shows me that the page is throwing a 500 error. Stating undefined offset: 0

My reference of autocomplete code has been from here.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1h9xlos
via IFTTT

mardi 29 septembre 2015

Cannot start artisan serve in laravel 5

I am using laravel 5, when I try to start server from

php artisan serve

I get following error :

[Symfony\Component\Debug\Exception\FatalErrorException] App\Providers\RouteServiceProvider::App\Providers{closure}(): Failed opening required 'D:\Test\app\app\Http/routes.php' (include_path='.;C:\xampp\php\pear')

I tried composer dump-autoload, it was successfull, but when i do

composer update

I get the same error.

How to resolve it?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LOcXpK
via IFTTT

Validating dynamically added input fields in Laravel 5

Problem: Need to validate dynamically added input fields.

Here is a screenshot of the UI:

enter image description here

Scenario 1: Adding a new schedule, validation works perfectly.

The form is validated using a Form Request file:

public function rules()
{
    $rules = [
        'name' => 'required|max:255',
        'due_at' => 'required|date_format:Y-m-d',
        'users' => 'required',
        'task_name' => 'required|max:255'
    ];
    if($this->request->get('task_name')){
        foreach($this->request->get('task_name') as $key => $val)
        {
            $rules['task_name.'.$key] = 'required|max:255';
            $rules['task_description.'.$key] = 'required|max:255';
        }
    }

    return $rules;
}

public function messages()
{
    $messages = [];
    foreach($this->request->get('task_name') as $key => $val) {
        $messages['task_name.'.$key.'.max'] = 'The field labeled task name must be less than :max characters.';
        $messages['task_name.'.$key.'.required'] = 'The field task name is required.';
        $messages['task_description.'.$key.'.max'] = 'The field task description must be less than :max characters.';
        $messages['task_description.'.$key.'.required'] = 'The field task description is required.';
    }
    return $messages;
}

Scenario 2: Updating an existing Schedule. This fails and I receive the following error message:

ErrorException in helpers.php line 454: htmlentities() expects parameter 1 to be string, array given (View: /Users/petestewart/Documents/Git Repos/.../resources/views/schedules/partials/_form.blade.php) (View: /Users/.../Documents/Git Repos/.../resources/views/schedules/partials/_form.blade.php)

enter image description here

Here is the Schedule controller update function:

/**
 * Update the specified resource in storage.
 *
 * @param  \App\Schedule $schedule
 * @return Response
 */
public function update(Schedule $schedule, ScheduleRequest $request)
{
    $schedule->name = $request->name;
    $schedule->apiary_id = $request->apiary_id;
    $schedule->due_at = $request->due_at;
    $schedule->update();

    // Attach users to the new schedule
    $schedule->users()->sync($request->get('users'));

    // Save the tasks
    if($request->get('task_name')){
        foreach($request->get('task_name') as $key => $task_name)
        {   
            //if(empty($task_name)) continue; // If a task is empty then skip to the next one   

            // Check if task exists and update task
            if(!empty($request->task[$key])){
                $task = Task::find($request->task[$key]);
                $task->name = $task_name;
                $task->description = $request->task_description[$key];
                $task->update();
            }else{
            // Add new task
                $task = new Task();
                $task->name = $task_name;
                $task->description = $request->task_description[$key];
                $task->schedule_id = $schedule->id;
                $task->save();
            }
        };
    };
    return Redirect::to('schedules')->with('success', trans('messages.update', ['name' => 'Schedule']));
}

And here is the HTML form:

@if(isset($tasks))  
        @foreach($tasks as $task)
            <div class="task-item row form-group">
                {!! Form::hidden('task[]', $task->id) !!}
                <a href="{{ route('schedules.task.delete', $task) }}" class="btn btn-danger btn-sm task-delete-btn" data-method="delete" data-confirm="Are you sure you want to delete this task?"><span class="fa fa-trash"></span></a>
                <div class="col-sm-4 task-name">
                    {!! Form::label('task_name', 'Task Name', array('class'=>'control-label')) !!}
                    {!! Form::text('task_name[]', $task->name, array('class'=>'form-control')) !!}
                </div>
                <div class="col-sm-8">
                    {!! Form::label('task_description', 'Task Description', array('class'=>'control-label')) !!}
                    {!! Form::text('task_description[]', $task->description, array('class'=>'form-control')) !!}
                </div>
            </div>
        @endforeach        
    @else
        @if(Form::old('task_name'))
            @foreach(old('task_name') as $key => $val)
                <div class="task-item row form-group">
                    <a href="#" class="btn btn-default btn-sm remove-task"><span class="fa fa-minus"></span></a>
                    <div class="col-sm-4 task-name {!! $errors->first('task_name.'.$key, 'has-error') !!}">
                        {!! Form::label('task_name', 'Task Name', array('class'=>'control-label')) !!}
                        {!! Form::text('task_name['.$key.']', old('task_name.'.$key), array('class'=>'form-control')) !!}
                        {!! $errors->first('task_name.'.$key, '<p>:message</p>') !!}
                    </div>
                    <div class="col-sm-8 {!! $errors->first('task_description.'.$key, 'has-error') !!}">
                        {!! Form::label('task_description', 'Task Description', array('class'=>'control-label')) !!}
                        {!! Form::text('task_description['.$key.']', old('task_description.'.$key), array('class'=>'form-control')) !!}
                        {!! $errors->first('task_description.'.$key, '<p>:message</p>') !!}
                    </div>
                </div>
            @endforeach
        @else
            <div class="task-item row form-group">
                <a href="#" class="btn btn-default btn-sm remove-task"><span class="fa fa-minus"></span></a>
                <div class="col-sm-4 task-name">
                    {!! Form::label('task_name', 'Task Name', array('class'=>'control-label')) !!}
                    {!! Form::text('task_name[]', null, array('class'=>'form-control')) !!}
                    {!! $errors->first('task_name', '<p>:message</p>') !!}
                </div>
                <div class="col-sm-8">
                    {!! Form::label('task_description', 'Task Description', array('class'=>'control-label')) !!}
                    {!! Form::text('task_description[]', null, array('class'=>'form-control')) !!}
                </div>
            </div>
        @endif
    @endif
    <a href="#" class="btn btn-default btn-sm" id="add-task"><span class="fa fa-plus"></span></a>

And finally the Jquery responsible for adding and removing tasks:

var TaskList = {

    addTaskBtn: $('#add-task'),
    completeTaskBtn: $('.task-complete-btn'),
    deleteTaskBtn: $('.task-delete-btn'),
    taskTemplate: '<div class="task-item row form-group"> \
                        <a href="#" class="btn btn-default btn-sm remove-task"><span class="fa fa-minus"></span></a> \
                        <div class="col-sm-4 task-name"> \
                            <label for="task_name" class="control-label">Task Name</label> \
                            <input class="form-control" name="task_name[]" type="text"> \
                        </div> \
                        <div class="col-sm-8"> \
                            <label for="task_description" class="control-label">Task Description</label> \
                            <input class="form-control" name="task_description[]" type="text"> \
                        </div> \
                    </div>',

    init: function() { 
        this.bindUIActions();
    },
    bindUIActions: function() {
        // Add new task item
        this.addTaskBtn.click(function () {
            $('.task-item:last').after(TaskList.taskTemplate);
            var newTask = $('.task-item:last');
            newTask.find('input[type=text]:first').focus();             
            return false;
        }); 
        $(document).on('click', 'a.remove-task', function (e) {
            if($(this).parent().is(':first-child')){
                $(this).parent().find('input[type=text]').val('');
                return;
            };
            $(this).parent().remove();
            return false;
        }); 
        // Set task as complete via AJAX
        this.completeTaskBtn.change(function () {
            var h3 = $(this).parent().parent().parent().parent().find('h3');
            var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
            var url = '/schedules/update-task';
            $.ajax({
                type: 'POST',
                url: url,
                data: {   
                    id: $(this).attr('id'),
                    complete: $(this).is(':checked')? 1 : 0,
                    '_token': CSRF_TOKEN
                },
                dataType: 'JSON',
                success: function (data) {
                    h3.find('span').remove();
                    h3.append(data.status_label);
                }
            });
            return false;
        });
        // Delete Task via AJAX
        this.deleteTaskBtn.click(function () {
            var taskWrapper = $(this).parent();
            var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
            var url = $(this).attr('href');
            if (confirm('Are you sure you want to delete this task?')) {
                $.ajax({
                    type: 'DELETE',
                    url: url,
                    data: {   
                        '_token': CSRF_TOKEN
                    },
                    dataType: 'JSON',
                    success: function (data) {
                        taskWrapper.remove();
                    }
                });
            }
            return false;
        });
    },
};

Any help with validating this when updating a Schedule would be appreciated. Thanks a lot!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1L3jAUw
via IFTTT

Laravel access classes without namespace in views

Usually, with laravel out of the box I am able to access the default "User" model without prefixing namespace routes, within any view, like so:

User::find(1);

However, if I create another model, for example - "Business", in order to access it in views I need to do the following:

App\Business::find(1);

Is there any way to "use" the classes globally in all views, so it works just like User class?

Thanks in advance.

Edit: It works if I do the following in a blade.php file, for example:

@extends('layouts.main')

@section('content')
    <?php
        use App\Business;
    ?>
    {{ Business::find(1)->name }}
@stop

But it seems like a not-so-clean way to do it. Or am I wrong and this is acceptable?

P.S - Using Laravel 5.1



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1FGR2zJ
via IFTTT

Laravel5 .How to store a variable in the database and then display it with its value on the page

I have a variable $title that I want to save in the database. I need to display it with its value on the page using Laravel5.

my code is:

{!! $article->title !!}

that gives me the following data on the page : $title , instead I want to see the value of the variable.

I will appreciate any help.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1jv1lNe
via IFTTT

How to use lists function while using where not in array filter?

Is it possible to generate a list(for a select item) while using hte whereNotIn filter option. I tried:

$sizes =  Size::lists('name', 'id')->whereNotIn('id', [1,3])->get();;

But i get the following error:

Call to undefined method Illuminate\Support\Collection::whereNotIn()

How should i filter these lists options?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1iZ5zwR
via IFTTT

Render html image tag from database in the Laravel 5

I want to store the complete code including:

img src="{{ (asset('/img/' .$variable. 'image.jpg')) }} "

in the database and display it on the page with Laravel 5.

My problem is that the image src is not rendering properly.

I will appreciate any help with this one.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LZvefn
via IFTTT

Laravel 5.1 - Need help to convert Raw Query to Eloquent

Can someone help me to convert this Raw Query to Eloquent? Thanks!

Raw Query:

$data = DB::select('
    select prefix, mobile, doubles, count(*) as numbers
    from contacts
    join (
        select count(*) as doubles
        from (
            select count(*)
            from contacts
            group by prefix, mobile
        ) as t1
    ) as t2 on contacts.id
    where group_id = 1
    group by prefix, mobile
    limit 5
');



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VoMr73
via IFTTT

Pass data from controller to view laravel 5

Controller

public function codingPuzzleProcess()
{

    $word     = Input::get('word');
    $length   = strlen($word);


    return Redirect::to('/coding-puzzle')
        ->with('word', $word )
        ->with('length', $length )
        ->with('success','Your word was submit succesfully!');

}


View

I tried to access those data in my blade view like this

{!!$word or '' !!} | {!!$length or '' !!}

and I got nothing printing. I'm sure that my

$word = 'love' with length of 4

Any hints / suggestion on this will be much appreciated !


Route

Route::get('/coding-puzzle', 'CodeController@codingPuzzle');
Route::post('/coding-puzzle/process', 'CodeController@codingPuzzleProcess');


Form / Blade

{!! Form::open(array('url' => '/coding-puzzle/process', 'class' => '', 'role' =>'form')) !!}

{{-- Text --}}
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 form-group form-row">
  <input required type="text" class="normal" placeholder="Enter Word" name="word"
  value="{{Request::old('word')}}">
  {!! $errors->first('word','<p style="color:#EE6593 !important; text-align: center;">:message</p>') !!}
</div>

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<input type="submit" id="submit" name="send" value="Get rank" class="button">
</div>

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



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VkZ2gP
via IFTTT

(maatwebsite) Laravel-excel. Is it possible to get the latest active row (or cell) while working with a blade view?

I'm working with laravel-excel, previously I used it creating a new sheet from scratch, so I was always able to know in which row I was by just using a variable ($row).

Now I'm exploring the other way of using it, by using a blade view, and it works great, but I want to do some transformations and add some formulas from the laravel-excel side (class side), the problem is that by using a view I lost control for knowing which row am I "standing" in.

I know how to pass variables to the view but I don't know how if I can give back a variable FROM the view to the class or if there is a way in laravel-excel to get the last active row after using a view or something like that.

This is a little example of what I would like to do:

public static function makeIng($params){
    $data['parts'] = Part::confirmed()->get();
    $data['adjusts'] = Adjust::confirmed()->get();
    Excel::create('Report', function($excel) use($data){
      $excel->sheet('1', function($sheet) use($data){
        $sheet->loadView('sii.dte.excel.ing', array('data' => $data));
        $sheet->mergeCells('A1:C1');
        $sheet->mergeCells('A2:C2');
        $sheet->mergeCells('A3:C3');

        //I would "dream" to to something like this:
        //$row=$sheet->getLastRow();
        //$sheet->cell('C'.($row+1),'=sum(C4:C'.$row.')');

     });
    })->export('xls');
}

BTW, using a "count" of my data to know how many rows to add is not an option this time, I did that for another excel but this time for some interactions inside the view that won't work.

I hope you can help me, thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1ju1As2
via IFTTT

Mongo $gt, $lt query not working for NumberInt

Here is my screenshot, I don't understand why sometimes value being stored as a a number and sometimes as NumberInt.

enter image description here

And When i am try this query for search

{
    "price.egglessPrice" : { '$gt' : 360, '$lt':370}
}

I always get the result including above screenshot. but this is not right ans. There is no price lies between 360 to 370.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1PLf1y2
via IFTTT

AngularJS and ngDroplet

I have an issues with ngDroplet to upload my files to server using an api request.

Following are my UploadCtrl:

'use strict';
/** 
  * controllers for Angular File Upload
*/
myApp.controller('UploadCtrl', ['$scope', '$timeout','$http',
function ($scope, $timeout,$http) {
   $scope.interface = {};
 /**
         * @property uploadCount
         * @type {Number}
         */
        $scope.uploadCount = 0;

        /**
         * @property success
         * @type {Boolean}
         */
        $scope.success = false;

        /**
         * @property error
         * @type {Boolean}
         */
        $scope.error = false;

        // Listen for when the interface has been configured.
        $scope.$on('$dropletReady', function whenDropletReady() {

            $scope.interface.allowedExtensions(['png', 'jpg', 'bmp', 'gif', 'svg', 'torrent']);
            $scope.interface.setRequestHeaders('/api/upload');
            $scope.interface.setRequestUrl('/api/upload');
            $scope.interface.defineHTTPSuccess([/2.{2}/]);
            $scope.interface.useArray(false);
            // $scope.

            //$scope.interface.sendFile('/api/upload');
            console.log('sending...');

        });

        $scope.$on('$dropletSuccess', function onDropletSuccess(event, response, files) {

            $scope.uploadCount = files.length;
            $scope.success     = true;
            console.log(response, files);

            $timeout(function timeout() {
                $scope.success = false;
            }, 5000);

        });

        // Listen for when the files have failed to upload.
        $scope.$on('$dropletError', function onDropletError(event, response) {

            $scope.error = true;
            console.log(response);

            $timeout(function timeout() {
                $scope.error = false;
            }, 5000);

        });

}]);

My view:

<div class="container-fluid container-fullw" ng-controller="UploadCtrl">
    <div class="row">
        <div class="col-md-6 col-md-offset-2">
                    <h3>Images</h3>
                    <section class="container">
        <section class="droplet" ng-class="{ uploading: interface.isUploading() }">
             <section class="toolbar">

                <input type="button" class="button upload-files" value="Upload Files"
                       ng-click="interface.uploadFiles()"
                       ng-hide="interface.isUploading()"
                       ng-class="{ clickable: interface.isReady() }" />

                <input type="button" class="button upload-files" value="Uploading..." ng-show="interface.isUploading()" />

                <div class="add-files">
                    <input type="button" class="button add-files" value="Add Files..." />
                    <droplet-upload-multiple ng-model="interface"></droplet-upload-multiple>
                </div>

                <comment class="progress" ng-class="{ visible: interface.isUploading() }">
                    Uploaded: {{interface.progress.percent}}%
                </comment>

            </section>
            <droplet ng-model="interface">

                <div class="loading" ng-class="{ visible: interface.isUploading() }">
                    <svg viewBox="0 0 400 400">
                        <path class="loading-path" data-progressbar ng-model="interface.progress.percent"
                              d="M 0,1 L 398,1 L 398,234 L 1,234 L 0,1"
                              stroke="#D3B2D1" stroke-width="1" fill-opacity="0"
                              style="stroke-dasharray: 392px, 392px;stroke-dashoffset: 392px;"></path>
                    </svg>
                </div>

                <comment></comment>

                <section class="message success" ng-class="{ visible: success }" ng-click="success = false">
                    Successfully uploaded {{uploadCount}} files.
                </section>

                <section class="message error" ng-class="{ visible: error }" ng-click="error = false">
                    Failed to upload any of the files.
                </section>

                <ul class="files">

                    <li ng-repeat="model in interface.getFiles(interface.FILE_TYPES.VALID)">
                        <droplet-preview ng-model="model"></droplet-preview>
                        <div class="delete" ng-click="model.deleteFile()">&times;</div>
                        <div class="size">{{model.file.size / 1024 / 1024 | number: 1}}MB</div>
                    </li>

                </ul>
            </droplet>
            </section>
</section>
        </div>
    </div>
</div>

The error I receive from server is TokenMismatchException in VerifyCsrfToken.php. I am using php laravel 5.1 as my server.

This is snapshot of console.

enter image description here

This is the link for the ngDroplet:

[http://ift.tt/1VkwlRb]



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1GefXFD
via IFTTT

How to run method in controller when user close browser in laravel 5

I need to detected when user close browser , to save record in data base ,

so how can I know when user close browser ? in laravel 5



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LZ124h
via IFTTT

Laravel Elixir version images which are linked via SASS/CSS

I'm fairly new to Laravel 5.0, but not to PHP. I've been playing around with Elixir to compile my SASS, copy images from my resource directory and run them through the mix.version function to prevent caching.

This works great for CSS, images and JavaScript, however; is it possible to have Elixir version images linked in my CSS/SASS too? Sure it's easily enough to version the images but is there a way of adjusting the CSS to reflect the new filenames?

I discovered this: http://ift.tt/1LZ14sO which allows you to append a query parameter to the file paths in a CSS file, so that is half of the problem solved. I would be quite happy to use this if it were possible to automatically change the query parameter each time gulp runs.

Any thoughts on how this can be achieved, or if it is even possible?

The reasons I would like to do this is I'm constantly developing my app and I use a large sprite sheet which is often rearranged, cache busting is a requirement, and if it could be automatic when gulp runs that would save me a lot of time and effort.

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1iYlQlJ
via IFTTT

select multiple column form database in laravel

How can I run following query in laravel ???

Select column1,column2,column3 from table;

I don't want to retrieve all columns records as we do by

Select * from table;



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KPlgNS
via IFTTT

log actions in Laravel and execution time

I want to log every request that come to the my site with all the parameters and the time it need to generate the response. The site is build in Laravel 5. I did try different approaches but no luck. My main problem is in how to get the total execution time.

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1P3hshh
via IFTTT

How to add 3 different themes for my website

I want 3 themes for my website. One theme for desktop version. Other for smartphones and tablets or highend mobile devices. Third theme is a basic theme for low internet connectivity and basic mobiles.

I also need to switch themes. Do anyone have idea that how to this in laravel 5



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KPidFg
via IFTTT

REST API Laravel: How to return a complex JSON response from an API

I'm a beginner with Laravel and PHP generally and was asked to create an API to get an array of data with an output like this:

"stages": [
                {
                    "id": "1f149fc7-5270-11e5-b3f3-3417ebe4606c",
                    "User": 
                                {
                                    "userId": "262b990f-526f-11e5-b3f3-3417ebe4606c",
                                    "firstName": "Name",
                                    "LastName": "last Name"
                                    "country": 
                                            {
                                                "countryId": 1,
                                                "countryName": "country"
                                            },
                                    "city": "city",
                                    "profilePicPath": "/path/abf115b7_5258_11e5_b3f3_3417ebe4606c/photo.jpeg"
                                },

                    "uploadDate": "2015-09-03 02:15:21",
                    "stageTypeId": "1f149fc7-5270-11e5-b3f3-3417ebe4606c",
                    "stageFilePath": "/path/MjYyYjk5MGYtNTI2Zi0xMWU1LWIzZjMtMzQxN2ViZTQ2MDZj.mp4",
                    "stageFilePhypath": "/path/MjYyYjk5MGYtNTI2Zi0xMWU1LWIzZjMtMzQxN2ViZTQ2MDZj.mp4",
                    "commentsCount":
                                {
                                    "count": 100,
                                },
                    "like":
                                {
                                    "count": 100
                                },

It is like twitter/instagram API where data returned is complete and complex. I have created an API with simple responses but not something like this where I have to get data from all other tables for each array of data that will be returned by the service. Also this would be easy if the data that I'm getting is not an array but for a specific ID. Is there a way can implement getting all data for each result array? Do I need to create 1 complex query to gather every information that I need?

Please help. Any advice, hints, tutorials will be really appreciated.

Thank you very much!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Rd5sc2
via IFTTT

Formetting Laravel's Data before returning

I want to have the returning data with a formatting like this -

{
  "cols": [
            {
              "label":"Topping",
              "type":"string"
            },
            {
              "label":"Slices",
              "type":"number"
            }
          ],
  "rows": [
            {
              "c":[
                    {"v":"Mushrooms"},
                    {"v":3}
                  ]
            },
            {
              "c":[
                    {"v":"Onions"},
                    {"v":1}
                  ]
            },
            {
              "c":[
                    {"v":"Olives"},
                    {"v":1}
                  ]
            },
            {
              "c":[
                    {"v":"Zucchini"},
                    {"v":1}
                  ]
            },
            {
              "c":[
                    {"v":"Pepperoni"},
                    {"v":2}
                  ]
            }
          ]
}

Is there any way in Laravel?

Thanks for helping.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KHtDxa
via IFTTT

How to display new lines where comma is there in address field in pdf generation using laravel 5?

I am trying to display address in new lines where comma is there like my adress as

#23, "Hari Prem Building", 1st Floor, Off CMH Road, Indiranagar, Bangalore, India

I just want to display my address as like

#23,
"Hari Prem Building",
1st Floor,
Off CMH Road,
Indiranagar,
Bangalore,India

For this i was trying the laravel syntax like {!! nl2br(e($inv->Address)) !!} but its not working for me ? Please help me out to solve this issue.. Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1FzmfVH
via IFTTT

One model to several tables Laravel 5

I have MySQL database tables, of which names are in "yyyymmdd" format. I need to select several tables, for example, from "20150901" to "20150930". I think there might be a way to implement only one model for those tables.

If somebody knows how to do so, please help.

Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1PKT4ip
via IFTTT

ajax request throwing 405 method not found error (Laravel 5)

I am making an ajax call from a form to send the checkbox data to a controller. Here is the relevant html code:

 <form method="POST" action="http://ift.tt/1MCSkLV" accept-charset="UTF-8" class="del_form" id="del_form" name="del_form"><input name="_token" type="hidden" value="igr6iMt1WfeZunyG8wpyy1tNK1efgiclyOvZ1hkF">
  <input id="submit" type="submit" name="submit" value="Delete Checked Records" onclick="return submitDelForm();">
   <div class="table-responsive shadow-edge-nofill">

    <table class="table table-striped">
                    <tbody>
                    <tr>
            <td><input id="badURL0" class="bad_url_checkbox" name="bad_url_checkbox" type="checkbox" value="2"></td>

    etc....etc.....etc....

    </form>

Here is the relevant javascript code:

  <script type="text/javascript">
    function submitDelForm(){
        $('div#loadmoreajaxloader').show();
        var form = document.del_form;
        var dataString = $(form).serialize();
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
        });
        $.ajax({
            type: 'POST',
            URL: '/delbadurl',
            contentType: "application/json; charset=utf-8",
            data: {'serial_data' : dataString},
            success: function(data){
                $('div#loadmoreajaxloader').hide();
            }
        });
    }
</script>

Here is relevant routing:

  Route::post('delbadurl','Admin\DashboardController@delBadURL' );

I can confirm that CSRF token is being appended to the dataString. The form data is being appended to the dataString as well. However, jquery throws 405 error.

I am using many other similar ajax functions to fetch and send the data. Everything works perfectly except this particular function. Some pointers will be greatly appreciated as I am coming empty handed.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KP92F0
via IFTTT

lundi 28 septembre 2015

Storing and serving uploaded images on new deployments

My web app has the funcionality of users being able to upload gallery images and profile pictures. They are saved in the /public/uploads folder and their URL is stored in the medias table in my database.

All was good when testing, but moving to production I found some issues: When I deploy a new version (I'm using deploybot), the current uploads folder gets substituted by the one in the new release. Even setting an option to ignore the uploads folder won't do any good, since the new release won't hold the same content the previous release had.

So my idea was to create a separate folder, outside the application directory, and symlink the public folder there.. then at every deployment, creating the new symlink to this folder.

I have two questions about this: 1) Would this be a common/good solution/practice for this problem? and 2) Since I'm using a separate folder, should I also create another server for this folder, something like images.mydomain.com?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LLGTCW
via IFTTT

Laravel 5 : Validation error message not working?

I can print error message in views with this code

return Redirect::back()->withInput()->withErrors($v);

Here is my view

@if(Session::has('errors'))
    <div class="row">
        <div class="col-md-12 col-sm-12">
            <div class="alert alert-warning">
                <button class="close" data-close="alert"></button>
                <ul>
                @foreach($errors->all() as $error)
                <li><strong>{{ $error }}</li></strong>
                @endforeach
                </ul>
            </div>
        </div>
    </div>
@else
        no error
@endif

But I can't print error if I use this code instead

return Redirect::back()->withInput()->withCok($v);

Here is the view

@if(Session::has('cok'))
    <div class="row">
        <div class="col-md-12 col-sm-12">
            <div class="alert alert-warning">
                <button class="close" data-close="alert"></button>
                <ul>
                @foreach($cok->all() as $error)
                <li><strong>{{ $error }}</li></strong>
                @endforeach
                </ul>
            </div>
        </div>
    </div>
@else
        no error
@endif

I always get no error.

  1. So how I can use withCok($v) instead of withErrors($v)?
  2. Why this thing happen ?
  3. Is this because withCok($v) does not create $cok variable ? while $errors already there by default ?


from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1ODyqTY
via IFTTT

Laravel 5.1 - Controller to Model Convertion

I have a function in controller like this-

function add_votes()
{
    $input = Request::all();
    $check_if_exists = DB::table('webinar_vote')
        ->where('webinar_id', '=', $input['uuid'])
        ->first();
    if (is_null($check_if_exists))                //Insert if not exist
    {
        DB::table('webinar_vote')->insert([
                                                    [
                                                        'webinar_id' => $input['uuid'],
                                                        'total_vote' => 0
                                                    ]
                                                ]);
    }

    DB::table('webinar_vote')                          //Incremnt the vote
                ->where('webinar_id', '=', $input['uuid'])
                ->increment('total_vote');
    return 'Vote given successfully';
}

My table is-

enter image description here

I want to have it in model.

My model is-

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class webinar_vote extends Model
{
    protected $table = 'webinar_vote';
    protected $primaryKey='webinar_id';

    public function give_vote()
    {
        //return $this->belongsTo('App\Webinar');
    }
}

But I don't know how to do it in give_vote function.

Can anyone help me please?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1iXZDEr
via IFTTT

Laravel 5.1 SQLSTATE[23000]: Integrity constraint violation error

On registering with new email, I can successfully register the new user, but when I try to make a validation rule to restrict an existing email from signup, instead of giving validation error message, its giving me Integrity constraint violation error ,

here is my controller

 public function postRegister(Request $request){
        $v = validator::make($request->all(), [
            'first_name' => 'required|max:30',
            'last_name' => 'required|max:30',
            'email' => 'required|unique:users|email',
            'mobile' => 'required|min:10',
            'password' => 'required|min:8',
            'confirm_password' => 'required|same:password'
        ]);

        if ($v->fails())
        {
            return redirect()->back()
                ->withErrors($v->errors())
                ->withInput(Input::except('password', 'confirm_password'));
        }



        else{

            // validation successful ---------------------------

            /*
            add data to database
             */

}

and this is my migration

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('first_name', 80);
            $table->string('last_name', 80);
            $table->string('email')->unique();
            $table->string('mobile',80);
            $table->string('password', 60);
            $table->boolean('confirmed')->default(0);
            $table->string('confirmation_code')->nullable();
            $table->float('amount', 80);
            $table->rememberToken();
            $table->timestamps();
        });
    } 

How can I fix this error? Any help appreciated.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NYGywP
via IFTTT

Command bus not going asynchronous

I made use of laravel 5.1 Command bus to run a specific task (upload a file, validate then record it in my db) on a background process. I tried uploading small csv file like 1.4kb (40 rows) and it worked. But when i tried uploading a 1MB csv file (20000 rows) i noticed it is not running in background process, it wait for the job to be finish then load the correct page which is not the way I wanted it :(. I think I followed the laravel documentation on how to run a command bus in asynchronous process just by php artisan make:command PurchasePodcast --queued.

Reference: http://ift.tt/16ov7Mw

My code

class ImportPricelistCommand extends Command implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

Am i missing something? Please help.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1h5CwWn
via IFTTT

Having trouble validating on update

this is my update function in usercontroller

public function update_user_credentials(UpdateUserRequest $request)
    { 
      $user = User::find($request->user()->id);
      if(!$user) 
      {
        return response('User not found', 404);
      }

      try
      {
        $data=Input::all();
        $user->fill($data);
        var_dump($user);
        exit;
        $user->save();

      } 
      catch(Exception $ex)
      {
        return response($ex->getMessage(),400);
        echo Success::get('message');
      } 
        return Redirect::back()->with('message','updated');   
    }

my UpdateUserRequest.php

<?php
namespace App\Http\Requests;

use App\Http\Requests\Request;

class UpdateUserRequest 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 [
                'first_name' =>'required',
                'last_name'=>'required',
                'url'=>'url',
                'password'=>'min:6|confirmed',
                'password_confirmation'=>'min:6',
                'email'=>'email|unique:users,email',            
                ];
            }

}

Each column has its own form. So updating email has its own form as does password.

When I'm updating without putting UpdateUserRequest inside my update controller, it works fine. But when I add that in for validations, nothing happens. I get a 302 error but I don't any messages.

I tried getting msgs with validator->messages but also got nothing.

Also if I put in

protected $redirect = '/'

I do get redirected. That means validation is working right?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1GduVvD
via IFTTT

Laravel 5 API Routes Returning 404 to Frontend

I'm trying to start a new project in Laravel 5, and I'm running into some routing issues. I used Laravel 4 before for something similar, but I'm new to laravel 5.

What I'm trying to do is create a demo application with an AngularJS frontend, and Laravel as a backend server and API for data. I have gulp build my frontend into laravel/public/app, so my structure looks like this:

laravel
 - app/
 - frontend-src/
 - public/
 -- app/
 --- index.php
 --- js/
 --- css/
 --- views/

I configured Laravel to look for views starting in public/app like this in laravel/config/view.php:

'paths' => array(__DIR__.'/../public/app'),

Then I configured my routes to load the Angular index page for '/' and a Route Group for my API calls like this:

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

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

    Route::resource('projects', 'ProjectController');

});

I'm serving it in development by using the artisan server and running it with php artisan serve - and this works fine. The index page loads, my Angular application is visible, and the homepage looks correct.

However, when I added a service call to GET /api/projects in the home page, the server responds with a 500 error

GET http://localhost:8000/api/projects 500 (Internal Server Error)

At first I thought I named something wrong or the routes were not setup, so I ran the command php atisan route:list - but the routes look fine:

+--------+----------+------------------------------+----------------------+------------------------------------------------+------------+
| Domain | Method   | URI                          | Name                 | Action                                         | Middleware |
+--------+----------+------------------------------+----------------------+------------------------------------------------+------------+
|        | GET|HEAD | /                            |                      | Closure                                        |            |
|        | GET|HEAD | api/projects                 | api.projects.index   | App\Http\Controllers\ProjectController@index   |            |
|        | POST     | api/projects                 | api.projects.store   | App\Http\Controllers\ProjectController@store   |            |
|        | GET|HEAD | api/projects/create          | api.projects.create  | App\Http\Controllers\ProjectController@create  |            |
|        | DELETE   | api/projects/{projects}      | api.projects.destroy | App\Http\Controllers\ProjectController@destroy |            |
|        | PATCH    | api/projects/{projects}      |                      | App\Http\Controllers\ProjectController@update  |            |
|        | GET|HEAD | api/projects/{projects}      | api.projects.show    | App\Http\Controllers\ProjectController@show    |            |
|        | PUT      | api/projects/{projects}      | api.projects.update  | App\Http\Controllers\ProjectController@update  |            |
|        | GET|HEAD | api/projects/{projects}/edit | api.projects.edit    | App\Http\Controllers\ProjectController@edit    |            |
+--------+----------+------------------------------+----------------------+------------------------------------------------+------------+

In the ProjectController, the index method is only one line:

return Response::json(array('success' => true));

Does anyone see what I'm missing, or what my /api routes would not not working? Thanks for your time, all!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1PJVKgk
via IFTTT

Laravel way to write re-usable view snippets

I have many models in my application. Each model has some specific markup that is used in countless locations. For instance, my User model has a profile_link attribute which is defined as follows:

class User extends Model {

    /*
     * Returns the anchor tag to the users profile.
     */
    public function getProfileLinkAttribute() {
        // This particular markup is simple. In the actual code, the HTML
        // is more complex, containing user's profile image etc.
        return '<a href="' . url($this->id) . '">' . $this->name . '</a>';
    }

}

There are many such accessors for many models, that return similar code snippets. The problem with this approach is that it makes me write HTML markup within the model. Is there any standard way to approach this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1MVbiQA
via IFTTT

laravel 5 subquery eloquent

How to write a request for such a plan

    SELECT T1.id, T1.name_ua,
    (SELECT COUNT(*) FROM categories T2 WHERE T2.parent_id = T1.id)  AS children_count
  FROM categories T1 WHERE parent_id = 0



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1h3zF0e
via IFTTT

Laravel 5 Asyncronous AJAX requests cause session problems

I am using Laravel 5 ("laravel/framework" version is " v5.1.16", Homestead Ubuntu), with session driver = 'file'.

I noticed that if a number of async AJAX requests (jQuery) are fired eg. in autocomplete search form field then the session variables are gone.

This happens, only with async AJAX requests, when async option is set to false this problem no longer exists.

Also, when session driver is set to 'cookie' and async set to true there is a new cookie created on each AJAX request, so with 10 requests there will be 10 laravel cookies etc.

Any suggestions? I have failed to find any decent cause or solution to this, except not using async requests.

Related issues, which seems to be fixed.

http://ift.tt/1Vm7I1i

http://ift.tt/1L0jGfF



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Vm8Fqn
via IFTTT

Laravel load settings from database

I'm looking for an efficient way to load settings/configuration from the database with Laravel 5. Settings consist of a key and value column, the model class basically looks like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $table = 'settings';
    protected $fillable = ['key', 'value'];
    protected $primaryKey = 'key';
}

At first I made a simple helper function which does the job. The problem is, this would lead to multiple calls per page request. Which is getting slow.

/**
 * Get the value for the given setting from the database.
 *
 * @param  string  $key
 * @return string
 */
function setting($key)
{
    $setting = Setting::whereKey($key)->firstOrFail();

    return $setting->value;
}

// $foo = setting('foo'); returns 'bar'

In an attempt to improve this I creating a custom class called Setting within the App\Classes directory (and also created a Facade for it):

<?php

namespace App\Classes;

use Cache;

class Setting {

    /**
     * The array of settings
     *
     * @var array $settings
     */
    protected $settings = [];

    /**
     * Instantiate the class.
     */
    public function __construct()
    {
        $this->loadSettings();
    }

    /**
     * Pull the settings from the database and cache them.
     *
     * @return void;
     */
    protected function loadSettings()
    {
        $settings = Cache::remember('settings', 24*60, function() {
            return \App\Setting::all()->toArray();
        });

        $this->settings = array_pluck($settings, 'value', 'key');
    }

    /**
     * Get all settings.
     *
     * @return array;
     */
    public function all()
    {
        return $this->settings;
    }

    /**
     * Get a setting value by it's key.
     * An array of keys can be given to retrieve multiple key-value pair's.
     *
     * @param  string|array  $key;
     * @return string|array;
     */
    public function get($key)
    {
        if( is_array($key) ) {
            $keys = [];

            foreach($key as $k) {
                $keys[$k] = $this->settings[$k];
            }

            return $keys;
        }

        return $this->settings[$key];
    }

}

// $foo = Setting::get('foo');

And now for my question: is this the best way to tackle this problem? I'm now caching all the settings when the class gets constructed. And then retrieve setting values from the cache after that.

I'm beginning to understand the Repository pattern in L5, but I'm not there yet. I thought that would be overkill in this case. I would love to hear if my approach makes any sence.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1MUkFAg
via IFTTT