dimanche 31 juillet 2016

Laravel 5 : Facing issue with defining routes with parameter

Working on Laravel 5.2 app, My problem with routes I've defined.

1. Redirect to home

Route::get('/', ['as' => '/','uses' => 'HomeController@index']);

2. Redirect to user profile i.e "http://ift.tt/2akSkng"

Route::get('/{username?}', ['as' => '/','uses' => 'HomeController@profile']);

3. Not Redirect to dashboard, its redirect to profile action

Route::get('/dashboard', ['as' => '/dashboard','uses' => 'HomeController@dashboard']);

Thanks in advance!



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

Laravel cookie sent to browser but not saving it

I am working with Laravel 5.2. When i working on my local envierment (vagrant) the code is working and the cookies are save at the browser. but when i trying it on production envierment, the cookie sent to the browser but it's not saving it. Can anyone help me please?

code:

    if (isset($cookies['poptin_display'])){
        //var_dump($cookies);
        return response()->json($poptinTrigger)->withCookie('poptin_dispaly_returning_visitor',$visit_counter, 86400)->withCookie('poptin_dispaly_after_x_visiting',$visit_first_time, 86400);
    }else{
        return response()->json($poptinTrigger)->withCookie('poptin_display',true, 1440)->withCookie('poptin_dispaly_returning_visitor',$visit_counter, 86400)->withCookie('poptin_dispaly_after_x_visiting',$visit_first_time, 86400);
    }



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

mailing outlook calendar event through laravel 5

Hi I just want to know how to mail an outlook event through laravel 5. Can anyone help me with this? Below is my code:

routes.php

Route::get('order/{order_id}/outlookevent', array('as' => 'order.outlookevent', 'uses' => 'OrderController@createOutlookEvent'));

My Controller page:

public function createOutlookEvent($order_id)
{   
$order = Order::findOrFail($order_id);
$data['order_number'] = $order->order_number;   
$data['to'] = 'test@hotmail.com';
$data['subject'] = "Millennium Falcon";

$data['organizer']          = 'sample';
$data['organizer_email']    = 'sample@gmail.com';

$data['participant_name_1'] = 'test';
$data['participant_email_1']= 'sample_test@yahoo.co.in';

$data['location']           = "Redmont-Seattle";
$data['date']               = '20150812';
$data['startTime']          = '0800';
$data['endTime']            = '0900';
$data['subject']            = 'Krankontrollen Estimation';
$data['desc']               = 'The purpose of the meeting is to discuss the capture of Krankontrollen Estimation and its crew.';

$data['headers'] = 'Content-Type:text/calendar; Content-Disposition: inline; charset=utf-8;\r\n';
$data['headers'] .= "Content-Type: text/plain;charset=\"utf-8\"\r\n"; #EDIT: TYPO

$data['message'] = "BEGIN:VCALENDAR\r\n
VERSION:2.0\r\n
PRODID:-//Deathstar-mailer//theforce/NONSGML v1.0//EN\r\n
METHOD:REQUEST\r\n
BEGIN:VEVENT\r\n
UID:" . md5(uniqid(mt_rand(), true)) . "example.com\r\n
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z\r\n
DTSTART:".$data['date']."T".$data['startTime']."00Z\r\n
DTEND:".$data['date']."T".$data['endTime']."00Z\r\n
SUMMARY:".$data['subject']."\r\n
ORGANIZER;CN=".$data['organizer'].":mailto:".$data['organizer_email']."\r\n
LOCATION:".$data['location']."\r\n
DESCRIPTION:".$data['desc']."\r\n
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN".$data['participant_name_1'].";X-NUM-GUESTS=0:MAILTO:".$data['participant_email_1']."\r\n
END:VEVENT\r\n
END:VCALENDAR\r\n";

$data['headers'] .= $data['message'];
Mail::send(['html'=> 'emails.test'], $data,  function ($message) use (&$order, &$data) {
    $message->subject($data['subject']);
    $message->from('fromtest@gmail.com', 'Krankontroller');
    $message->to($data['to']);
});
return Redirect::back()->with($this->success, trans($this->sent_success));
}

My View page is:

<?php echo $headers; ?>

and my output is:

Content-Type:text/calendar; Content-Disposition: inline; charset=utf-8;\r\nContent-Type: text/plain;charset="utf-8" BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Deathstar-mailer//theforce/NONSGML v1.0//EN METHOD:REQUEST BEGIN:VEVENT UID:21835d460dd0be889c405846ad40d9a3example.com DTSTAMP:20160801T054626Z DTSTART:20150812T080000Z DTEND:20150812T090000Z SUMMARY:Krankontrollen Estimation ORGANIZER;CN=Catherine:mailto:catherinegitanjali@gmail.com LOCATION:Redmont-Seattle DESCRIPTION:The purpose of the meeting is to discuss the capture of Krankontrollen Estimation and its crew. ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CNGitanjali;X-NUM-GUESTS=0:MAILTO:gita_cathy@yahoo.co.in END:VEVENT END:VCALENDAR

But what I'm expecting is:

enter image description here

It just print the headers and not giving the outlook event style. what mistake I made here? Can anyone help me, please? thanks in advance.



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

Laravel routing with model as string

I am trying to simplify my routing for my models using Laravel 5.1. I have two resources, Questions and Categories, which inherit from ResourceController.

$router->get('/categories', 'Resources\Categories@index');
$router->get('/questions', 'Resources\Questions@index');

In ResourceController.php, my resource classes use this index method:

public function index(Request $request, Route $route)
{
    // Converts route name into namespaced Model string
    // E.g: App\Http\Controllers\Resources\Questions@index -> App\Question
    $model = $this->getModelClass($route->getActionName());

    return $model::all();
}

This SO post says I can call a eloquent methods using a fully qualified string:

$model_name = 'App\Model\User';
$model_name::where('id', $id)->first();

If I return $model, I get App\Category and App\Question for the respective routes I hit. This is good!

If I return $model::all(), I get a 500 error with no data.

I checked my sequel pro query logger and saw that both questions and categories were called about 20+ times even though I'm making a request to only one route at a time.

enter image description here

Why is this happening? This could explain the 500 error. I was able to get the models when only one resource was using this parent index method.

When both Questions and Categories relied on the same index, the errors started. I don't see why this is a conflict as the route sends the specific call to the index with the model name.


EDIT: I think this is related to how I am specifying eager loading:

Category.php Model:

protected $with = ['questions'];

Question.php Model:

protected $with = ['category'];

So it seems to be a circular reference where loading questions will come with categories, which will in turn load related questions, and so on.

But I do in fact need each to load with the relation. How can I fix this?



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

Laravel Route Model binding - get model path

I'm trying to use Laravel 5.1 Route Model binding to simplify my resource controllers.

I have a model Categories, which inherits from ResourceController, which attempts to list generic methods like index, show, etc.

I know you can use route binding to guess a model instance based on a route variable, such as {category} would get me a specific category ID.

But from the route below, how can I get Resources\Categories passed into the parent ResourceController index method?

Route:

$router->get('/categories', 'Resources\Categories@index');

Categories controller for model Category:

class Categories extends ResourceController {

Parent ResourceController: I am manually trying to grab the model path, /categories and convert it to App\Category, but this seems like the wrong way to do it.

class ResourceController extends Controller
{
    public function index()
    {
        // /categories
        $route_uri = Route::getFacadeRoot()->current()->uri();

        // Do some string conversion to get `App\Category` from `/categories` route
        $model = stringConverter($route_uri);

        // Then return App\Category::all()
        return $model::all();
    }


I suppose another option is explicitly passing in the class to the parent. But this seems unnecessary since I already have this information from the route:

class Categories extends ResourceController
{

