lundi 31 octobre 2016

laravel 5 - pass php varaible to jquery or ajax or javascript

I search many in site but i could not find the answer so i post my question. I think for my question has exist easy asnwer but It's first time i use javascript , jquery and ajax and i don't know what to do :(! I use Laravel 5 I have a blade php Page and in this file i have a while that create many < div >s like this chart.blade.php:

<?php $id=0; ?>
@foreach($results as $row)
...

<?php 
 $i++; 
 $allGrade = findData($row);
 echo "<div id=\"container$id\" style=\"...\"></div>";
?>
...
@endforeach

this file create all of my divs with id container1, container2, container3, ... in some case create 100 divs , in some case 1200 divs and it's not constant!

in these divs i want to use a Bar charts , and i use http://highcharts.com/ . One of my question is what is the best way for doing this work? the top of this blade i use this java script function for highchart.js

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ift.tt/Sw98cH"></script>
<style type="text/css">
    $ {
        demo.css
    }
</style>
<script type="text/javascript">
    $(function () {
        for (var i = 0; i < 5000; i++) {
          // Some Alert ****test here ****
            //I put some alert work correctly




            $('#container' + i).highcharts({
                chart: {
                    type: 'bar'
                }
                , title: {
                    text: 'Historic World Population by Region'
                }
                , subtitle: {
                    text: 'Source: <a href="http://ift.tt/1hiu6or">Wikipedia.org</a>'
                }
                , xAxis: {
                    categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania']
                    , title: {
                        text: null
                    }
                }
                , yAxis: {
                    min: 0
                    , title: {
                        text: 'Population (millions)'
                        , align: 'high'
                    }
                    , labels: {
                        overflow: 'justify'
                    }
                }
                , tooltip: {
                    valueSuffix: ' millions'
                }
                , plotOptions: {
                    bar: {
                        dataLabels: {
                            enabled: true
                        }
                    }
                }
                , legend: {
                    layout: 'vertical'
                    , align: 'right'
                    , verticalAlign: 'top'
                    , x: -40
                    , y: 80
                    , floating: true
                    , borderWidth: 1
                    , backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF')
                    , shadow: true
                }
                , credits: {
                    enabled: false
                }
                , series: [{
                    name: 'Year 1800'
                    , data: [107, 31, 635, 203, 2]
    }, {
                    name: 'Year 1900'
                    , data: [133, 156, 947, 408, 6]
    }, {
                    name: 'Year 2012'
                    , data: [JSON.parse('<?php echo json_encode($allGrades[1]); ?>')]
    }]
            });
        }
    });
</script>
</head>

<body>
<div id="container4" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
<div id="container2"></div>
<div id="container3"></div>
<div id="container1"></div> 
. 
.
.

<script src="http://ift.tt/TQup4m"></script>
<script src="http://ift.tt/1rNirHL"></script>
</body>

</html>

The value of allGrade[1] is 20 , and when I use this alert test in Alert test section as below

   var d = <?php echo json_encode($allGrades); ?>; //Don't forget the extra semicolon!
        //alert(d[1]);

  j++;
  var newJ = JSON.parse('<?php echo json_encode($allGrades); ?>');
  var c1 = newJ[1];
  var c2 =newJ[2];
  alert(c1);
  alert(JSON.parse('<?php echo json_encode($allGrades[1]); ?>'));

alerts work and shows data 20 in alert box!

I Expect for Data Year 2012 when i put c1 or put JSON.parse('') the chart data be 20 , But when i put these two items don't work!



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

Change the laravel hasing mechanism to encrypt and store the password in users table

As laravel uses its own mechanism to encrypt and save the password in users table. But i want to change the password encryption mechanism and want to write my own, also the two inbuilt function of laravel authentication should work according to my my password encryption mechanism

check() and attempt()

Anyone please tell me how to do that..



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

Laravel change id column to userId in users table

i am trying to change the id of users table to userId, but laravel authentication mechanism always checks for id column of users table.like

Users::check() and Users::attempt()

these functions always check for id attribute of users table, how to change this behavior of laravel.



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

Laravel 5 Session Timeout store details in database

Let's say I have set the session lifetime to 15 minutes,so by default, laravel will auto logout the user after session timeout. What I want to do now is to log this action in database saying that this user has been logged out due to session expired.

Can anyone just give me an idea on how to do it?



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

Laravel Model Factory Freezes PHPUnit test

I have this test that checks getting a list of bank accounts. If I remove the factory line the test will run and fail as no record was created, but with it there the test just hangs and spikes my CPU.

public function get_list_of_bank_accounts()
    {
        $user = $this->newLoggedInUser();
        factory(App\BankAccount::class)->create(["account_id" => $user->account_id]);

        $json = $this->get($this->url . "/", $this->userAuthHeader($user));
        $json->assertResponseStatus(200);
        $bankAccounts = self::jsonToArray($json);
        $this->assertEquals(1, count($bankAccounts));
    }

If I output $bankAccount after the line I get the output and the tests stop so it does not seem to hang because of the factory and then the get request will run if I do not have the factory so I do not know why these combined is breaking.

public function get_list_of_bank_accounts()
    {
        $user = $this->newLoggedInUser();
        $bankAccount = factory(App\BankAccount::class)->create(["account_id" => $user->account_id]);
        dd($bankAccount);    

        $json = $this->get($this->url . "/", $this->userAuthHeader($user));
        $json->assertResponseStatus(200);
        $bankAccounts = self::jsonToArray($json);
        $this->assertEquals(1, count($bankAccounts));
    }



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

Acces collection on laravel 5.2

I'm using entrust for my roles and permissions on laravel 5.2 and I have this on my controller:

$user = Auth::user();
    $rol = $user->roles;
    dd($rol);

in my User model:

 public function roles(){
    return $this->belongsToMany('Nini\Role','role_user');
}

And get this: Snapshot

I'm tryng to acces and show "display_name" on my view and i can't, help! Thanks in advance.



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

How to install mongodb on homestead - vagrant environment for laravel?

I have recently installed homestead for Laravel using vagrant. The provided configuration does not contain the mongodb installation which i want to install. I have tried to manually ssh into the vagrant and then try to install the mongodb using sudo apt-get install mongodb-server and sudo apt-get install php7.0-mongodb, but this does not seem to install mongodb.

Moreover, when i destroy the vagrant instance and start it again, all my configurations related to mongodb are lost and i had to perform the installation again.

Could the experts here please help me out with mongodb installation on laravel-homestead installation?



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

Angular returning array values wrapped in []

I am working on teaching myself Angular at the moment, and I am currently getting to grips with sending http requests from my angular front-end.

I am successfully sending a POST request, and I am also getting the correct error response back. The error response returned is from Laravel and basically a JSON response.

return Response::json(['message' => $validator->errors()], 422);

This returns something that looks like,

{"message":{
    "first_name":["The first name field is required."],  
    "surname":["The surname field is required."],  
    "email":["The email field is required."],  
    "school_name":["The school name field is required."]
 }}

In my angular template I have this in my controller for now,

app.controller('signupController', function($scope, $http){
console.log("...signup controller initialised...");
$scope.formData = {};
$scope.error = "";
$scope.processForm = function() {
    console.log($scope.formData);
    var postForm = $http.post('http://ift.tt/2f2sAQV', $scope.formData);
    postForm.success(function(data, status, headers, config) {
        $scope.message = data;
    });
    postForm.error(function(data, status, headers) {
        $scope.error = data;
        console.log($scope.error);
    });     
}

});

In my template I form entries that looks like this,

<div class="form-group">
        <label for="firstName" class="is-required">First Name</label>
        <input type="text" class="form-control" id="firstName" name="first_name" ng-model="formData.firstname" ng-class="{'has-error': error.message.first_name}">
        <div class="error__block"></div>
    </div>

Now on error the form input get the has-error class assigned, but the error block shows something like this,

["The first name field is required."]

When I would have thought it would show something like this,

The first name field is required

Am I doing something incorrectly on my laravel end of my angular end?



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

Laravel 5 make the routes know that I am an sending Authorized request

I am stucked with this problem for a few days. I am making a request from a function inside a controller using the snappy library to convert a part of the page to pdf. My plan is this:

Use this $snappy->getOutput('http://ift.tt/2esKIzV'); to take a screenshot of the page and convert it to pdf but whenever i use this it's taking a screenshot of the login page. - even if it is not good for the app i tried to exclude that routes from CSRF verification but still login page is showing on the generated pdf :(

Your suggestions will be very much appriciated. Thank you in advance!



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

How to use ->append v. protected $appends in Laravel

How do you append an attribute to one query but not all of the queries for a model. I know you can add attributes to all queries in the model by adding

protected $appends = ['icon'];

public function getIconAttribute(){
    return Gravatar::src($this->email, 100).'&r=g&d=mm';
}

I want to add it for only one query

$usernames = User::where('username', 'LIKE', '%'.$request->get('search').'%')
   ->append('icon')->get();

but that gives the error Call to undefined method Illuminate\Database\Query\Builder::append()

I can see the method but am feeling dumb http://ift.tt/2e6qRWf



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

Lavarel Facebook connection URL can not be loaded

When i try to load stuff from facebook i get this error from facebook:

URL can not be loaded: The domain of this URL is not added to the domains of this app. Add all domains and subdomains of your app to the Appdomeinen field in the settings of your app to load this URL.

but i added it? i don't understand what to do.

enter image description here

my website is : retailveiling.nl

the facebook callback uses : http://ift.tt/2f24Igb

any help is appreciated



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

How to protect ajax requests in Laravel?

I use ajax to store, update and delete resources associated with authenticated user. Routes for these actions use web middleware so cookies, session etc are available. Project is based on Laravel framework.

Is it necessary to protect those routes from unauthorized access in any additional way? I've read about API tokens that one could use, but I am not sure if it is necessary.

I will be grateful for any insights on ajax security or how ajax requests work in general, as it is a little over my head at this moment.



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

Error on migration:rollback that should drop a column- Using Laravel Homestead & SQlite

I'm getting an error on running "php artisan migrate:rollback" that should drop a column.

I've already ran:
1. composer require doctrine/dbal
2. composer update
3. I even tried "composer dump-autoload"

When I check on the database schema using: "sqlite3 database/database.sqlite" the table contains all the columns (including the one called "excerpt" which is the rogue one that should be dropped) but on running the rollback I get the error that the column isn't published. See below.

(Environment: laravel 5.3- Homestead, Gitbash, Sublime Text3, SQlite3)

The error is as follows:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1 no such column: published (SQL: CREATE TEMPORARY TABLE __temp__articles AS SELECT id, title, body, created_at, updated_at, published at FROM articles)

[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000]: General error: 1 no such column: published

[PDOException]
SQLSTATE[HY000]: General error: 1 no such column: published

My schema is as follows:

CREATE TABLE "migrations" ("id" integer not null primary key autoincrement, "migration" varchar not null, "batch" integer not null);
CREATE TABLE "users" ("id" integer not null primary key autoincrement, "name" varchar not null, "email" varchar not null, "password" varchar not null, "remember_token" varchar null, "created_at" datetime null, "updated_at" datetime null);
CREATE UNIQUE INDEX "users_email_unique" on "users" ("email");
CREATE TABLE "password_resets" ("email" varchar not null, "token" varchar not null, "created_at" datetime null);
CREATE INDEX "password_resets_email_index" on "password_resets" ("email");
CREATE INDEX "password_resets_token_index" on "password_resets" ("token");
CREATE TABLE "articles" ("id" integer not null primary key autoincrement, "title" varchar not null, "body" text not null, "created_at" datetime null, "updated_at" datetime null, "published at" datetime not null, "excerpt" text null);

The Migration that created the column is as follows:

<?php

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

class AddExcerptToArticlesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('articles', function (Blueprint $table) {

        $table->text("excerpt")->nullable();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('articles', function (Blueprint $table) {

        $table->dropColumn("excerpt");

    });
}
}

How do you solve this so that you can seamlessly drop columns using migrate:rollback?



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

Compress files on S3 and download with PHP

I have an app where I need to allow users to download many media items at once, possibly over 500. We do all our storage on S3 and I am finding it difficult to handle a large request of media, potentially over 400 items.

I was wondering, does anybody know of a way to compress the media on S3 and then download a single archive? Is that supported? If not, can anyone recommend a service that would accomplish this?

Our current setup is set to download all the media from S3 and then compress it locally but we are running into server timeouts when we try to accomplish this on a large scale.

Thanks!



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

Laravel 5.3 image upload issue

I am new to laravel 5.3. I need to upload the image to the database table spare. Here is my controller. The error i am getting is also attached.Please help thanks in advance.

 public function store(Request $request)
{
    try{
        $Spare=new Spares;
        $Spare->model_id=$request->get('modelId');
        $Spare->brand_id=$request->get('brandId');
        $Spare->partNumber=$request->get('partNumber');
        $Spare->warranty=$request->get('warranty');
        $Spare->retailer_id=$request->get('retailerId');
        $Spare->quantity=$request->get('quantity');
        $Spare->price=$request->get('price');
        $Spare->description=$request->get('description');
        $file = $request->file('image');

        // Get the contents of the file
        $contents = $file->openFile()->fread($file->getSize());

        $Spare->image=$contents;

        $Spare->save();
        \Session::flash('flash_message','Added new Spare.'); //<--FLASH MESSAGE

        return redirect()->back();
    }
    catch (\Illuminate\Database\QueryException $ex){
        dd($ex->getMessage());
    }
}

I am getting this error.

enter image description here



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

Laravel / Eloquent - Multiple Many to Many Relationships Using One Reference Table

I have a table that looks lie:

enter image description here

The table serves as a reference table between two tables. The kicker is that the second table this reference table serves depends on the value of member_type.

There are three tables being connected using the above table: incidents, user_member_incidents, and server_member_incidents. The member_id column in the reference table references either the user_member_incidents table or the server_member_incidents table. This is determined by the value of the member_type column.

How would I reflect this relationship using a belongsToMany method in Eloquent?



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

Select where with timestamp values null not work

On laravel 5.3 with SqliteDriver

table cpjobs

...
$table->timestamp('created_at')->nullable(false);  // saved data unixtime
$table->timestamp('delayed_at')->nullable(true);  // saved data unixtime
...


| id  | delayed_at | start_at    |
|-----| ---------- | ----------- |
| 2   | null       | 1477912725  |
| 3   | 1478007928 | null        |
| 4   | null       | null        |   

if run on tinker

Cpjob::where('delayed_at', '>', '1478007902')->first();
    => App\Cpjob {#694
         id: "11",
         type: "backup",
         created_at: "1477911786",
         delayed_at: "1478007928",
       } 

But if run a complex for delayed_at > now and start_at null, return empty result, when must be return row with id 4

 Cpjob::where([['delayed_at', '<', '1477912725'],['start_at', null]])->first();
=> null

If get SQL generated...

>>> Cpjob::where([['delayed_at', '<', '1478007734'],['start_at', null]])->toSql();
=> "select * from "cpjobs" where ("delayed_at" < ? and "start_at" is null)"

I've tried several way for send time, unix timestamp, carbon, but all, produces same < ?



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

Laravel 5.3 Observer can't reach the model

I have an Eloquent User model in Laravel. When i creating a new User, i want to create a token automatically for it. I do it with an observer. But in observer, I can't reach the created model, it want to create a new one.

My User model:

namespace App;

use App\Observers\UserObserver;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

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

    public static function boot()
    {
        parent::boot();

        static::observe(UserObserver::class);
    }

}

My UserObserver

namespace App\Observers;

use App\User;

class UserObserver
{
    public function creating(User $user)
    {
        $user->token = str_random(30);
    }
}

When I create a new User, i get an exception

QueryException in Connection.php line 763:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: users.name (SQL: insert into "users" ("token", "updated_at", "created_at") values (JQYUmmMrRRJT64VcFVA8UzkpY019u6, 2016-10-31 14:33:35, 2016-10-31 14:33:35))



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

why it is showing error in laravel? NotFoundHttpException in RouteCollection.php line 161:

can any body help me, I'm beginner to laravel, i got the below error.

Route.php

  Route::group(['middleware' => ['web']], function(){
  Route::get('/', function () {
  return view('welcome');
  });

  Route::post('/signup', [
  'uses' => 'UserController@postSignup',
  'as' => 'signup'
  ]);

  Route::post('/signin', [
  'uses' => 'UserController@postSignin',
  'as' => 'signin'
  ]);

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

welcome.blade.php

 @extends('layouts.master')

 @section('title')
 Welcome
 @endsection

 @section('content')
 <div class="row">
    <div class="col-md-6">
    <h3>Sign Up</h3>
        <form method="post" action="">
            <div class="form-group">
                <label for="email">Enter your email</label>
                <input type="text" class="form-control" name="email" id="email">
            </div>
            <div class="form-group">
                <label for="user_name">User full name</label>
                <input type="text" class="form-control" name="user_name" id="user_name">
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control" name="password" id="password">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
            <input type="hidden" name="_token" value="">
        </form>
    </div>
    <div class="col-md-6">
    <h3>Sign In</h3>
        <form method="post" action="">
            <div class="form-group">
                <label for="email">Enter your email</label>
                <input type="text" class="form-control" name="email" id="email">
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control" name="password" id="password">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
            <input type="hidden" name="_token" value="">
        </form>
    </div>
    </div> 
   @endsection

UserController.php

  <?php

  namespace App\Http\Controllers;

  use App\user;
  use Illuminate\Http\Request;
  use Illuminate\Support\Facades\Auth;
  use App\Http\Requests;

  class UserController extends Controller
  {
   public function getDashboard()
  {
    return view('dashboard');
  }

 public function postSignup(Request $request)
 {
    $user_name = $request['user_name'];
    $email = $request['email'];
    $password = bcrypt($request['password']);

    $user = new User();
    $user->name = $user_name;
    $user->email = $email;
    $user->password = $password;

    $user->save();

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

public function postSingin(Request $request)
{
    if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']]))
    {
        return redirect()->route('dashboard');      
    }
    return redirect()->back();

  }
 }

dashboard.blade.php

    <h1>This is the dashboard page...</h1>

I'm not understand what is the problem, can any body explain breafly... Thanks a lot



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

How to retrieve Nested Relationship data in laravel 5 using eloquent?

Having some problems retrieving nested relationship data. Here are my models:

Partner Model

class Partner extends Model
{
    public function admins()
    {
         return $this->hasMany(Resource::class)->where('resource_type', 'Admin');
    }
}

Resource Model

class Resource extends Model
{
    public function details() {
        return $this->belongsTo(ResourceDetail::class);
    }
}

ResourceDetail Model

class ResourceDetail extends Model
{
}

When I try $this->partner->admins[0]->details it's giving null. The sql it generated is: "select * from resource_details where resource_details.id is null". I'm not quite sure why is it null in the query. I must have done something wrong with the relations. I tried $this->partner->with('admins.details')->find($this->partner->id)->toArray();. It's getting the admins, but details is still null. I also tried hasManyThrough, like: return $this->hasManyThrough(ResourceDetail::class, Resource::class)->where('resource_type', 'Admin'); it finds "unknown column". This is my database structure:

Schema::create('partners', function (Blueprint $table) {
        $table->increments('id');
});

Schema::create('resources', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('partner_id')->nullable()->unsigned();
        $table->foreign('partner_id')->references('id')->on('partners')
            ->onUpdate('cascade')->onDelete('set null');
        $table->enum('resource_type', constants('RESOURCE_TYPES'))->nullable();
        $table->integer('resource_detail_id')->unsigned();
        $table->foreign('resource_detail_id')->references('id')->on('resource_details')
            ->onUpdate('cascade')->onDelete('cascade');
});

Schema::create('resource_details', function (Blueprint $table) {
        $table->increments('id');
});

Do I need to change the structure? Or, how can I get the data from current structure? All I want is, a partner has many resources, and a resource has one details.



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

Fetching data from multiple tables in laravel5

I have two tables posts and sharedposts. sharedposts table has columns "user_id", "updated_at" and "post_id" where as posts table has 'id', 'title' and 'body'. I know about the relations to link both tables. All i want to do is to display each post ordered by 'updated_at' from both the tables. Please help with both query builder and eloquent way. Thanku



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

How to create a pdf with indexes on the left side in laravel 5.2.

I need to create a dynamic pdf from an html in laravel 5. I need an indexing on the left side of the pdf.



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

Mithril's MSX with Laravel Elixir

I've tried tons of things but can't add msx-loader to Elixir webpack config anyhow.

Has anyone ever done this?

This is what I do in my gulpfile:

elixir((mix) => {
    Elixir.webpack.mergeConfig({
        module: {
            loaders: [
                {
                    test: /\.js$/,
                    loaders: ['buble', 'msx-loader']
                }
            ]
        }
    });

    mix.sass('app.scss')
        .webpack('app.js')
        .browserSync({
            proxy: 'http://localhost:8000'
        })
});



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

How to make relationship between two models and update the database

It's me again but now I need some more help from you, I have some version of shopping cart and the whole idea is when I click on the product button the database to be update with the informations which user(id) has order that product(id). First I make orders table with informations(id, product_name, price), other table is users table (id, user_name) and the final table user_order table(id, user_id, order_id);

After that I make two models, one is the Orders model for the products and the second one is the User model. The relationship that I want to make is between this two models.

User model function:

public function orders(){
        return $this->belongsToMany('App\Orders', 'user_order', 'user_id', 'order_id');
       // return $this->belongsToMany('App\Orders');
    }

Orders model function:

public function users(){
      return $this->belongsToMany('App\User', 'user_order', 'order_id', 'user_id');
        //return $this->belongsToMany('App\User');
   }

This is the main html where I show all products with the submit button:

 <div class="row">
                    @foreach($orders as $order)
                    <div class="col-sm-4 col-lg-4 col-md-4">
                        <div class="thumbnail">
                            <img src="http://ift.tt/1MdjS7v" alt="">
                            <div class="caption">
                                <h4 class="pull-right"></h4>
                                <h4><a href="#"></a>
                                </h4>
                                <p>See more snippets like this online store item at <a target="_blank" href="http://ift.tt/2eelEin">Bootsnipp - http://ift.tt/2f93Qmr;
                            </div>
                            <div class="ratings">
                                <p class="pull-right">15 reviews</p>
                                <p>
                                    <span class="glyphicon glyphicon-star"></span>
                                    <span class="glyphicon glyphicon-star"></span>
                                    <span class="glyphicon glyphicon-star"></span>
                                    <span class="glyphicon glyphicon-star"></span>
                                    <span class="glyphicon glyphicon-star"></span>
                                </p>
                            </div>
                            <div class="btn-group center">

                                <a href="" name="req" class="btn btn-warning">Order this product!</a> 
                            </div> 
                            <br>
                        </div>
                    </div>
                    @endforeach

The whole idea is how to make function after submiting the button the table user_order to be updated with the id of the user, and id of the product.

Any help?



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

Which is the best authentication method using for REST API in laravel?

Do I want to know about which is best? I had googled this query and got much information from there ,Some of are CSRF,JWT,Auth0 Can you suggest the best one ?



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

How to create multi auth system in laravel 5.2 or greater using php artisan command is it possible?

I have searched how to do this but, none of these worked for me. so I decided to create a question.

Hi, I am learning Laravel. I am using Laravel 5.2. I want to create multi auth system in Laravel using composer. Is there any PHP Package Repository for this. I don't want to do manually.

Thanks in advance. I hope this question will help others.



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

Rewrite http to https after set project to root directory from public directory

I have removed the public directory from laravel 5.3 and set my project to root directory. I renamed the server.php in the root directory to index.php and copied .htaccess file to the root directory as discussed in this answer This works fine. Now I tried to redirect http to https and non-www to www. Below is my .htaccess file:

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

    RewriteEngine On


    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

    RewriteCond %{HTTPS} off
    RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

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

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

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]



    RewriteRule ^.*\.env$ [NC,L]
    RewriteRule ^.*\.json$ [NC,L]
    RewriteRule ^.*\.xml$ [NC,L]
    RewriteRule ^.*\.md$ [NC,L]
    RewriteRule ^.*\.js$ [NC,L]
    RewriteRule ^.*\.zip$ [NC,L]
</IfModule>

Now nothing is broken except the url. It shows as follows: http://ift.tt/2f8Pra3

Can anyone help me with this?



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

Duplicate column name Laravel

I'm creating migration in laravel and when I run command php artisan migrate the cmd give me error Duplicate column name 'user_id' ('id' int unsigned not null auto_increment primary key, 'user_id' int unsigned not null, 'user_id' int not null, 'order_id_' int unsigned not null, 'order_id' int not null) default character set utf8 collate utf8_unicode_ci)

This is my migration:

<?php

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

class CreateUserOrrderTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::create('user_orrder', function (Blueprint $table) {

            $table->increments('id');

            $table->integer('user_id')->unsigned();
            $table->integer('user_id')->references('id')->on('users');

            $table->integer('order_id')->unsigned();
            $table->integer('order_id')->references('id')->on('orders');
        });
    }

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



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