    public function index()
    {
        return parent::index(Category::class);
    }



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

Filtering models by eager loaded data, at the database level

In the laravel docs they discuss eager loading related data to solve the N+1 query problem. I would like to filter my data based on the data from these relationships, without having to iterate through the results (that is, I would like this done at query time)

An example used in the docs is as follows:

$books = App\Book::with('author.contacts')->get();

If I wanted to filter these books to only include those who's author lives in the zip code 12345, how would I do that?

Neither of the following queries work for me:

$books = App\Book::with('author.contacts')->where('zip', 12345)->get();
$books = App\Book::with('author.contacts')->where('author.contacts.zip', 12345)->get();

Is there a simple way to do this in Eloquent?



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

can i re-use validator instance in the controller ?

i use ajax to send my request , and i want to format errors in special way (still jason though .. i want to change data structure of error and add some flags to it )

so since apparently $this->validate just would print out errors without my permission ! and i have no control over it , i have to use static method of validator

$whitelist = [
    'title'=>'required',
    'slug'=>'present' ,
    'text'=>'present'
];

$validation = Validator::make($request->all(), $whitelist);
if($validation->fails())
{
    format_output_likeIwant($validation->messages()->messages());
}

$another_whitelist = [
    'some_other_info'=>'required',
];

just out of curiosity , is there any way for me to validate my $another_whitelist with my existing instance ? or should i create a new instance of validator for each list ?

btw reason for having 2 different validation array is , i'm using this whitelists/arrays to populate my model instance before save/update in database and avoid writing lots of extra code in case of big tables.. 2 list here belong to different model/tables (see here for example)

i've looked in the laravel documentation , it seems all of the examples assume single validation list



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

Laravel form not submitting when logged in

I have a strange error. My form is not submitting in laravel, but only when i am logged in. So when i am not logged in everything works fine and when i am logged in a can click on the submit button, but nothing happens.

Does anyone have an idea what could be wrong?

I am using the latest version of laravel 5.2



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

DB_HOST and Browser Settings For Laravel App

I'm putting together a Laravel 5.2 application and using Homestead with it. When I need to migrate my database these are the settings that I have set up that allows me to do migrate. However if I want to use these in my browswer then I have to switch 127.0.0.1 to localhost. Why do I have to do this and how do I fix that?

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=33060
DB_DATABASE=homestead    
DB_USERNAME=homestead
DB_PASSWORD=secret



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

generate route for routes defined inside group

I have this route defined inside a group

Route::group(['domain' => '{subdomain}.test.com'], function () {

    Route::get('/models/{id?}', [
        'as' => 'car-model',
        'uses' => 'CarModelController@details'
    ]);

});

I want to avoid hardcoding URLs in blade



but that returs this url

ford.test.com/models

no model id!

Not sure if is relevant but in my controller CarModelController.php I defined

public function details($subdomain, $id)

why is not sending the id to the generated url? Do I need to send the $subdomain parameter to the detail function?



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

Form validation and all subsequent code doesn't execute

I have an update form,that i call inside a modal on my main page,(with an onclick event,the click triggers a call with xmlhttprequest for the edit page containing the form with the stored data values). The thing is,everything works fines,the update works,post works,retrieving data in the first place works,except for the form validation,and ajax use to post the data. Please notice that on my main page,i have a create call,that creates a new instance,and it works just fine,with the form validation and the ajax post,so it can't be some required jQuery or any other script.

This is my form:

<form id="eventFormUpdate" method="POST" class="form-horizontal" action="Event//Update">
    <input type="hidden" name="_method" value="PATCH" id="hidden-update">
    <div class="form-group">
        <label class="col-xs-3 control-label">Nom</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="nameUpdate" value=""/>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Date de début</label>
        <div class="col-xs-5 dateContainer">
            <div class="input-group input-append date" id="startDatePickerUpdate">
                <input type="text" class="form-control" name="starting_dateUpdate" value=""/>
                <span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
            </div>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Date de fin</label>
        <div class="col-xs-5 dateContainer">
            <div class="input-group input-append date" id="endDatePickerUpdate">
                <input type="text" class="form-control" name="ending_dateUpdate" value=""/>
                <span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
            </div>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Assigné à</label>
        <div class="col-xs-5 selectContainer">
            <select name="assigned_toUpdate" class="form-control">
                <option value="4" selected >First</option> <!--fix this by checking if is the selected data or not-->
            </select>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Description</label>
        <div class="col-xs-5">
            <textarea id="descUpdate" class="form-control" name="descriptionUpdate" placeholder="Veuillez entrer une description"></textarea>
        </div>
    </div>

    <div class="form-group">
        <div class="col-xs-5 col-xs-offset-3">
            <button type="submit" class="btn btn-default" id="update-event-submit">valider</button>
        </div>
    </div>
</form>

And here is my script that handles the form validation and the ajax posting

<!-- event update script -->
<script>
$(document).ready(function() {
    $('#startDatePickerUpdate')
            .datepicker({
                format: 'yyyy/mm/dd'
            })
            .on('changeDate', function(e) {
                // Revalidate the start date field
                $('#eventFormUpdate').formValidation('revalidateField', 'starting_dateUpdate');
            });

    $('#endDatePickerUpdate')
            .datepicker({
                format: 'yyyy/mm/dd'
            })
            .on('changeDate', function(e) {
                $('#eventFormUpdate').formValidation('revalidateField', 'ending_dateUpdate');
            })
            .find('[name="assigned_toUpdate"]')
            .selectpicker()
            .change(function(e) {
                /* Revalidate the pick when it is changed */
                $('#eventFormUpdate').formValidation('revalidateField', 'assigned_toUpdate');
            })
            .end();

    $('#eventFormUpdate')
            .formValidation({
                framework: 'bootstrap',
                icon: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    nameUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'Le nom est obligatoire.'
                            }
                        }
                    },
                    starting_dateUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'La date de début est obligatoire.'
                            },
                            date: {
                                format: 'YYYY/MM/DD',
                                min: new Date(new Date().setDate(new Date().getDate()-1)),
                                max: 'ending_date',
                                message: 'La date de début est non valide.'
                            }
                        }
                    },
                    ending_dateUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'La date est oligatoire.'
                            },
                            date: {
                                format: 'YYYY/MM/DD',
                                min: 'starting_date',
                                message: 'La date de fin est non valide.'
                            }
                        }
                    },
                    descriptionUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'La description est obligatoire.'
                            }
                        }
                    },
                    assigned_toUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'Veuillez séléctionner un utilisateur.'
                            }
                        }
                    }
                }
            })
            .on('success.field.fv', function(e, data) {
                if (data.field === 'starting_dateUpdate' && !data.fv.isValidField('ending_dateUpdate')) {
                    // We need to revalidate the end date
                    data.fv.revalidateField('ending_dateUpdate');
                }

                if (data.field === 'ending_dateUpdate' && !data.fv.isValidField('starting_dateUpdate')) {
                    // We need to revalidate the start date
                    data.fv.revalidateField('starting_dateUpdate');
                }
            })

            .submit(function(){
                return false;
            })

            .submit(function(){
                console.log('gonnastartsub');
                var $form = $("#eventFormUpdate"),
                        url = $form.attr('action');
                console.log('got vars');
                $.post(url, $form.serialize()).done(function () {
                    console.log('am in');
                    $("#modal-closeUpdate").click();
                    console.log('posted');
                });
            });
});
$("#descUpdate")
        .focus(function() {
            if (this.value === this.defaultValue) {
                this.value = '';
            }
        })
        .blur(function() {
            if (this.value === '') {
                this.value = this.defaultValue;
            }
        });

One last thing,at first the script was on my main page,and it didn't work so i tried to put it in in the called page with xmlhttprequest,and still doesn't work. The only thing i can think of is,when i call the new page(the form to edit and update data) the script is already loaded in the main page,so it doesn't find the ids of the elements to handle,that's why it does not work,or at least this is the only reason i could find . Any suggestions please?



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

lavaral php artisan serve not working in server

I am totally new to laravel. I wanted to install latest laravel i.e., 5.2.* in 1and1 server . However 1and1 linux shared hosting provides php5.5.38 so I installed laravel 5.0.* in the server following the instruction provided in

http://ift.tt/2apV5W5