Laravel : How to show dependent variable on tab

I have two tables , categories and product.Each category has id and name. Each product has id, name and category id. Now I want to load the data on each tab when a user click on specific category_id.so related product will be shown on each category tab. I have tried but couldn't get the solution.

Here is my controllers:

public function gettestItem(){
    $products = Product::all();
    $categories = Category::all();
    return view('products', compact('products', 'categories'));
     }

public function showitems(Request $request){
    $id=$request->id;   
    $products = DB::select(DB::raw("SELECT products.name FROM products INNER JOIN categories on categories.id = products.category_id WHERE products.category_id ='id'"));
    return \Response::json($products);
    }

Here is the view :

<html>
    <head>
        <title> Item List</title>
        <meta name="csrf-token" content="">   
            <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://ift.tt/2apRjw3" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
 <script src="http://ift.tt/2eBd7UN"></script>
  <script src="http://ift.tt/2aHTozy"></script>
    <meta name="csrf-token" content="">   
    </head> 
    <body>
         <div class="container">
            <div id="content">              
                <ul id="tabs" class="nav nav-tabs" data-tabs="tabs">   
                 @foreach ($categories as $category)              
                <li><a href="showItem()" data-toggle="tab" ></a></li>
                @endforeach
                </ul>

                 <div id="my-tab-content" class="tab-content">
                    @foreach($categories as $category)                       
                        <div class="tab-pane " id="">
                        @foreach($products as $product)
                                                    
                        @endforeach
                        </div>                    
                    @endforeach
                </div>     
            </div>
        </div>
        <script>
             function showItem(id) {
                $.ajaxSetup({
                        headers: {
                      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                     });
                $.ajax({ 
                           type: "POST", 
                           url:"", 
                           data:{id:id},
                           success: function(data) {                  
                               console.log(data);
                           }
                       }); 
                 } 
        </script>   
    </body>
</html>

Here is the route:

Route::get('/testItem',[
    'uses'=>'ItemController@gettestItem',
    'as'=>'testItem'
    ]);

Route::post('/showitems',[
    'uses'=>'ItemController@showitems',
    'as'=>'showitems'
    ]);

if anyone could help me solve the problem will be appreciated.



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

dimanche 30 octobre 2016

MethodNotAllowedHttpException in RouteCollection.php line 218 Laravel 5.1 using Knockout js and Ajax

Hi there I´m new in this comunity. I´m developing a web application with laravel 5.1, and i want to call the method store of my model Sale from an ajax POST request, but I have this from console "MethodNotAllowedHttpException in RouteCollection.php line 218", What could it be? thanks a lot.

these are my routes:

//Rutas para inicios de sesión
Route::resource('log', 'LogController');
Route::get('logout','LogController@logout');

//Rutas generales
Route::get('/', 'WelcomeController@index');
Route::get('index', 'WelcomeController@indexdos');


//Routes for users
Route::get('user/actualizar','UserController@actualizar');
Route::get('user/deleter','UserController@deleter');
Route::resource('user', 'UserController');

//Routes for pacients
Route::get('pacient/deleter','PacientController@deleter');
Route::get('pacient/actualizar','PacientController@actualizar');
Route::resource('pacient', 'PacientController');

//Routes for medicaments
Route::get('medicament/deleter','MedicamentController@deleter');
Route::get('medicament/actualizar','MedicamentController@actualizar');
Route::resource('medicament', 'MedicamentController');

//Routes for doctors
Route::get('doctor/deleter','DoctorController@deleter');
Route::get('doctor/actualizar','DoctorController@actualizar');
Route::resource('doctor', 'DoctorController');

//Routes for dates
Route::get('date/deleter','DateController@deleter');
Route::get('date/actualizar','DateController@actualizar');
Route::get('date/bitacora','DateController@bitacora');
Route::resource('date', 'DateController');

//Routes for sales
Route::resource('sale', 'SalesController');`

this is the form that contents the values i want to send to sale.store

@extends('layouts.principal')
@include('Ventas.forms.barra')
@section('content')
<div class="container">
  {!!Form::open()!!}
     <input type="hidden" name="_token" value=""      id="token"></input>
    @include('Ventas.forms.sale')
    <button id="btnAgregar" data-bind="click: $root.agregarVenta"    class="btn btn-success">Registrar venta</button>
{!!Form::close()!!}
 </div>
@stop

As You can see, I include the 'sale' form, where I include knockout js code:

<div class="form-group">
<table>
<tr>
<td>{!!Form::label('id_doctor_1','Cita a la cual se facturará: ')!!}</td>
<td><select data-bind="options: $root.citas, optionsText: function(item) {
                   return item.paciente()  + '  (Fecha: ' + item.fecha() + ' , Hora: ' +item.hora() + ')'
               },
                                 value: selectedDate,
               optionsCaption: 'Elija una cita...'"></select></td>
</tr>
<tr>
  <td>{!!Form::label('Producto:')!!}</td>
  <td><select data-bind="options: $root.productos, optionsText: function(item) {
                                     return item.nombre()  + '  (Precio de venta: ' + item.precio_venta() + ' ,Existencias: ' +item.existencias() + ')'
                             },
                             value: selectedProduct,
                             optionsCaption: 'Elija un producto...'">     </select></td>

 <tr>
   <td>{!!Form::label('cantidad:')!!}</td>
 <td><input type="number" data-bind="value: cantidad"></input></td>
 </tr>
</table>
</div>
<div class="form-group">
  <label for="btnAgregar" class="col-sm-2 control-label"></label>
   <div class="col-sm-10">
     <button id="btnAgregar" data-bind="click: $root.agregarProducto_venta"   class="btn btn-primary col-sm-8 col-md-offset-1">Agregar producto a la venta actual</button>
</div>
</div>

<div class="form-group">
<br><br/><br><br/>
</div>

<div data-bind="visible: selectedDate"> <!-- Appears when you select something -->
 <div class="post format-image box masonry-brick">
 <!-- Begin Blog Grid -->
 <div class="blog-wrap">
  <table>
     <tr>
         <td><strong>Detalles de cita elegida</strong></td>
     </tr>
     <tr>
         <td><strong>Paciente:</strong></td>
         <td><span data-bind="text: selectedDate() ? selectedDate().paciente : 'unknown'"></span></td>
     </tr>
     <tr>
         <td><strong>Producto:</strong></td>
         <td><span data-bind="text: selectedDate() ? selectedDate().producto : 'unknown'"></span></td>
     </tr>
     <tr>
         <td><strong>Cantidad:</strong></td>
         <td><span data-bind="text: selectedDate() ? selectedDate().cantidad : 'unknown'"></span></td>
     </tr>
     <tr>
         <td><strong>Subtotal:</strong></td>
         <td><span data-bind="text: selectedDate() ? selectedDate().subtotal : 'unknown'"></span></td>
     </tr>
     <tr>
         <td><br><br></td>
     </tr>
     <tr>
         <td><strong>Productos a facturar</strong></td>
     </tr>
     <tr>
         <td colspan="2"></td>
     </tr>
 </table>
 <table>
         <thead>
                 <tr><th>Nombre del producto____|</th><th>Precio____|</th><th>Cantidad____|</th><th>Subtotal____|</th><th>Acción____|</th></tr>
         </thead>
         <tbody data-bind="foreach: productos_venta">
                 <tr>
                         <td data-bind="text: producto"></td>
                         <td data-bind="text: precio"></td>
                         <td data-bind="text: cantidad"></td>
                         <td data-bind="text: subtotal"></td>
                         <td><a href="#" data-bind="click: $root.removeProduct">Remover</a></td>
                 </tr>
         </tbody>
 </table>
  </div>
    </div>
</div>
<h3 style="color:#FAFAFA" data-bind="visible: totalSurcharge() > 0">
  Total (incluyendo medicamentos y cita): $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>

And finally this is my app.js file, It is supposed that when I click on the button "btnAgregar", the method "agregarVenta" makes an ajax request type POST, but it doesn´t work, what am I doing wrong? again, thanks a lot.

File app.js (ajax method):

//Método para agregar una nueva venta al arreglo de ventas, y después pasarlo
//a la base de datos.
self.agregarVenta=function(){
  // crea un nuevo objeto Venta y después lo añade al arreglo.
  var id_cita = self.selectedDate().id();
    var venta= new Venta({id_cita: id_cita,producto:   self.selectedDate().producto(),
    cantidad: self.selectedDate().cantidad(),subtotal:  self.selectedDate().subtotal()});
    self.ventas().push(venta);

  for (var i = 0; i < self.productos_venta().length; i++) {
    venta= new Venta({id_cita: id_cita,producto: self.productos_venta()[i].producto(),
      cantidad: self.productos_venta()[i].cantidad(),subtotal: self.productos_venta()[i].subtotal()});
        self.ventas().push(venta);
  }
  var token = $("#token").val();
  var ruta = "sale.store"
  $.ajax({
     route: ruta,
     headers: {'X-CSRF-TOKEN': token},
     type: 'POST',
     data: {ventas: self.ventas()},
     dataType: 'JSON',
     error: function(respuesta) {alert("error");},
     success: function(respuesta) {
       if (respuesta) {
         alert("exito");
       }else {
         alert("error");
       }
     }
 });
 }
}



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

use a controller inside a folder in the controllers folder

I'm trying to use a controller inside a folder in the controllers directory like

route

Route::get('/','site\HomeController@index');

but seem's does not work like it gives me this error

Class App\Http\Controllers\site\HomeController does not exist

Note: I have also a HomeController.php in the controllers folder. I'm trying to organize my controllers by putting them unto their specific folders.

Any help, ideas please?



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

Get all results from within the hour

I'm trying to get all results within the hour. NOT THE PAST HOUR, but WITHIN THE HOUR.

For example, if it's currently 12:30, I want to get all results since 12:00, not 11:30. Or if it's 6:45, I want to get all results since 6:00, not 5:45.

How can I do this using Carbon and Laravel?

Here's what I've got so far:

$user = User::where('created_at', WHAT DO I PUT HERE)
    ->get();



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

Make Input file required based on database in laravel

I have a dynamic input file in laravel, input file will display based on data in database on select dropdown. here is my database loop_attachment table

here is the explanation by code i have.

ajax when select 2 dropdown which has id=groupid and id=lendertype:

$('#groupid').on('change', function(){
    $.post('', {type: 'loop_attachment', id: $('#groupid').val(), key: $('#lendertype').val()}, function(e){
        $('#image').html('');
        $('#image').html(e);
        });
    });
$('#lendertype').on('change', function(){
    $.post('', {type: 'loop_attachment', id: $('#groupid').val(), key: $('#lendertype').val()}, function(e){
        $('#image').html('');
        $('#image').html(e);
        });
    });

when select dropdown, input file will display in here :

<div class="row" id="image">
</div>

and here is my controller :

public function postDynamic(Request $request) 
{        
    switch(Input::get('type')):
        case 'loop_attachment':
            $return = '';
            foreach(Loop_attachment::where('groupid', Input::get('id'))->where('type2', Input::get('key'))->where('active', 1)->get() as $row) 
                $return .= "<div class='row'><div class='col-md-3'></div><div class='col-md-6'><center><div class='form-group'><div class='btn btn-primary'><span>Upload $row->doctype</span> <input type='file' style='margin-bottom:1px;' class='form-control upload' name='image[]' id='image-$row->doctype'></div></div></center></div><div class='col-md-3'></div></div>";
            return $return;
        break;
    endswitch;       
}

Currently there are no errors or issues. My question is, how to make input file become required if required column is 1 ? please help me with the code.

I hope my explanation easy to understand. Thanks in advance.



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

Automatically pass variable to any view [duplicate]

This question already has an answer here:

I'm on Laravel 5.3. I can just pass variable to view by

public function test(){
    $testVar = 'test';

    return view('pages.home',compact('testVar'));
}

How can I automatically pass a variable to view without creating the variable unto the controller and then pass it to the compact argument? like

public function test(){
    return view('pages.home');
}

and then in view, I can just retrieved the variable anywhere in my application, like using the 'Auth::check()'

<div class="menu" id="primary-menu">
    
</div>

any ideas, help please?



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

CSS not loaded in view when sent in email

I'm working with laravel5 and using materialize whene I send a view in email the css is not loaded I tried to make my css files inlined but this don't work



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

How to get Larvel5.3 session data or Authentication data from public directory?

I write some php function in public directory because I have use external library then I can't retrieved any session data and authentication data from the controller I have testing with below php script

session_start();
var_dump($_SESSION['user']);

I have initial Session data from AdminMiddlware already It awesome for using it in Resource->view directories but can not in public.

namespace App\Http\Middleware;

use Closure; use App\User; use Illuminate\Support\Facades\Auth;

class AdminMiddleware {

/**
 * Handle an incoming request. User must be logged in to do admin check
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */


public function handle($request, Closure $next)
{

    $user = User::find(\Auth::user()->id);
    if ((int)$user->is_admin == (int)config('auth.guards.is_admin'))
    {

        $collection = collect(Auth::user());
        $thisdata = $collection->toArray();
        $request->session()->put('user', $thisdata);

        return $next($request);
    }

    return redirect()->guest('/');


}

}



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

Can't autoload a helper file - Laravel 5.3

I have a helper file located at

app/Helpers/Navigation.php

Helper file with namespace:

   <?php

namespace App\Helpers;

class Navigation
{
    public static function isActiveRoute($route, $output = 'active')
    {
        if (Route::currentRouteName() == $route) {
            return $output;
        }
    }
}

i wanted to autoload this file . So in my composer.json i have this:

"autoload": {
    "classmap": [
      "database"
    ],
    "psr-4": {
      "App\\": "app/"
    },
    "files": [
      "app/Helpers/Navigation.php"
    ]
  },

In my view i want to do this:

<li class="">

But i get the error:

Call to undefined function isActiveRoute()

Not sure what i'm doing wrong. I did composer dumpautoload when i changed the composer file. I tried installing composer again, that also didn't change anything.



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

laravel get last comment from each post

I have 2 tables, Items and Bids.

Items hasMany(Bid);

Table items

  • id-1
  • id-2
  • id-3

Table bids

  • id-1 | 3
  • id-1 | 4
  • id-2 | 2
  • id-2 | 5
  • id-3 | 4
  • id-3 | 6

and now I want to show the highest bid of each item.

and here is my code

    $data = PostItem::with(['bids' => function($query){
                    $query->orderBy('new_bid','desc')->get();
                }])
                ->get();

but the problem is it will takes all bids.

but if i use this code

    $data = PostItem::with(['bids' => function($query){
                    $query->orderBy('new_bid','desc')->take(1);
                }])
                ->get();

it will takes only 1 latest bid, do not take the latest bid of each item.

How to do it properly?

Thanks in advance



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

How to merge values of collection using pluck function?

I use the pluck() function to get output collection with key, value:

$work_types = Work::orderBy('name')->get()->pluck('name', 'id');

Output is:

{
  0 => "Name1",
  1 => "Name2",
  2 => "Name3
}

How can I merge value name with value id that to get the following object:

 {
      0 => "0 -Name1",
      1 => "1 - Name2",
      2 => "2 - Name3
    }



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

How to make laravel display grouped values

I'm developing a question answer app using laravel, I want to display all answers under each question for that particular question. The problem I'm facing is I'm unable to alter the view to display answer under the respective question, since there is no way to match ID's in laravel views!

My view code:

@section('list-questions-answers')
    <ul>
        @foreach($listQuestions as $q)
            <li><a href=""></a></li>
            @foreach($listAnswers as $a)
                <ul>
                    <li></li>
                </ul>
            @endforeach
        @endforeach
    </ul>
@endsection

Answer's model

public function User()
{
    return $this->belongsTo('App\User');
}
public function questions()
{
    return $this->belongsTo('App\questions','answer_id');
}
public function scopefetchAnswers($query)
{
    return $query->select('answer')->where('people_id','<>',Auth::id())->get();
}

Everything is display on the dashboard.blade.php, which runs on dashboard controller

class Dashboard extends Controller
{
    public function index(){

        $listQuestions=questions::latest('created_at')->fetchQuestions();
        //$listAnswers=answers::groupBy('question_id')->fetchAnswers();
        $listAnswers=answers::fetchAnswers();
        return view('forms.question',compact('listQuestions','listAnswers'));
    }
}

Output I'm getting

Current Output

Ouput I want

Required output

Answer's table

enter image description here

How can I achive that output? I'm using Laravel 5.2



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

samedi 29 octobre 2016

Laravel events not firing?

I can't seem to get any of my eloquent.saved event handlers to run.

I tried this:

<?php

namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        'eloquent.saved: \App\Models\Company' => [
            '\App\Models\Company@hasSaved',
        ],
    ];

}

And then added this method to \App\Models\Company:

public function hasSaved() {
    die("SAVED!!!");
}

But it doesn't run when I save a company.

I tried creating an observer:

<?php

namespace App\Providers;

use App\Models\Company;
use App\Observers\CompanyObserver;
use DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{

    public function register()
    {
        Company::observe(CompanyObserver::class);
    }
}

But the events never fire:

<?php namespace App\Observers;

class CompanyObserver {

    public function saved() {
        \Kymark\Dbg::log('saveddd');
        die('saved');
    }

    public function saving() {
        \Kymark\Dbg::log('savvving');
        die('saved');
    }
}

I tried using a listener class in EventServiceProvider instead:

protected $listen = [
    'eloquent.saved: \App\Models\Company' => [
        \App\Listeners\CompanySavedListener::class,
    ],
];

But that also never runs.

Lastly, I tried adding this to EventServiceProvider

public function boot(DispatcherContract $events)
{
    parent::boot($events);

    $events->listen('eloquent.*', function() {
        \Kymark\Dbg::log(func_get_args());
    });
}

And that does fire a bunch of random events, but it's just feeding me model instances -- I have no idea what events are actually firing.

So what's going on? I just want to know when my Company has saved.



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

Laravel form validation doesn't seem to work

I'm making my first form in Laravel and the generation of the form is all working. It's just that the store function seems to blindly return the user to my contact page irrelevant of the result of the form validation.

My controller looks like this:

namespace App\Http\Controllers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;

use App\Http\Requests\ContactFormRequest;

class ContactController extends Controller {

  public function create(){
      return view('contact');
  }

  public function store(ContactFormRequest  $request) {

      return \Redirect::route('contact')
        ->with('message', 'Thanks for contacting us!');

  }
}

And the form handler like this:

namespace App\Http\Requests;
use Illuminate\Http\Request;

class ContactFormRequest extends Request {
  public function authorize() {
    return true;    // don't need to be registered to run form so true
  }
  public function rules() {
    return [
        'email' => 'required|email',
    ];
  }
}

And the form like this:

  <ul>
    @foreach($errors->all() as $error)
      <li></li>
    @endforeach
   </ul>
   @if(Session::has('message'))
      <div class="alert alert-info">
        
      </div>
   @endif


 {!! Form::open(array('route' => 'contact_store', 'id' => 'contactCallMeForm')) !!}         
 {!! Form::label('Your E-mail Address') !!}
 {!! Form::text('email', null,  array('required',  'class'=>'form-control',  'placeholder'=>'Your e-mail address')) !!}
 {!! Form::submit('Contact Us!',  array('class'=>'btn btn-primary')) !!} 
 {!! Form::close() !!}



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

Laravel 5.3 Eloquent - select from 3 tables

in addition to my last question Laravel 5.3 Eloquent Relationships

i added a new table called Labels and of course create a new model for this table.

Languages

id
name
short_name

Dictionary

id
label_id
value
language_id

Labels

id
label_name

and i have this code:

$lables = Dictionary::whereHas('language', function($query) {
        $short_name = basename(__DIR__);
        $query->where('short_name', $short_name);
    })->pluck('value', 'label_id')->toArray();

i want to pull out the label_name field instead of the label_id

but i dont know how to make this join

thank you!



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

Menu in laravel 5 Multiple levels?

Model:

class Menu extends Model
{
    protected $table = 'menus';

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

}

Controller:

class MenuController extends Controller
{

    public function index()
    {
        $menus = Menu::where('parent_id', 0)->get();
        return view('admin.menus.index',compact('menus'));
    }
}

View:

<ul>
    @foreach($menus as $menu)
    <li>
    @if($menu->sub_menu->count() > 0)
       <ul>
       @foreach($menu->sub_menu as $sub)
           <li</li>
       @endforeach
       </ul>
   @endif
   </li>
   @endforeach
</ul>



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

Cropper.js - drawing rectangle

Is it possible to add easily an ability to draw - for example - a rectangle on image with cropper.js? I would like to be able to indicate the position of the rectangle on each image separately. To draw a rectangle using only Image Intervention doesn't solve my problem.



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

Laravel get user language based on user country

i trying to set the user default language based on user's country

i tried to use this command

Request::server('HTTP_ACCEPT_LANGUAGE');

but it give me this result:

en-US,en;q=0.8,he;q=0.6,zh-CN;q=0.4,zh;q=0.2,ru;q=0.2

so i realized that this is not the right way to detect the user default language because it based on the browser usage and i think that my users will prefer to use their country language

so i wonder what is the best way to get the user language based on his country?

thank you!



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

Laravel 5.3 Socialite facebook login

I followed this http://ift.tt/2eXXkAl tutorial on how to use laravel socialite, although i am using laravel 5.3, the syntax still works fine for me.


Problem

The problem is that when i click my fb login link, which refers to my callback function in my AuthController. I get stuck on the callback link with a url lke this localhost:8000/callback?code=<very long code here>, and then when i try to refresh the browser, it gives me this error InvalidStateException in AbstractProvider.php line 200.


Code

This is the callback function

 public function handleProviderCallback()
    {
        $user = Socialite::driver('facebook')->user();
    }

Redirect function

public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();
    }

My routes

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

Auth::routes();

Route::get('/home', 'HomeController@index');
Route::get('/redirect', 'Auth\AuthController@redirectToProvider');
Route::get('/callback', 'Auth\AuthController@handleProviderCallback');


Notes

Before this error happened, i have already made the facebook pop-up work but then i got the cacert.pem error. But i already fixed that by downloading the cacert.pem and configuring php.ini.

Things i've tried

I tried using dd on the $user and the output is this:

User {#192 ▼
  +token: "EAAEjWyWCELYBANza7O7zUIWqYyxG6nZBO8EcuTLCxIeyJ9qP3bcpgrVVxyQpqbTAIHx7ZA69UDs56pWQUca3ZBo7FUSt9cV4kWkhxw3KqbhDJGesB4gvOK95XYQ4QGuRZBABNRNztGrWwD5bZAB2ZApIhIiiHbiW0ZD"
  +refreshToken: null
  +expiresIn: "5157925"
  +id: "1350466991653065"
  +nickname: null
  +name: "<my name>"
  +email: "<my email>"
  +avatar: "http://ift.tt/2eGa4Ns"
  +user: array:6 [▶]
  +"avatar_original": "http://ift.tt/2eXSCTg"
  +"profileUrl": "http://ift.tt/2eG9pM5"
}

I replaced my name and email there.
Any help would be much appreciated!



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

Laravel create table, wchich hav other fields

I hav question, i create database, wchich have 6 tables and make recommendation

php artisan make:migration create_users_table2

Return me score Migration table created successfully. Created Migration: 2016_10_29_092820_create_users_table2

then make recommendation php artisan migrate

Return me score Migration table created successfully. Migrated: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_100000_create_password_resets_table Migrated: 2016_10_29_092820_create_users_table2

and have created databases, but other from other tables, That is my file about name 2014_10_12_000000_create_users_table

<?php

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

  class CreateUsersTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('login',60);
        $table->string('email');
        $table->integer('date_registration');
        $table->string('password',200);
        $table->string('permissions',1);
        $table->rememberToken();
        $table->timestamps();
    });

   Schema::create('statistics', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('date');
        $table->string('variable_http_user_agent',200)
        $table->string('page',200);
        $table->string('ip',20);
        $table->string('user',60);
    });

   Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name',100);
        $table->integer('id_category');
        $table->integer('id_category2');
        $table->float('price');
        $table->text('description');
        $table->bool('auction');
        $table->bool('sold');
        $table->integer('id_usera');
        $table->integer('quantity');
        $table->string('path_to_image',100);

    });        
   Schema::create('basket', function (Blueprint $table) {
        $table->increments('id');
        $table->string('quantity_products',100);
        $table->integer('id_usera');

    });        
   Schema::create('category', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name',100);

    });        
   Schema::create('category2', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name',100);

    });        

}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('users');
    Schema::drop('statistics');
    Schema::drop('products');
    Schema::drop('basket');
    Schema::drop('category');
    Schema::drop('category2');
}

}



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

Laravel 5.3- How call controller using AJAX function inside view

hi folks I'm newbie to Laravel and got stuck while working. I'm trying to call a controller function on onload from AJAX which will return me the categories stored in database but it gives me following error

MethodNotAllowedHttpException in RouteCollection.php line 218:

My Question/Queries

  • How to call Laravel Controller using AJAX function?
  • And how to display it in li?
    Thanks for helping me out :)
    here is the code

create_category_table.php

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

class CreateCategoryTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create  ('categories',function($table)
    {
        $table->increments('category_id',true);
        $table->string('category_name');
        $table->text('description');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
}
}

AjaxOperationController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;

class AjaxOperationController extends Controller
{
public function category($category){
    $category=DB::select('select category_name from categories');
    return response()->json(array('category_name'=> $category), 200);
}
}

header.php (View)

 <script>
 $(document).ready(function(){
        $.ajax({
           type:'POST',
           url:'/category',
           data:'_token = <?php echo csrf_token() ?>',
           success:function(data){
              //$("#msg").html(data.msg);
              alert(data);
           }
          });
         });
</script>

routes.php

 Route::post('/category','AjaxOperationController@category');
 Route::post('/category/{category}', 'AjaxOperationController@category');



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

vendredi 28 octobre 2016

Redirect to login page with message not working in laravel 5.3

When registering for external link, I want to dislay a message :

 if (!Auth::check()){
        Session::flash('message', trans('msg.please_create_account_before_playing', ['tournament' => $tournament->name]));
        return redirect(URL::action('Auth\LoginController@login'));
    }

In my login page, I have:

@if (Session::has('message'))
   <div class="alert alert-info">
    <button type="button" class="close" data-dismiss="alert"><span>×</span><span class="sr-only">Close</span></button>
    </div>
@endif

I checked in my login page, with laravel debugbar, and there is no message var in session. But it never shows up...

Any idea why it is not working?



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

Show create_by from table User in Laravel5?

I want to show field create_by in view from table user. Please Help.



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

What tools are available for managing PHP/Laravel projects across autoscaling groups on AWS?

Given the following scenario/desirables.

  • Projects built on Laravel 5.*
  • Source managed using a Git Flow workflow hosted via Bitbucket.
  • High availability + automatic horizontal scaling using a launch configuration and an AWS autoscaling group, ELB, RDS etc.
  • The ability to deploy versions to all servers with zero/minimal downtime.
  • The ability to release said versions preferably from a GUI where all that's required is to specify or choose a tag, branch or commit.
  • Not needing to SSH into instances or do any sort of manual setup in terms of instance build or code deployment (this should be handled as part of the deployment process using checked-in shell scripts etc).
  • Being able to control what services and software run on each instance.
  • Being able to set environment variables/configuration on each instance securely, preferably without checking in these files with the source.

Now I've already played around with Elastic Beanstalk and Code Deploy on AWS. However, each seem to have their own pitfalls when it comes to the above described workflow. Other 3rd party (non AWS) services like Forge and Envoyer (Laravel specific) do address some of the mentioned points, but they focus on manually spun up instances and as far as I am aware cannot manage an AWS auto scaling group.

So my overall question is - what (if any) service(s) exist to manage Laravel/PHP projects across an AWS autoscaling group while offering zero-downtime deployment with no visible effects to active users while deployments occur.

If no such service exists out of the box, have you personally used or found a set of tools or a workflow that closely resembles the above with example code and implementation details you can point to?



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

Input array loop on controller laravel 5

I have inputs array and i need to make a foreach but laravel $request->all() only return last one:

url:

http://localhost:8000/api/ofertas?filter_pais=1&filter_pais=2&filter_pais=3

controller:

public function filtroOfertas(Request $request){
        return $request->all();
}

result:

{"filter_pais":"3"}

result should return 1, 2 and 3 and i need to make a foreach in filter_pais. Any solution? Thanks



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

Laravel 5 - Remove Parameter From All Request Objects at Controller Level

I have URLs that look like:

http://ift.tt/2eNrntE
http://ift.tt/2e5znYA
etc...

In my controllers, I have functions that look like:

public function user_get_endpoint(Request $request){

    $request = $request->toArray();
    return UserModel::where($request)->get()->toArray();

}

The above will currently break since the $request object contains a property called api_token which does not exist in the user table. I am using the api_token in a middleware to check for authentication.

I can manually unset the api_token property in each of my API functions by using unset($request['api_token'], but I'd like to avoid that if possible.

Is there anyway to do this application wide or at a class or controller level?



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

Create nested OR condition using Laravel Eloquent

I want to create something like:

select * from documents where 'chapter'=3 and 'section'=4 and ('title' like '%abc% OR 'desc' like %abc%);

How can I do this using Eloquent? I've tried using Eloquent's whereOr method but that doesn't seem to do anything.

Some of what I've got:

    $docSearch = DB::table('documents');

    if ($chapter > 0) {
        $docSearch->where('chapter', $chapter);
    }

    $existingManagementArray = Management::getAllManagementIDsAsArray();
    if ($management_id > 0 && in_array($management_id, $existingManagementArray)) {
        $docSearch->where('management_id', $management_id);
    } else {
        $docSearch->whereIn('management_id', $existingManagementArray);
    }

    if (strlen($term) > 0) {
        //These don't seem to change the SQL
        $docSearch->whereOr('title', 'like', "%$term%"); 
        $docSearch->whereOr('desc', 'like', "%$term%");
    }

    DB::enableQueryLog();
    $allFoundDocs = $docSearch->get();
    dd(DB::getQueryLog());



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

Multilingual ui using Laravel 5.3

i'm working on a CRM that should work on different countries

this is my first time using Laravel so i'm bit confused

my database looks like this:

Language

  • id
  • name
  • short_name (en,ru etc)

Dictionary

  • id
  • label (sign_in,forgot_password etc)
  • value ('Sign In','Вход' etc )
  • language_id

i thought about working this way:

http://domain.com/en

http://domain.com/ru

http://ift.tt/2fnMdnf

http://ift.tt/2dU79N9

if user go to http://domain.com so it will redirect him by this steps:

  1. if the user logged in the past and has cookie with his language
  2. if there is no cookie get the country of the user by his IP
  3. if the country's language is not recognized in the Languages table redirect the user to default language that set on the config/app.php => 'locale' => 'default language'

i wonder if there is any way to do that without sending the language variable in every function in the controllers, what do i mean?

i mean that i dont wont my routes and my controllers to look like this:

Routes

Route::get('/{locale}', 'Auth\LoginController@showLoginForm');  
Route::get('/{locale}/users/', 'UsersController@index');
Route::get('/{locale}/users/view/{id}', 'UsersController@viewUser');

Controllers

public function showLoginForm($locale)
{
    App::setLocale($locale);
    return view('auth.login');
}
...
public function index($locale)
{
    App::setLocale($locale);
    return view('users.index');
}
...

i want it to work in the background without me setting the language every time and setting the routes,

thank you!



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

How do find /path/to/artisan ?

Trying to Scheduling Artisan Commands

http://ift.tt/2abk27w

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

Can someone please show me how do I know the /path/to/artisan ?



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

Configure Laravel Task Scheduling with Crontab

I've create a laravel task and added to my crontab file

<?php

namespace App\Console;

use Carbon;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\Inspire::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $now = Carbon\Carbon::now('America/New_York');
        $dt = Carbon\Carbon::parse($now);
        $time_start = $dt->toTimeString();
        $dt = str_replace('-','_',$dt);
        $dt = str_replace(' ','_',$dt);
        $dt = str_replace('/',':',$dt);
        $schedule->exec('curl '.env('APP_URL').'fbwifi/acl_update')->everyMinute()
            ->sendOutputTo(public_path().'/tasks/log_'.$dt.'.txt');
    }
}


My crontab file

*       *       *       *       *       /usr/local/bin/php artisan schedule:run
*       *       *       *       *       php artisan schedule:run


Result

For some reasons my crontab doesn't trigger. After 5 minutes, I don't anything generated. Am I missing anything ?

How would one go about and debug this ?


I'm opening to any suggestions at this moment.

Any hints / suggestions / helps on this be will be much appreciated !



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

Call to undefined method Bllim\Datatables\DatatablesServiceProvider::package()

I followed these instructions ( http://ift.tt/1omy9IN ) while setting up bllim datatables. but when I execute

php artisan config:publish bllim/datatables

I get this error

[Symfony\Component\Debug\Exception\FatalThrowableError]                         
Call to undefined method Bllim\Datatables\DatatablesServiceProvider::package() 

Any suggestions on how I should solve this



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

JQuery Select2 Plugin + Laravel 5.3

I Have some problem while using Select2 Jquery Plugin cause its my 1st time use it.

    $(".select-class").select2({
    ajax: {
        url: "",
        dataType: 'json',
        type: "POST",
        data: function (term, page) {
          return {
                type: 'type_of_mine',
                kelas : kelas,
                jurusan : jurusan,
                q: term
            };
        },
        results: function (data, page) {
            return { results: data.results };
        }

    },
    initSelection: function (item, callback) {
        var id = item.val();
        var text = item.data('option');
        if(id > 0){
            var data = { id: id, text: text };
            callback(data);
        }
    },
    formatAjaxError:function(a,b,c){return"Not Found .."}
});

but i always got this error message on my console :

jquery.min.js:2 Uncaught Error: No select2/compat/initSelection(…)

can you help me please?? thanks



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

Add element changes in laravel in separate table?

I have a classic create() function to create elements, but changes I wish to save in a separate table, like history. There is table: element_changes and also model created named ElementChange, but in my ElementController, how can I tell to save it in a separate table?

Classic create function:

public function create(Request $request) 
    $item = new Item();
    $item->fill($request->old());
    return view('items.create', compact('item'));
}



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

LoadBalanced AWS EC2 Instances Intermittently fail a jQuery xhr.send with a 500 Error

I have set up a Load Balanced Environment on AWS, containing two EC2 Servers, running a Laravel 5.3 website.

The LB polls every 2 minutes for a successful connection to an html file Called Healthy.html on each instance.

Also every 2 minutes each instance syncs it's contents with a folder stored on an S3 Bucket. This means I can push amendments to the bucket and all EC2 Instances pick up those amendments and sync every 2 mins.

I am using Jquery to ASynchronously POST to a route called /register to send an email.

This works every time in the local and dev environment. It works every time when I connect to each EC2 Instance seperately.

However, it will intermittently through a server 500 error (on the jquery xhr.send() call) when I run this via the loadbalanced URL.

To explain this "intermittent" behaviour more, the first time I submit the form, it throws a 500 error. If i click the button again it submits the form and sends the email. if I click it again it will throw a 500 error. Each time I do not change the data or refresh the page.

And it's the intermittent behaviour that is confusing me. Is it possible that the Asynchronous call is hopping onto the second server and thus the session is invalid?

Any other possibilities?



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

PHP - Using Interfaces, Strategy Pattern and Optional Method Parameters

I was wondering if i could get a bit of help.

I have an interface like so

interface BackupContract {
    public function testConn($request, $port);
}

Then the 2 example implementations of this interface is as follows

class FTPBackup implements BackupContract {
    public function testConn($request, $port = 21) {
        // code here
    }
}

class SFTPBackup implements BackupContract {
    public function testConn($request, $port = 22) {
        // code here
    }
}

As i need things like 'service' and port designated at runtime, im using 'strategy pattern' to achieve this, like so.

class BackupStrategy {
    private $strategy = NULL;

    public function __construct($service) {

        switch ($service) {
            case "ftp":
                $this->strategy = new FTPBackup();
                break;
            case "sftp":
                $this->strategy = new SFTPBackup();
                break;
        }

    }

    public function testConn($request, $port)
    {
        return $this->strategy->testConn($request, $port);
    }
}

and finally, in my controller im using the following code to put it all together.

$service = new BackupStrategy($request->input('service'));
$service->testConnection($request, $request->input('port'));

The problem is, that if a user doesnt enter a port, it is meant to auto assign a port variable, i.e 21 or 22 like in the 2 implementations.

It doesn't seem to be working, but its not throwing any errors



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

How to set require if value is chosen in another multiple choice field in validation of laravel?

I have a form like this:

<input type="checkbox" name="category[]" value="a">Option A</option>
<input type="checkbox" name="category[]" value="b">Option B</option>
<input type="checkbox" name="category[]" value="c">Option C</option>
<input type="checkbox" name="category[]" value="d">Option D</option>
<input type="checkbox" name="category[]" value="e">Option E</option>
<input type="checkbox" name="category[]" value="f">Option F</option>

<input type="text" name="description">

If option A is chosen, I want to make description required in backend validation in laravel 5. So I tried:

$validator = Validator::make($request->all(), [
        'description' => 'required_if:category,a',
    ]);

if ($validator->fails()) {
        return "error!"
}

However, the checking is not working. How should I set the validation rule to make it works?



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

Laravel Entrust Different Roles on Different Organizations

Is it possible to have different roles on different organizations for a user using Entrust http://ift.tt/1dURk13

Entrust docs say you can have a user and attach roles to it. But what I would like is a user can belong to multiple organisations and has roles for each organisation

Something like this

  • John Doe
    • Organisation A
      • Admin
    • Organisation B
      • User

I'm also using Laravel



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

Use of undefined constant (input) laravel 5

I am junior developer and got stucked with such problem: Laravel brings me back an error: "Use of undefined constant input - assumed 'input'" And I dont understand why: this variable is IN javascript code.

Here it is:

        <div class="form-group">
        {!! Form::label('pac-input', 'Адрес') !!}
        {!! Form::text('pac-input', $meta ? $meta->pac-input:old('pac-input', null), ['class' => 'form-control', 'placeholder' => 'Введите адрес']) !!}
    </div>

My input

var input = (
                document.getElementById('pac-input'));

                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.bindTo('bounds', map);

My JavaScript code (google.maps.api3)

Also got a question: in the source there was a comment after "var input = /** @type {!HTMLInputElement} */( document.getElementById('pac-input'));" - what kind of HTMLInputElement this one wants?

Thanks!



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

Laravel public/subfolder another source code

anybody know how to let laravel some route to another folder inside laravel public folder, current folder structure:

public
   index.php <==== this is laravel index.php
   .htaccess <==== this is laravel default .htaccess
   subfolder <==== this is not laravel php code files

in my localhost, i can visit the subfolder with url http://ift.tt/2eLMhtb

but in my live site, http://ift.tt/1gosCeT throw me error of

NotFoundHttpException in RouteCollection.php line 161:

here is the laravel .htaccess files

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

    RewriteEngine On

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

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

both local/live server source code are sync, i guess this is some server settings issues but i dont know what is the keyword, appreciate for all the help

btw, laravel 5.2 version



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

Why is this protected route refusing logged in users? laravel 5.3

I have a custom guard setup and it's been logging me in, or it was until I protected one of the routes, and now the route is rejecting all users out of hand.

Route::get('agencydash', 'AgencyRegisterController@getDashboard')->name('agencydash')->middleware('auth:agency');

This is the controller part related to login. It has the same response when registering and so on though. I tried emptying the browser cache, and even instituted a logout button:



Goes to

Route::get('logout', 'AgencyRegisterController@logout')->name('logout');

Which runs

public function logout() {
        Auth::guard('agency')->logout();
        return redirect()->route('start');
    }

But no matter what. No cigar. The login gets rejected back to the front page.

public function postSignIn(AgencyFormRequest $request){

    $credentials = array('Username'=>Input::get('Username'),
                     'password'=> Input::get('Password'));
    if (Auth::guard('agency')->attempt($credentials)) {
        return redirect()->route('agencydash');
    }
    return redirect()->back();
}

I know the logging in function works as it does redirect to that route, which promptly triggers the auth route and goes, "Nope buddy."

I added an extra line to the Handler file to send me back to the front page:

protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest('/')->withMessage('Gotta be logged in for that mate.');
    }

This is the guard:

'agency' => [
            'driver' => 'session',
            'provider' => 'agencies',
        ],

This is the provider:

'agencies' => [
            'driver' => 'eloquent',
            'model' => App\AgencyLogin::class,
        ],

This is the model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class AgencyLogin extends Authenticatable
{
    use Notifiable;

    protected $table='ministry';

    protected $fillable = [
        'Username', 'Password',
    ];


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

The correct namespaces have been imported into the controller (it'd break otherwise). Auth is complicated so I'm really making an effort to understand it as this app has a lot of layers of Auth.

I have confirmed that the normal Auth functionality does work. Of course this gets weirder as if I allow the generic middleware Auth lock, it redirects from agencydash to the user home dashboard. Which I'm assuming is part of the Auth middlewhere functionality.



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