The frame work is installed as I can see all the folders necessary. I wanted to test if it is working by running the command php5.5 artisan serve it does not run continuously it says:

   Laravel development server started on http://localhost:8000/
   Error in argument 1, char 2: option not found S
   X-Powered-By: PHP/5.5.38
   Content-type: text/html
   Usage: php5.5 [-q] [-h] [-s] [-v] [-i] [-f <file>]
   php5.5 <file> [args...]
  -a               Run interactively
  -b <address:port>|<port> Bind Path for external FASTCGI Server mode
  -C               Do not chdir to the script's directory
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse <file>.  Implies `-q'
  -h               This help

I expect the Laravel development server started on http://localhost:8000/ running in the server until I press crtl+c.

If I use php5.5 artisan up it says ‘Application is now live’, but I can’t see anything in locahost:8000 am I checking the wrong URL?? I have not changed any url in the installed laravel project I have also tried different command like

php5.5 -s localhost:8000 -t public
which shows

Status: 404 Not Found
X-Powered-By: PHP/5.5.38
Content-type: text/html
No input file specified.

Is there any other command to check laravel. Note: I was using php5.5 in all the command because the default php version in 1and1 server is 4.4.9

Sorry if I am asking silly questions I am new to laravel. Thanks in advance. I would really appreciate your help.



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

Modifing the Auth registration system in Laravel 5.2 to include hidden form fields

every one. I'm currently having an issue modifying the Auth registration system in Laravel 5.2. What I am trying to do, is have two separate loging system for regular users and admins. I added a new field into the database for the users called admin, and set the default to 0, or false. Using the registration page that Laravel's auth system uses, I added a hidden input and set the value to 1. This page will obviously be used to log in the admins so that they can enter the admin area.

When I submit the form, the admin field is simply set to the default value, which is not what I want for this portion of the site. Once the user clicks submit on this page, I want his information to get sent to the database the the admin value of 1. Is there any way of doing this?

Here is what I have done so far to customize the auth registration system.

I removed the name field and added a firstname and lastname field so that the users can enter both of these value in separate text inputs. I updated the User model to include these fields in the $fillable array and updated the AuthControllers validate method so that these fields could be validated.

Here is the code for each

Here is the User.php model file

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'firstname', 'lastname', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token', 'admin',
];
}

and here os the AuthContoller file

class AuthController extends Controller
{

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/';

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

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'firstname' => 'required|max:255',
        'lastname' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
        'admin' => 'required',
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return User
 */
protected function create(array $data)
{
    return User::create([
        'firstname' => $data['firstname'],
        'lastname' => $data['lastname'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'admin' => $data['admin'],
    ]);
}
}

As you can see, I also added the admin field in the User.php model file hoping that that would auto fill automatically.

If anyone can tell me how this could be done, that would be great. But as you can see this isn't really a practical solution for an actual website, but its more about learning the ins-and-outs of Laravel and learning how to customize the heck out of it. As I began to write this question out, it seemed to me, that I could easily just use the registration for any user, then allow an upper level admin to set the value of the admin field to true so that the user could venture into the admin sections of the application. Of course, will a system like this, there would be no need to have two separate log in screens, but like I said, I'm just learning.

I also plan on adding roles, similar to word presses for the various level's of admins, that would control things such as creating, editing, and publishing content such as posts. but for now, I'm just working on this system as it is.

Thanks for any help and comments about this topic.



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

Laravel: Pass Variables in View to Controller

I want to pass two variables from the form in the view to my controller and there to use them... But I don't know how...

Can you help me?

shop.blade.php:

<div class="mcitem">
                    <img src="/images/shop/Stein.png" alt="Stein">
                    <div class="mcunits">
                        
                        
                    </div>
                    <div class="mcbuy">
                        $itemid = 1;
                        $bprice = 3;
                        
                    </div>
                    <div class="mcsell">
                        
                        
                    </div>
                </div>

ShopController:

public function add(Request $request){
    $this->validate($request, [
        'units' => 'required|min:1',
    ]);
    if(Input::Get('buybtn')) {
        $this->Buy(); //if Buy Button is pushed
    } elseif(Input::Get('sellbtn')) {
        $this->Sell(); //if Sell Button is pushed
    }
}

public function Buy(){
    $username = Auth::user()->name;
    $units = Input::Get('units');
    if((DB::table('users')->where('name', $username)->value('kontostand')) >= ($bprice*$units)){
        $check_entry = DB::table($username)->where('Item', '=', $itemid)->first();
        if(is_null($check_entry)){
            $hunits = DB::table($username)->where('Item', $itemid)->select('units')->get();
            DB::table($username)->where('Item', $itemid)->update([$itemid => $hunits + $units]);
        }
        else{
            DB::table($username)->where('Item', $itemid)->insert(
                [$itemid => $units]
            );
        }
    }
    else{
        echo "Zu wenig Geld auf dem Kontostand!";
    }
}

I know now it's completly wrong because I tried so much but yeah...Nothing happens...



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

laravel 5 service provider not working my web server

Laravel 5 service provider cannot working in web server but its working fine in my localhost details explain bellow

App->Privider->MymoduleServiceProvider.php

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App;
class MyModuleServiceProvider extends ServiceProvider
{
    public function boot()
    {
        //
    }
    public function register()
    {
         App::bind('mymodule', function()
        {
            return new \App\Module\MyModule;
        });
    }
}

I have make one folder named Module in this folder have two file

App->Module

1. MyModule.php

namespace App\module;
use Session;
class MyModule {

public function Vegitable($data){
          $veg = \App\models\veg::select('id')
                  ->where('vegs', $data)
                  ->get()->count();
          echo $veg;
      }
}

2. MyModuleFacade.php

namespace App\Module;
use Illuminate\Support\Facades\Facade;
class MyModuleFacade extends Facade{
    protected static function getFacadeAccessor() { return 'mymodule'; }
}

and i added in config->app.php

'providers' => [
     App\Providers\MymoduleServiceProvider::class
]
 'aliases' => [
    'MyModule'=> App\module\MyModuleFacade::class,
]

and calling in view like

its working fine in my localhost(xampp) but not working my web server geting error message given bellow

ErrorException in AliasLoader.php line 66:
Class 'App\module\MyModuleFacade' not found (View: /home/pric/public_html/veg/demo/vegster/resources/views/veglist.blade.php)



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

how to check filled input in Laravel 5.1

I want to validate some inputs of Laravel5.1 application to be fill not require meaning,its not require to an attribute was sent but if was sent,its value could not be empty string,what is your solution? Of course I used filled rule but its useless and if value of input is empty it can not be validate attribute



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

Quality option in the Imagine laravel component

I have a question about Imagine component. Several days ago I had been installed It and I use It with the laravel 5. Everything looks good, but I have a trouble with a quality options. It looks like this settings are not working when I had been trying to apply It in my code. No errors, warnings or notices, but when I had been trying to apply different values nothing has been changed in the images quality :( my code looks like:

    $imagine = new Imagine();

    $options = [
        //'resolution-units' => ImageInterface::RESOLUTION_PIXELSPERINCH,
        //'resolution-x' => 300,
        //'resolution-y' => 300,
        'jpeg_quality' => 100,
    ];

    $image = $imagine->open($image->getRealPath());
    $size = $image->getSize();
    $width = $size->getWidth();
    $height = $size->getHeight();
    $aspect_ratio = $width / $height;

    $height_in_percent = round((230 * 100) / $height); //округлить (считаем новую высоту, 230px, в процентах от оригинальной)
    $new_width = round(($width * $height_in_percent) / 100); //высчитываем пропорциональную оригинальной новую ширину

    if(!isset($input['original'])) {
        //$aspect_ratio >= 1.3 ? $a = '1' : $a = '0';
        if($aspect_ratio < 1.33) return Redirect::intended($pass)->with('message', 'Пожалуйста, выберите изображение панорамной ориентации (ширина больше, чем высота и соотношение сторон больше или равно 1.33 (aspect ratio))');

        /*$aspect_ratio >= 1.33 ? $img = $img->resize(null, 230, function ($constraint) { //сравниваем AR загружаемого изображения с AR (1.3) выходного изображения, если >= 1.3, то подгоняем по высоте, а потом кропим ширину, иначе - наоборот
            $constraint->aspectRatio(); //автоподгонка по высоте
            $constraint->upsize(); //предотвращение возможного увеличения изображения
        }) : $img = $img->resize(300, null, function ($constraint) {
            $constraint->aspectRatio(); //автоподгонка по высоте
            $constraint->upsize(); //предотвращение возможного увеличения изображения
        });

        $img->crop(300, 230); //кропим изображение*/

        $image = $image->resize(new Box($new_width, 230))
            //->rotate(45)
            ->crop(new Point(0, 0), new Box(300, 230));

    }

    //$img->save('public/' . $image_filename, 90); //rezise изображения починить, ошибка записи в папку
    //$img->save($image_filename, 90); //rezise изображения починить, ошибка записи в папку
    $image->save('images/' . $image_filename, $options);

This morning I had been found a solution which is working as I think. I had been looking in the

private function saveOrOutput

in the imagine/imagine/lib/imagine/Gd/Imagine.php and It looks like there is no 'jpeg_quality' in the $options array, there is 'quality' options exists. So I had been changed It (to 'quality' => 100) and It's working.

Does anybody working with this component? Is my thoughts correct?



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

samedi 30 juillet 2016

Laravel 5.2 Add errors in an array using After Validation Hook

I'm trying to add a function in my app where users are allowed to change their account password. I have three fields and my view looks like this:

<form class="form" role="form" action="" method="post">
    

    <div class="form-group label-floating ">
        <label class="control-label" for="oldpassword">Old Password</label>
        <input type="password" name="oldpassword" class="form-control">

        @if ($errors->has('oldpassword'))
            <span class="help-block">
                <strong></strong>
            </span>
        @endif
    </div>

    <div class="form-group label-floating ">
        <label class="control-label" for="newpassword">New Password</label>
        <input type="password" name="newpassword" class="form-control">

        @if ($errors->has('newpassword'))
            <span class="help-block">
                <strong></strong>
            </span>
        @endif
    </div>

    <div class="form-group label-floating">
        <label class="control-label" for="newpassword_confirmation">Confirm Password</label>
        <input type="password" name="newpassword_confirmation" class="form-control">
    </div>

    <div class="form-group">
        <button class="btn btn-raised btn-primary">Change</button>
    </div>
</form>

Firstly, I want to check if all fields are completely filled up and for that I used Validator. And then check if the oldpassword is match from the database so I use if (Auth::attempt(array('password' => $request->oldpassword))) condition. I also found in the laravel 5.2 documentation the After Validation hook. I don't know what is wrong but it seems it don't validates the oldpassword field when I typed a wrong password.

My controller:

$validator = Validator::make($request->all(), [
    'oldpassword' => 'required|max:255',
    'newpassword' => 'required|min:6|max:255|confirmed',
    ]);
$validator->after(function($validator) use($request) {
    if (Auth::attempt(array('password' => $request->oldpassword))) {
        $validator->errors()->add('oldpassword', 'Old password dont match in our database.');
    }
});
if ($validator->fails()) {
    // Toastr
    $title = "Oops!";
    $message = "Please make sure to fill all required fields.";
    $options = [
        'progressBar' => false,
        'positionClass' => 'toast-top-right',
        'timeOut' => 6000,
    ];
    Toastr::error($message, $title, $options);
    return redirect()->back()
        ->withErrors($validator);
} else {
    return 'success'; // for testing only
}

Any idea regarding this?



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

Laravel, Restangular, and AngularJS 1.5.8

I'm attempting to figure out why I'm receiving a Module Injection error for my script that references to:

** Uncaught Error: / Error Reference / $injector / modulerr

app file which contains all files in /angular/routes/, /angular/controllers/, /angular/filters/, /angular/services/, /angular/directives/, /angular/routes/, /angular/config/

(function(){
"use strict";

var app = angular.module('app',
        [
        'ngRoute',
        'app.controllers',
        'app.filters',
        'app.services',
        'app.directives',
        'app.routes',
        'app.config'
        ]);

angular.module('app.routes', ['ui.router']);
angular.module('app.controllers', ['ngMaterial', 'ui.router', 'restangular']);
angular.module('app.filters', []);
angular.module('app.services', []);
angular.module('app.directives', []);
angular.module('app.config', ['ngMaterial']);
})();



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

Accessing parameters in Request

I have a question about obtaining parameters from Request object.

What is the difference between

$name = $request->name;

OR

$name = $request->input("name");

They show the same behavior. I am asking that from the typing perspective, it is faster to utilize #1 method. But I don't know the difference. Is #1 prone to SQL injections?



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

Catch exception from controller in middleware

I have a laravel controller that can throw an exception, and a global middleware that catches that exception. In semi pseudo code:

// App\Controllers\...
class Controller {
  function store() {
    throw new FormException; // via validation etc, but it's thrown here
  }
}

// App\Http\Middleware\...
class Middleware {
  function handle(Closure $next) {
    try {
      // Breakpoint 1
      return $next();
      // Breakpoint 2
    }
    catch (FormException $ex) {
      // Breakpoint 3
      exit('FormException caught!');
    }
  }
}

The problem is that the exception is never caught. Somwhere in the pipeline, the application catches the exception and prints a pretty error page, but it should be caught by my middleware so it can handle it properly.

  • Breakpoint 1 should trigger, and it does << good
  • Breakpoint 2 shouldn't trigger, and it doesn't << good
  • Breakpoint 3 should trigger, but it doesn't << what??

The only way I can imagine my middleware not catching it, is if it's caught somewhere deeper inside the pipeline, not further up/around, but I can't find any try/catch in other middleware, or in the pipeline execution code.

Where is this exception caught? Why?

This might not be a great pattern, but I don't care about that now. I'm more curious than anything else. Do I completely misunderstand Laravel's middleware?

Relevant Laravel code:

  • Kernel::handle() starts the middleware pipeline << this has a catch-all catch(), but my catch() comes first, right?
  • Pipeline::then() starts the middleware execution
  • Pipeline::getSlice() handles and creates the $next closures


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

How to convert this short if statement in Laravel into a long one?

I have a short if else statement that I'm having trouble converting into a full one.

The reason is I would like to include some html inside instead of just text.

Auth::user()->likes()->where('status_id', $status->id)->first() ? Auth::user()->likes()->where('status_id', $status->id)->first()->like == 1 ? 'You like this post' : 'Like' : 'Like'



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

Need to 'convert' an MySQL-query to Eloquent; where to start / how to think?

I'd like to 'convert' a raw SQL-query to Eloquent, so I can have eager loaded models attached too, so I don't have to edit some templates I got. Problem is, the query got some subqueries and I do not know how to 'convert' the query into Eloquent's format. The query in question is:

SELECT e_eh.id, s.name as serie, s.id as serie_id, e_eh.season, e_eh.episode, e_eh.name, eh1.prog_trans, eh1.prog_check, eh1.prog_sync, eh1.avi FROM ( SELECT e.* , ( SELECT eh.id FROM episode_histories AS eh WHERE 1 AND eh.episode_id = e.id ORDER BY eh.id DESC LIMIT 1 ) AS eh_id FROM episodes AS e WHERE 1 AND e.completed = 0 AND e.deleted_at IS NULL ) AS e_eh INNER JOIN episode_histories AS eh1 ON e_eh.eh_id = eh1.id INNER JOIN series as s ON s.id = e_eh.serie_id ORDER BY prog_trans DESC, prog_check DESC, prog_sync DESC

I've tried a few things already, but none have worked. I'm a bit stuck in how to "think" this into Laravel / Eloquent. Documentation from Laravel itself is also not much helpful.

In a nutshell: I've got two models, one is episodes, other is episode_histories, whichs stores some history on related episode. A third model is the show model, the related show for it. I need to get an episode, with related show model (is a relation in my model already). but I also need to get the latest episode_histories model for given episode.

What I currently have in my models:

Episode: `class Episode extends Model { use SoftDeletes; use App\History; // The history model

protected $table        = 'episodes';
protected $primaryKey   = 'id';
public    $timestamps   = true;

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = ['deleted_at'];

/* Eloquent relations */
public function show() {
    return $this->belongsTo('App\Serie', 'serie_id', 'id');
}

public function history() {
    return $this->hasMany('App\History', 'episode_id', 'id')->orderBy('id', 'desc');
}

public static function getEpisodes2() {
    return DB::select();
}

}And my history model looks like this: class History extends Model { use SoftDeletes;

protected $table        = 'episode_histories';
protected $primaryKey   = 'id';
public    $timestamps   = true;

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = ['deleted_at'];

/* Eloquent relations */
public function episode() {
    return $this->belongsTo('App\Episode');
}

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

/* Custom functions */

}` I hope someone can help me out on this.



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

Laravel Query Builder: Caching a list result

It's possible to cache query result like so:

$users = DB::table('users')->remember(10)->get();

But how do I cache a list result. This doesn't work:

$roles = DB::table('roles')->lists('title'); // Works, but not cached.
$roles = DB::table('roles')->remember(10)->lists('title'); // Not working.

Error thrown:

exception 'BadMethodCallException' with message 'Call to undefined method Illuminate\Database\Query\Builder::remember()'



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

Laravel Redirect /login route

How do I redirect the user if they visit www.myapp.com/login or http://ift.tt/2acaYvR to a different domain/route?

In Laravel 5.2 which controller actually loads the views for login & register?



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

get by latitude and longitude in laravel 5 with other joins

This is quite a complicated one for me. I have a route that is a search - which works quite well, except I am unable to search by postcode to find the nearest to the lat and long of a given postcode. That is, I can work out the lat and long, but I am not sure how to integrate it to my existing query. This query is the search query without postcodes:

$query = DB::table('dogs');
$query->leftJoin('dog_addresses','dogs.id','=','dog_addresses.dog_id');
$query->leftJoin('dog_videos','dogs.id','=','dogs_videos.dog_id');
$query->leftJoin('dogs_breeds','dogs.breed_id','=','dogs_breeds.id');
if($request->input("breed") && $request->input("breed") != "" && $request->input("breed") != "any")
    {
        $breed = Dog_Breed::where("breed_name", $request->input("breed"))->first();
        $query->where('dogs.breed_id', $breed->id);
    }
$results = $query->get();

I have something to add to the query to get the latitude and longitude of the postcode:

if($request->input("postcode")) 
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_URL, "http://ift.tt/1Ot6dhd" . $request->input('postcode'));
    $result = json_decode(curl_exec($curl));
    curl_close($curl);
    $postcode_lat = $result->result->latitude;
    $postcode_long = $result->result->longitude;            
}

This lets me get my postcode latitute and longitude. But I don't then know how to get the dogs by location based on the lat and long columns present in the dog_addresses table, which is joined to the dogs table. How do I do this?

So if my dog_addresses table has the columns Lat and Long.

So dogs:

id | user_id | dog_name | age

dog_addresses:

id | dog_id | address_line_1 | town | postcode | lat | long

So for my query I need to get all dogs, where bred ID is 1, but I want to inner join videos so I can get all video information and addresses information, but I also want to sort the order of dogs returned by how close they are to my inputted postcode, based on lat and long.

I'm very confused. I found this:

( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance

But I'm still not sure how to integrate it, or what use it is for me. Please help



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

How to route back to the desired page with passing parameters using laravel?

I am working on Laravel 5.0. I want to return back from my current page to the previous page with passing parameter. I have an id of all images and galleries in my urls. After clicking on a particular image, i move to another page with the id of that image in my url, Now, i want to return back to my gallery page to which that image belongs to.

My controller:

public function viewgallerypics($id){
    $gallery= Gallery::findorFail($id);
    return view('dropzone' , ['gallery'=>$gallery]);
     }

public function bigimage($id){
   $gallery=Gallery::all();
   $image=image::findorFail($id);
   return view('bigimage' , ['image'=>$image,'gallery'=>$gallery]);

   }

My routes:

   Route::get('/image/big/{id}' ,[
   'uses'=>'GalleryController@bigimage',
   'as'=>'bigimage'
   ]);


   Route::get('/gallery/view/{id}' ,[
   'uses'=>'GalleryController@viewgallerypics',
   'as'=>'viewpics'
   ]);

My view:

<section class="col-md-1">
<a class="btn btn-primary btn-lg" 
href="HERE, WHAT I HAVE TO PASS TO GET MY DESIRED
PAGE????">Back</a>
</section>

My desired page where i want to return back depending on the id pass through the route:

  <div class="row">
 <div class="col-md-offset-1 col-md-10">
 <div  id="gallery-images">
 <ul>
 @foreach($gallery->images as $image)
 <li>
 <a href="">
 <img id="jumboimage2" src=""></a>
 </li>
 <li>
 <a href="" id="margin">
 <span id="margin" class="glyphicon glyphicon-remove-sign"></span></a>
 </li>
 @endforeach
 </ul>
 </div>
 </div>
 </div>



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

Save SQL queries and execute them later in Laravel 5.2?

I have two types of users in my Laravel application and I'd like them to have different permissions.

I want the admin to be able to create, retrieve, update and delete some objects stored on my database. And the common user to be able to only retrieve these objects. But, I'd like to have them ask for permission on the other actions, and then, have an admin execute them. I imagined the common users going through almost the whole proccess, but near the end, instead of executing the query, the application should save it in the "requests" table.

The "requests" table would have the following collumns:

  • id int auto_increment
  • user_id int (would be the id of the user that requested the action)
  • date date (so the admin knows when the request was made, I would just get the current time when the user tries to execute)
  • query string (this would be the query generated by laravel)

My doubts are, is it possible to save the query in Laravel before it is executed? If so, how do it? Also, after it's on my table, how can I run it later?



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

Laravel doesn't running my route

I'm beginner in Laravel 5. I created a model(Cars), a controller(CarController) and a view(show.blade.php). But, everytime that I try to execute my project, I get the same error:

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

1/1
NotFoundHttpException in RouteCollection.php line 161:
in RouteCollection.php line 161
at RouteCollection->match(object(Request)) in Router.php line 821
at Router->findRoute(object(Request)) in Router.php line 691
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54
at require_once('C:\xampp\htdocs\laravel\public\index.php') in server.php line 21

These are my codes:

Car.php (Model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    //
}

2016_07_30_135543_create_cars_table.php

<?php

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

class CreateCarsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->increments('id');
            $table->string('make');
            $table->string('model');
            $table->date('produced_on');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('cars');
    }
}

CarController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Car;

class CarController extends Controller
{
    //
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
        $car = Car::find($id);
        return view('cars.show', array('car' => $car));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}

show.blade.php

<!DOCTYPE html>
<html>
  <head>
    <title>Car </title>
  </head>
  <body>
    <h1>Car </h1>
    <ul>
      <li>Make: </li>
      <li>Model: </li>
      <li>Produced on: </li>
    </ul>
  </body>
</html>

routes.php

<?php


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

Route::resource('cars', 'CarController');

I try: localhost:8000/laravel/public/cars localhost:8000/laravel/public/cars.show localhost:8000/laravel/public/show

I don't know why this is happening. Can anyone help me?



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

Wrong validator redirect with laravel (phpunit)

I tried to test a form (post) with phpunit and Laravel.

I use the validator to check that my two inputs are filled. On graphical use my code totally works. When an input was not filled i'm redirected on form page with errors and old inputs informations.

But when i try to launch my unit tests with phpunit the validator does not redirect on the URL of the form when the validation fail, I'm redirect on an other page completely beside the point.

For information, I reach the form page. The problem become after sending the form with post method.

This is my routes :

Route::group(['prefix' => 'users', 'middleware' => ['web', 'auth']], function() {

Route::get('/', 'DashboardUsersController@users');
Route::get('/create', 'DashboardUsersController@usersCreateView');

Route::post('/create', 'DashboardUsersController@userCreate');

The controller :

public function userCreate(Request $request){
    $data = Input::all();

    $this->validate($request, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users'
    ]);

    $password = User::random_password(12);
    $data['password'] = $password;
    Mail::send('auth.emails.register', $data, function($message) use ($data){
        $message->from('donotreply@****.fr', 'Test');
        $message->to($data['email']);
    });

    User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($password),
    ]);
    Session::flash('success', "L'utilisateur a été ajouté avec succès.");
    return redirect('/users');
}

My simple unit test :

public function testAddUser(){
    $user = factory(App\User::class)->create();

    //Verify that empty form redirect with errors
    $resp = $this->actingAs($user)
        ->visit('/users/create')
        ->click('Ajouter')
        ->see(trans('validation.required', ['attribute' => 'Nom']));

     //More when this validate...
}

And to finish the error message gave by phpunit on account of the wrong redirection and see() assertion :

Failed asserting that the page contains the HTML [Le champ Nom est obligatoire.]. Please check the content above.

Anyone got an idea of the problem ?



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

Laravel basic auth slow performance

I'm implementing an API using Laravel5 with MySQL database. The endpoints are very simple: there is 'customers' table and API CRUDs it's data.

The problem is the following:

API endpoints are protected by Basic HTTP-auth, implemented by standard Laravel5 functionality in middleware

$response = $this->auth->guard($guard)->basic();

And it has very slow performance. Curl trace shows, that with this middleware enabled the request is processed during 0.6 sec. Without this middleware - during 0.2 sec.

To my mind it is too much to just fetch one row from a simple table.

Do you know the possibilities, how to make this auth work faster. Maybe use another type of auth or implement custom Basic Auth Middleware where just check for login/pass in database?



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

Is it possible to create custom relationships in Laravel models?

I have a relationship which is neither One-To-One nor One-To-Many and I was wondering if it's possible to express a custom relationship in Laravel/Eloquent models.

Essentially I have products which belong to a single category, but multiple products can belong to the same category. The products table stores the category_id. This obviously isn't One-To-One as categories are reused and Laravel would require a product_id foreign key on the categories table. It is closer to a One-To-Many, which is limited to a single item, but I'd prefer having to avoid making an additional category_product table to define a single relationship. I suspect this is a Many-To-One relationship?



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

Laravel 5 - Class 'DB' not found

I have ChatController located in app/http/controllers like so:

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use DB;

class ChatController extends Controller implements MessageComponentInterface {

    protected $clients;

    function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) 
    {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $conn, $msg) 
    {
        foreach ($this->clients as $client) 
        {
            if ($client !== $conn )
                $client->send($msg); 

            DB::table('messages')->insert(
                ['message' => $msg]
            );
        }
    }

    public function onClose(ConnectionInterface $conn) 
    {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) 
    {
        echo 'the following error occured: ' . $e->getMessage();
        $conn->close();
    }

}

And I have chatserver.php file in the root like so:

<?php
require  'vendor/autoload.php';

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;


$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ChatController()
        )
    ),
    8080
);

$server->run();

If I remove

DB::table('messages')->insert(
                    ['message' => $msg]
                );

from the ChatController and start chatserver.php it works, but if I don't remove it then the server starts but as soon as I send a message I get this error:

Fatal error: Uncaught Error: Class 'DB' not found in C:\wamp\www\laraveltesting\app\Http\Controllers\ChatController.php:31

Why won't it use DB? I am extending the laravel controller.



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

Is it a good idea to edit .env dynamically in Laravel 5?

I need to make some settings of my Laravel 5 app configurable to end users through front-end interface. My initial thoughts were to utilize Cache facade, getting user-defined configs from there:

<?php
// app/config/custom_settings.php

return [
    'key' => Cache::get('key');
];

However, It appears, that Facades are loaded after the config files in Laravel, so the above code doesn't work.

Because of this, I am thinking about writing the user's configuration directly into .env file programmatically. Is this a good idea, or can it turn into a headache in the future?



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

Laravel Team-Game relationship

I'm building a website that involves a schedule of basketball games. I have 2 tables for this: teams and games.

As for the relationships between the models. For Game I got this:

public function homeTeam()
{
    return $this->belongsTo('App\Team\Team', 'home_team');
}

public function awayTeam()
{
    return $this->belongsTo('App\Team\Team', 'away_team');
}

But what should I do for the Team model? By the games() method inside it, I want to get all the team's games, home and away, and for this I need to reference both home_team and away_team columns on the games table.



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

mcrypt_encrypt(): Key of size 4 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported

I have changed my APP_KEY in .env file to 32char string , but it didnt work.

other than this error it also showed some other errors like UNDEFINEDINDEX : APP_KEY Undefined index: APP_DEBUG UNDEFINED INDEX : HTTP_HOST UNDEFINED INDEX : DB_HOST and almost all content of .env file are the right hand side of undefined index example UNDEFINED INDEX : DB_HOST



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

How to Route back with passing parameters using Laravel?

I am working on Laravel 5.0. I want to return back from my current page to the previous page with passing parameter. I have an id of all images and galleries in my urls. After clicking on a particular image, i move to another page with the id of that image in my url, Now, i want to return back to my gallery page to which that image belongs to.

My controller:

   public function viewgallerypics($id){
        $gallery= Gallery::findorFail($id);
        return view('dropzone' , ['gallery'=>$gallery]);
         }

    public function bigimage($id){
       $gallery=Gallery::all();
       $image=image::findorFail($id);
       return view('bigimage' , ['image'=>$image,'gallery'=>$gallery]);

       }

My routes:

       Route::get('/image/big/{id}' ,[
       'uses'=>'GalleryController@bigimage',
       'as'=>'bigimage'
       ]);


       Route::get('/gallery/view/{id}' ,[
       'uses'=>'GalleryController@viewgallerypics',
       'as'=>'viewpics'
       ]);

My view:

    <section class="col-md-1">
    <a class="btn btn-primary btn-lg" 
    href="HERE, WHAT I HAVE TO PASS TO GET MY DESIRED
    PAGE????">Back</a>
    </section>

My desired page where i want to return back depending on the id pass through the route:

 <div class="row">
 <div class="col-md-offset-1 col-md-10">
 <div  id="gallery-images">
 <ul>
 @foreach($gallery->images as $image)
 <li>
 <a href="">
 <img id="jumboimage2" src=""></a>
 </li>
 <li>
 <a href="" id="margin">
 <span id="margin" class="glyphicon glyphicon-remove-sign"></span></a>
 </li>
 @endforeach
 </ul>
 </div>
 </div>
 </div>



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

Unlink : permission denied (Laravel)

Here, I want to download backup database For that i have user following code in handle() method in console\command.So when i run the command , it should download the backup database. But I'm getting following Error while running the command:

[ErrorException]                                
 unlink(2016-07-30_07-38.sql): Permission denied 

Here is my handle() method code:

 public function handle()
    {
        $date = Carbon::now()->format('Y-m-d_h-i');
        $user = env('DB_USERNAME');
        $password = env('DB_PASSWORD');
        $database = env('DB_DATABASE');
       $command = "mysqldump --user={$user} -p{$password} {$database} > {$date}.sql";        
        $process = new Process($command);
        $process->start();
        while ($process->isRunning()) {
            $public = Storage::disk('public');
            $public->put('acl/' . $date . ".sql", file_get_contents("{$date}.sql"));
            unlink("{$date}.sql");
        }
    }

If anyone found the same problem or have the solution please help me to find it out.



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

vendredi 29 juillet 2016

Like/Dislike with jQuery AJAX returns 500 (Internal Server Error) but works when I reload the page

I have a Like Status button that sends data using AJAX to the controller.

When I click the button, the button changes from "like" to "dislike" and all the classes and form action get changed as well.

The problem is, if I like the status, I see the changes reflected, but if I decided to dislike it without reloading the page, I get this error

GET http://localhost/socialnet/public/likestatusCount/undefined 500 (Internal Server Error)

If I reload the page and click dislike, my vote gets removed from the database and the button changes back to "like"

It works if I reload the page.

If I remove the get() request to retrieves the likes count, nothing happens and console.log() returns an empty row, I don't see any data being returned.

I opened laravel.log and I saw this error

local.ERROR: exception 'ErrorException' with message 'Trying to get property of non-object' in C:\xampp\htdocs\socialnet\app\Http\Controllers\FeedController.php:140

which is this line in getlikesCounter() method

return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);

I am using Laravel 5.2

The form in the view

@if(\App\StatusLikes::where(['status_id' => $status->id, 'user_id' => Auth::user()->id])->first())
    {!! Form::open(['action' => 'FeedController@dislikeStatus', 'id' => 'dislike_form', 'class' => 'dislikeform']) !!}
    <button type="submit" class="btn btn-danger btn-xs dislike" data-user="" data-status="" id="dislike-status">
       <i class="fa fa-thumbs-down"></i> <span class="dislike-button-text">Dislike</span> <span class="dislike-button-counter">()</span>
    </button>
   {!! Form::close() !!}
   @else
   {!! Form::open(['action' => 'FeedController@likeStatus', 'id' => 'like_form', 'class' => 'likeform']) !!}
     <button type="submit" class="btn btn-info btn-xs like" data-user="" data-status="" id="like-status">
       <i class="fa fa-thumbs-up"></i> <span class="like-button-text">Like</span> <span class="like-button-counter">()</span>
      </button>
   {!! Form::close() !!}
@endif

The methods in the controller for like, dislike, and get likes count

public function likeStatus() {
    if (Input::has('like_status')) {
        $status = Input::get('like_status');
        $selectedStatus = Status::find($status);

        $selectedStatus->likes()->create([
            'user_id' => Auth::user()->id,
            'status_id' => $status
        ]);

        $response = [
            'status' => 'success',
            'msg' => 'You have liked this status',
        ];

        return Response::json($response);
        //return redirect(route('feed'));
    }
}

public function dislikeStatus() {

    if (Input::has('dislike_status')) {
        $status = Input::get('dislike_status');
        $selectedStatus = Status::find($status);

        $selectedStatus->likes()->where('user_id', Auth::user()->id)->delete([
            'status_id' => $status
        ]);

        $response = array(
            'status' => 'success',
            'msg' => 'You have disliked this status',
        );

        return Response::json($response);
        //return redirect(route('feed'));

    }
}

public function getlikesCounter($id) {
    $status = Status::find($id);
    return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);
}

The javascript form likeform and dislikeform

$('.likeform').submit(function(e) {
    e.preventDefault();

    var submitBtn = $(this).find('.like');
    var form = $(this).find('.likeform')
    var likeText = $(this).find('span.like-button-text');
    var likeCounter = $(this).find('span.like-button-counter');
    var status_id = submitBtn.data('status');
    var user_id = submitBtn.data('user');
    var token = $('input[name=_token]').val();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': token
        }
    });

    $.ajax({
        url: 'http://localhost/socialnet/public/likeStatus',
        method: 'POST',
        cache: false,
        data: { like_status: status_id, user_id: user_id, _token: token },
        success: function(data) {
            submitBtn.removeClass('btn-info').addClass('btn-danger');
            submitBtn.find($(".fa")).removeClass('fa-thumbs-up').addClass('fa-thumbs-down');
            submitBtn.closest("form").removeClass('likeform').addClass('dislikeform').attr('id', 'dislike_form').attr('action', 'http://localhost/socialnet/public/dislikeStatus');
            submitBtn.closest("form").find("input[name=like_status]").attr('name', 'dislike_status');
            submitBtn.removeClass('like').addClass('dislike');
            submitBtn.find($(".like-button-text")).removeClass('like-button-text').addClass('dislike-button-text');
            submitBtn.find($(".like-button-counter")).removeClass('like-button-counter').addClass('dislike-button-counter');
            likeText.text('Dislike');

            $.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
                likeCounter.text('(' + data.count + ')');
            });

            console.log(data);
        },
        error: function() {
            console.log('error');
        }
    });
});

$('.dislikeform').submit(function(e) {
    e.preventDefault();

    var submitBtn = $(this).find('.dislike');
    var form = $(this).find('.dislikeform')
    var likeText = $(this).find('span.dislike-button-text');
    var likeCounter = $(this).find('span.dislike-button-counter');
    var status_id = submitBtn.data('status');
    var user_id = submitBtn.data('user');
    var token = $('input[name=_token]').val();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': token
        }
    });

    $.ajax({
        url: 'http://localhost/socialnet/public/dislikeStatus',
        method: 'POST',
        cache: false,
        data: { dislike_status: status_id, user_id: user_id, _token: token },
        success: function(data) {
            submitBtn.removeClass('btn-danger').addClass('btn-info');
            submitBtn.find($(".fa")).removeClass('fa-thumbs-down').addClass('fa-thumbs-up');
            submitBtn.closest("form").removeClass('dislikeform').addClass('likeform').attr('id', 'like_form').attr('action', 'http://localhost/socialnet/public/likeStatus');
            submitBtn.closest("form").find("input[name=dislike_status]").attr('name', 'like_status');
            submitBtn.removeClass('dislike').addClass('like');
            submitBtn.find($(".dislike-button-text")).removeClass('dislike-button-text').addClass('like-button-text');
            submitBtn.find($(".dislike-button-counter")).removeClass('dislike-button-counter').addClass('like-button-counter');
            likeText.text('Like');

            $.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
                likeCounter.text('(' + data.count + ')');
            });

            console.log(data);
        },
        error: function() {
            console.log('error');
        }
    });
});



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

Laravel 5.1 Complicated Relationship Query Builder

Relationship: Receipt hasMany LineItems

$columns = ['rece_id','rece_user_id','rece_name','rece_date']

$builder = Receipt::select($columns)
        ->with('lineItems')
        ->where('rece_user_id', Auth::user()->id)

dd($builder->get()->toArray());

Above code gives me the receipts with their all respective related line items (all columns).

I need only first line item's one column e.g. liit_description. (I need that as another column in $columns list).

Is this even possible with Eloquent?



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

jQuery get() request retrieves data before the new data has been submitted

The title may be a bit vague, sorry about that, allow me to explain.

I have a users_status_likes table with the follow columns: id, user_id, status_id

The idea is simple, when a user clicks the like button of a status, the data gets submitted to the database with the logged in user_id and the status_id of the status.

Now, I'm trying to do a get() request to retrieve the number of likes a status has. The problem is, the get request is retrieving the number of likes the status had before the new like has been added.

For example, there's a status that has 1 like, but then I click the like button, so now it has 2 likes, there are 2 rows in the table for the same status_id but each has a different user_id. When I click the like button, the console says count 1 but it really should be count 2 because I just liked the status and data has been submitted to the table.

I am using Laravel 5.2, so let me start by posting the route

Route::get('likestatusCount/{id}', 'FeedController@getlikesCounter');

The getlikesCounter() method in FeedController

public function getlikesCounter($id) {
    $status = Status::find($id);
    return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);
}

And the form inside the view

{!! Form::open(['action' => 'FeedController@likeStatus', 'id' => 'like_form', 'class' => 'likeform']) !!}
          <button type="submit" class="btn btn-info btn-xs like" data-user="" data-status="" id="like-status">
          <i class="fa fa-thumbs-up"></i> <span class="like-button-text">Like</span> <span class="like-button-counter">()</span>
          </button>
{!! Form::close() !!}

The javascript

$('.likeform').submit(function(e) {
    e.preventDefault();

    var submitBtn = $(this).find('.like');
    var likeText = $(this).find('span.like-button-text');
    var likeCounter = $(this).find('span.like-button-counter');
    var status_id = submitBtn.data('status');
    var user_id = submitBtn.data('user');
    var token = $('input[name=_token]').val();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': token
        }
    });

    $.ajax({
        url: 'http://localhost/socialnet/public/likeStatus',
        method: 'POST',
        cache: false,
        data: { like_status: status_id, user_id: user_id, _token: token },
        success: function(data) {
            submitBtn.removeClass('btn-info').addClass('btn-danger');
            submitBtn.find($(".fa")).removeClass('fa-thumbs-up').addClass('fa-thumbs-down');
            likeText.text('Dislike');
            console.log(data);
        },
        error: function() {
            console.log('error');
        }
    });

    // data.count returns the count before the new like has been submitted
    $.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
        likeCounter.text(data.count);
        console.log(data.count);
    });
});



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

Cache facade not working in Laravel 5

I have following code located in App/Http/Helpers/helpers.php:

<?php 
use Illuminate\Support\Facades\Cache;

function putIntoCache(){
    Cache::put('foo', 'bar');
}

When calling putIntoCache() function in app/config/custom.php, I get the following message:

Fatal error: Call to a member function put() on a non-object in D:\www\project\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 216

How to fix this?



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

Extra rows before file download laravel 5.1

Before downloading a file by user I want to log it in the database that user downloaded which file, so I implemented this function below:

  public function downloadTheme(Theme_lang $themLang)
{

    $userOrdered=$this->getUserOrdered();

   if(($themLang->is_free==1) || (in_array($themLang->id,$userOrdered))){
        Theme_download::create(['user_id'=>Auth::user()->id,'theme_lang_id'=>$themLang->id]);
        $file=base_path($themLang->download_url);
        return response()->download($file);
   }else{...}
}

But the problem is when I check the database I see there are extra duplicated rows inserted there! So how can I solve it?



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

Setting elixir not to merge css files

Is there a way to prevent elixir from merging my assets? My code:

mix.sass(['comingsoon/*.scss', 'comingsoon/**/*.scss'], 'public/assets/comingsoon/css')
        .scripts(['comingsoon/*.js', 'comingsoon/**/*.js'], 'public/assets/comingsoon/js');

I set this to compile all of my sass and js files, but I want to keep the files separate just the way I separate my pre-compiled files. For example, I have home.scss and contact.scss, I want them to be compiled into home.css and contact.css instead of them being merged to app.css.

Ho do I do that?



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

Amazon S3 Upload error SSL certificate issues

I'm trying to test Laravel Amazon S3 on my localhost but keep getting the same error:

S3Exception in WrappedHttpHandler.php line 192: Error executing "ListObjects" on "http://ift.tt/2a5Tg1p"; AWS HTTP error: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://ift.tt/1mgwZgQ)

My code :
$s3 = \Storage::disk('s3'); $filePath = '/images/' . $filename; $s3->put($filePath, file_get_contents($image), 'public');



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

How to add custom config file to app/config in Laravel 5?

I want to add custom_config.php to app/config directory of my Laravel 5 project, but can't find any article explaining this process. How is this done?



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

Exclude Laravel-specific values from request

I want to run json_encode($request->all()) after a form is submitted, however the returned array is "polluted" with _method and _token values.

Is there any neat way to exclude the framework-specific fields from the generated json?



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

Don't know how to manage in laravel this database reality

I have this tables:

admins places grants

Each Admin has 0-N Place. Each Place has 0-N Grant. So we have:

admin_place grant_place (this one has an autoincremental id)

Now what I want to do is that, each Admin could have 0-N of those grant_place. So I have a table:

admin_grant_place

How do I express this in my Laravel app?

I have the Admin, Place and Grant Model classes. But, for example, how can I get all the grant_place that an Admin has?.

Thank you,



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

How to set an array inside $_SESSION in Laravel 5?

I have this code:

Session::set('dt[global][temp][arrLanguage_selector]', $arrLanguage_selector);

and

Session::set('dt[global][env][country]', $country);

Later in others page I will try to get these values back with:

$global = Session::get('dt[global]');
$env= $global[env][country]ç
$lang = [temp][arrLanguage_selector];

But it is not working. It is returning null

What am I missing?



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

Placing a loading screen in laravel while getting data from server

I'll try to explain. I have a dynamic view that display in a list all the results that my query gets. each element has a "view" button. That button is a get request that handles the action to my controller. The problem is that it takes a long time to bring the info of the element to display its info. I wanna put a loading screen while the GET is finished but I've tried a lot of solutions but none solve my problem .

Here's my route

Route::get('/certificaciones/consultar/{id}&{tipo}&{order_id}&{count}', [
    'uses' => 'certificacionesController@preview',
    'as' => '/certificaciones/consultar/vistaPrevia']);

i do the calling here

<td style="width: 5px;"><a href=""><button class="btn btn-xs pink tooltips" data-placement="top" data-original-title="Consultar" id="loading"><i class="fa fa-eye"></i></button></a></td>

What i want is when the user click that button, it shows a loading screen while the controller is done getting all data and display the preview blade

I hope I made myself clear and please help me I'm stuck there



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

Laravel join inside controller

I'm trying to print out from array into view but it always says ('Illuminate\Database\QueryException with message 'SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'stations' (SQL: select * from stations inner join stations on stations.id = users.station)'

This is function inside controller

public function show()
    {
$users = App\Classes::join('stations','stations.id','=', 'users.station');
return view('configuration.configuration', compact($users));
}

This is model Stations and model users

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

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

and the foreign key is in table users

$table->integer('station')->nullable()->unsigned()->default(null);
$table->foreign('station')->references('id')->on('stations')->onDelete('cascade');



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

MD5 Password login is not working laravel 5

I want to change my password field bcrypt to md5. In database i am storing password in md5 but login is not working

myController:

 public function postLogin(Request $request)
 {
   $this->validate($request, array('username' => 'required', 'password' => 'required'));
$credentials = $request->only('email', 'password');

if (Auth::validate($credentials)) 
{
    $user = Auth::getLastAttempted();
    Auth::login($user, $request->has('remember'));
    return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
    'email' => $this->getFailedLoginMessage(),
]);

}



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

How to properly add external php files in Laravel 5

I have a small websockets chat written, the php part is just 2 files, server.php and Chat.php, they are both inside a bin folder and depend on ratchet and some other libraries which I downloaded to the laravel installation via composer.

server.php

require __DIR__.'/../vendor/autoload.php';
require 'Chat.php';

use Ratchet\Server\IoServer;
use Ratchet\http\HttpServer;
use Ratchet\WebSocket\WsServer;

$server = IoServer::factory(new HttpServer(new WsServer(new Chat)), 8080);

$server->run();

Chat.php

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {

    protected $clients;

    function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) 
    {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $conn, $msg) 
    {
        foreach ($this->clients as $client) 
        {
            if ($client !== $conn ) {
                $client->send($msg); 
            }
        }
    }

    public function onClose(ConnectionInterface $conn) 
    {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) 
    {
        echo 'the following error occured: ' . $e->getMessage();
        $conn->close();
    }

}

Now, I have that bin folder inside the laravel root, and so I am able to start the server since the server.php is looking for dependencies in vendor one level up, but what I wanna do is use all the laravel goodies within these files, especially within Chat.php.

So now for example if I write use DB in Chat.php it gives an error (which I understand, it has no way of knowing laravel), so my question is how do I include this bin folder and its files so that I can use all the laravel goodies within them?



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

Laravel Conditional Statement: is when() efficient?

I would like to know about the efficiency / performance of using Laravel's new Conditional Statements when() that comes in the Query Builder functions.

Are they more efficient than a simple variable condition?

Example: i am filtering results with some radio and checkboxes, and they will provide many conditionals, i would like to know the most efficient way of applying them:

Simple conditional:

if($request->has('sale')) $query = $query->sale();

Laravel Conditional statement:

 query->when($request->has('sale'), function ($query){
     return $query->sale();
 })

Thanks in advance, cheers.

Docs: http://ift.tt/1rTRTqH



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

how to pass variables from database to custom error page in laravel

I want to pass variables to my custom error page but i can't do it so can anyone help me , that's my handler.php :

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if($e instanceof NotFoundHttpException)
    {
        return response()->view('errors.404', [], 404);
    }
    return parent::render($request, $e);
    }
}

so can anyone help me please to pass data to this page from database into the page ?



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

Laravel angular2-jwt template requests

I've an interesting question. I have setup a project using Laravel 5 and Angular2 with angular2-jwt. Laravel uses a JWT authentication library (http://ift.tt/1GFm4Yr) and produces tokens upon login, which are then sent over the vast Internet and saved to localStorage.setItem('id_token', response.token) the local machine.

Everything is working fine, but my Laravel controllers use jwt.auth, which requires my Angular2 component template requests to send with them the token. I'm a little lost here, since I seemingly cannot integrate the angular2-jwt library into my @component: templateUrl requests.

This means that I cannot request templates that should only be visible to logged in users, because the template request doesn't contain the token and thus is not authenticated to request those templates.

Can anybody advise or give me directions?

example component that I need to request a template for from Laravel with the jwt token attached to.

@Component ({
    selector: 'app-page',
    templateUrl: '/templates/Main.base',
    directives: [
        ROUTER_DIRECTIVES,
        HeaderComponent,
        UsersComponent,
        ProductsComponent
    ]
})



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

Storing validation rules alongside entries in the database in Laravel 5

I have a Setting model, and a SettingController. They are used for storing application-wide settings as a JSON string into the database.

Problem

Because of the diversity of setting types (checkboxes, inputs, email fields, etc), it is impossible to define the universal validation rules for each setting.

Possible Solution

To solve the problem of having "variable" validation rules, I'm considering storing them as a JSON string in the same table with settings.

Question

My question is, am I heading into the right direction, or am I making some major design flaws that can cause me pain in the future? And is it a good idea to store model's validations in the database?



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

How to display selected values from database to graphs

Actually i wanted to display 5 largest values from a column numberofclick in my database and create graphs for these top 5 data and also when howered shows id from id column so far i have done this....... im using laravel 5.2 and chart.js this is my controller

$click = Click::select(DB::raw("(numberofclick) as count"))

    ->orderBy("numberofclick")

    ->groupBy(DB::raw("(numberofclick)"))

    ->get()->toArray(); 

$click = array_column($click, 'count');



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